89 lines
2.3 KiB
Go
89 lines
2.3 KiB
Go
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
|
|
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
|
|
RevokedAt time.Time
|
|
ExpiredAt time.Time
|
|
Scopes *Scopes
|
|
}
|
|
|
|
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, 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
|
|
}
|
|
|
|
// Update token name or permissions, other changes are ignored by this method
|
|
func (ctrl *TokenController) Update(ctx context.Context) (string, error) {
|
|
return "", nil
|
|
}
|
|
|
|
// ForceExpiration of a token, so it can no longer be used
|
|
func (ctrl *TokenController) ForceExpiration(ctx context.Context) error {
|
|
return nil
|
|
}
|
|
|
|
// Regenerate a token and get a new value
|
|
func (ctrl *TokenController) Regenerate(ctx context.Context) (string, error) {
|
|
return "", nil
|
|
}
|
|
|
|
// Get an existing token data
|
|
func (ctrl *TokenController) Get(ctx context.Context, uuid string) error {
|
|
return nil
|
|
}
|
|
|
|
// List all available token
|
|
func (ctrl *TokenController) List(ctx context.Context) error {
|
|
return nil
|
|
}
|