forked from mtusi2026/mtusi2026lab3
184 lines
4.4 KiB
Go
184 lines
4.4 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"mtusi2026-messenger/internal/credentials"
|
|
"mtusi2026-messenger/internal/db"
|
|
"mtusi2026-messenger/internal/model"
|
|
"mtusi2026-messenger/internal/postgres"
|
|
|
|
"github.com/google/uuid"
|
|
goredis "github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
const sessionCacheTTL = 60 * time.Second
|
|
const cacheOpTimeout = 300 * time.Millisecond
|
|
|
|
var (
|
|
ErrInvalidCredentials = errors.New("invalid credentials")
|
|
ErrUnauthorized = errors.New("unauthorized")
|
|
)
|
|
|
|
type authQueries interface {
|
|
CreateSession(ctx context.Context, arg db.CreateSessionParams) error
|
|
DeleteSession(ctx context.Context, tokenHash string) (int64, error)
|
|
GetActiveSession(ctx context.Context, tokenHash string) (db.GetActiveSessionRow, error)
|
|
GetUserByUsername(ctx context.Context, username string) (db.User, error)
|
|
}
|
|
|
|
type AuthService struct {
|
|
q authQueries
|
|
cache *goredis.Client
|
|
sessionTTL time.Duration
|
|
log *slog.Logger
|
|
}
|
|
|
|
func NewAuthService(q authQueries, cache *goredis.Client, sessionTTL time.Duration, log *slog.Logger) *AuthService {
|
|
return &AuthService{
|
|
q: q,
|
|
cache: cache,
|
|
sessionTTL: sessionTTL,
|
|
log: log,
|
|
}
|
|
}
|
|
|
|
var dummyHash, _ = credentials.HashPassword("dummy-password-for-timing")
|
|
|
|
func (s *AuthService) Login(ctx context.Context, username, plain string) (model.Session, error) {
|
|
user, err := s.q.GetUserByUsername(ctx, username)
|
|
if postgres.IsNotFound(err) {
|
|
_ = credentials.VerifyPassword(dummyHash, plain)
|
|
return model.Session{}, ErrInvalidCredentials
|
|
}
|
|
if err != nil {
|
|
return model.Session{}, err
|
|
}
|
|
|
|
if err := credentials.VerifyPassword(user.PasswordHash, plain); err != nil {
|
|
if errors.Is(err, credentials.ErrPasswordMismatch) {
|
|
return model.Session{}, ErrInvalidCredentials
|
|
}
|
|
return model.Session{}, err
|
|
}
|
|
|
|
token := credentials.NewToken()
|
|
expiresAt := time.Now().UTC().Add(s.sessionTTL)
|
|
|
|
err = s.q.CreateSession(ctx, db.CreateSessionParams{
|
|
TokenHash: credentials.HashToken(token),
|
|
UserID: user.ID,
|
|
ExpiresAt: expiresAt,
|
|
})
|
|
if err != nil {
|
|
return model.Session{}, err
|
|
}
|
|
|
|
return model.Session{
|
|
Token: token,
|
|
ExpiresAt: expiresAt,
|
|
User: model.User{
|
|
ID: user.ID,
|
|
Username: user.Username,
|
|
DisplayName: user.DisplayName,
|
|
CreatedAt: user.CreatedAt.UTC(),
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
|
|
tokenHash := credentials.HashToken(token)
|
|
key := cacheKey(tokenHash)
|
|
|
|
if id, ok := s.cacheGet(ctx, key); ok {
|
|
return id, nil
|
|
}
|
|
|
|
row, err := s.q.GetActiveSession(ctx, tokenHash)
|
|
if postgres.IsNotFound(err) {
|
|
return uuid.Nil, ErrUnauthorized
|
|
}
|
|
if err != nil {
|
|
return uuid.Nil, err
|
|
}
|
|
|
|
s.cacheSet(ctx, key, row.UserID, min(time.Until(row.ExpiresAt), sessionCacheTTL))
|
|
|
|
return row.UserID, nil
|
|
}
|
|
|
|
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
|
tokenHash := credentials.HashToken(token)
|
|
|
|
n, err := s.q.DeleteSession(ctx, tokenHash)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
s.cacheDel(ctx, cacheKey(tokenHash))
|
|
|
|
if n == 0 {
|
|
return ErrUnauthorized
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func cacheKey(tokenHash string) string {
|
|
return "session:" + tokenHash
|
|
}
|
|
|
|
func (s *AuthService) cacheGet(ctx context.Context, key string) (uuid.UUID, bool) {
|
|
if s.cache == nil {
|
|
return uuid.Nil, false
|
|
}
|
|
|
|
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
|
defer cancel()
|
|
|
|
val, err := s.cache.Get(cctx, key).Result()
|
|
switch {
|
|
case err == nil:
|
|
id, perr := uuid.Parse(val)
|
|
if perr != nil {
|
|
s.log.Warn("session cache value is not a uuid", "error", perr)
|
|
return uuid.Nil, false
|
|
}
|
|
s.log.Debug("session cache hit")
|
|
return id, true
|
|
case errors.Is(err, goredis.Nil):
|
|
s.log.Debug("session cache miss")
|
|
default:
|
|
s.log.Warn("session cache get failed, falling back to database", "error", err)
|
|
}
|
|
return uuid.Nil, false
|
|
}
|
|
|
|
func (s *AuthService) cacheSet(ctx context.Context, key string, id uuid.UUID, ttl time.Duration) {
|
|
if s.cache == nil || ttl <= 0 {
|
|
return
|
|
}
|
|
|
|
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
|
defer cancel()
|
|
|
|
if err := s.cache.Set(cctx, key, id.String(), ttl).Err(); err != nil {
|
|
s.log.Warn("session cache set failed", "error", err)
|
|
}
|
|
}
|
|
|
|
func (s *AuthService) cacheDel(ctx context.Context, key string) {
|
|
if s.cache == nil {
|
|
return
|
|
}
|
|
|
|
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
|
|
defer cancel()
|
|
|
|
if err := s.cache.Del(cctx, key).Err(); err != nil {
|
|
s.log.Warn("session cache delete failed", "error", err)
|
|
}
|
|
}
|