Add token creation methods

Signed-off-by: Nikolai Rodionov <allanger@badhouseplants.net>
This commit is contained in:
2026-05-13 21:32:10 +02:00
parent 35c6689a2c
commit eb339f5495
5 changed files with 104 additions and 2 deletions

View File

@@ -3,15 +3,28 @@ package controllers
import (
"context"
"database/sql"
"errors"
"time"
"gitea.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/hash"
"gitea.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/logger"
"gitea.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/token"
"github.com/google/uuid"
)
type TokenController struct {
DB *sql.DB
DB *sql.DB
HashCost int16
}
// Errors
var (
ErrServerError = errors.New("internal server error")
)
type TokenData struct {
UUID string
Name string
UserID string
CreatedAt time.Time
LastUserAt time.Time
@@ -23,7 +36,29 @@ type TokenData struct {
type Scopes struct{}
// Create a new token, store its hash in the database and return the token value
func (ctrl *TokenController) Create(ctx context.Context) (string, error) {
func (ctrl *TokenController) Create(ctx context.Context, data *TokenData) (string, error) {
id := uuid.NewString()
log := logger.FromContext(ctx).WithValues("uuid", id)
log.V(2).Info("Creating a new token")
tokenValue, err := token.GenerateToken()
if err != nil {
log.Error(err, "Couldn't create a token")
return "", ErrServerError
}
tokenHash, err := hash.HashPassword(tokenValue, int(ctrl.HashCost))
if err != nil {
log.Error(err, "Couldn't calculate token hash")
return "", ErrServerError
}
query := "INSERT INTO tokens (uuid, token_hash, user_id, scopes, created_at, expires_at) VALUES ($1, $2, $3, $4, $5, $6)"
if _, err := ctrl.DB.Query(query, id, tokenHash, "dummy", time.Now(), data.ExpiredAt); err != nil {
log.Error(err, "Couldn't insert a token in the database")
return "", ErrServerError
}
return "", nil
}