feat(auth): cache sessions in redis with postgres fallback

This commit is contained in:
kk10
2026-10-06 15:36:52 +03:00
parent f7e1866d4e
commit 5bd210b59d
7 changed files with 126 additions and 15 deletions
+55 -4
View File
@@ -3,6 +3,7 @@ package service
import (
"context"
"errors"
"log/slog"
"time"
"mtusi2026-messenger/internal/credentials"
@@ -11,8 +12,12 @@ import (
"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")
@@ -27,13 +32,17 @@ type authQueries interface {
type AuthService struct {
q authQueries
cache *goredis.Client
sessionTTL time.Duration
log *slog.Logger
}
func NewAuthService(q authQueries, sessionTTL time.Duration) *AuthService {
func NewAuthService(q authQueries, cache *goredis.Client, sessionTTL time.Duration, log *slog.Logger) *AuthService {
return &AuthService{
q: q,
cache: cache,
sessionTTL: sessionTTL,
log: log,
}
}
@@ -81,7 +90,24 @@ func (s *AuthService) Login(ctx context.Context, username, plain string) (model.
}
func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
userID, err := s.q.GetSessionUserID(ctx, credentials.HashToken(token))
tokenHash := credentials.HashToken(token)
key := cacheKey(tokenHash)
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
val, err := s.cache.Get(cctx, key).Result()
cancel()
if err == nil {
id, perr := uuid.Parse(val)
if perr == nil {
return id, nil
}
s.log.Warn("session cache value is not a uuid", "error", perr)
} else if !errors.Is(err, goredis.Nil) {
s.log.Warn("session cache get failed, falling back to database", "error", err)
}
userID, err := s.q.GetSessionUserID(ctx, tokenHash)
if postgres.IsNotFound(err) {
return uuid.Nil, ErrUnauthorized
}
@@ -89,17 +115,42 @@ func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID
return uuid.Nil, err
}
cctx, cancel = context.WithTimeout(ctx, cacheOpTimeout)
if err := s.cache.Set(cctx, key, userID.String(), s.cacheTTL()).Err(); err != nil {
s.log.Warn("session cache set failed", "error", err)
}
cancel()
return userID, nil
}
func (s *AuthService) Logout(ctx context.Context, token string) error {
n, err := s.q.DeleteSession(ctx, credentials.HashToken(token))
tokenHash := credentials.HashToken(token)
n, err := s.q.DeleteSession(ctx, tokenHash)
if err != nil {
return err
}
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
defer cancel()
if err := s.cache.Del(cctx, cacheKey(tokenHash)).Err(); err != nil {
s.log.Warn("session cache delete failed", "error", err)
}
if n == 0 {
return ErrUnauthorized
}
return nil
}
func cacheKey(tokenHash string) string {
return "session:" + tokenHash
}
func (s *AuthService) cacheTTL() time.Duration {
if s.sessionTTL < sessionCacheTTL {
return s.sessionTTL
}
return sessionCacheTTL
}