forked from mtusi2026/mtusi2026lab2
94 lines
1.6 KiB
Go
94 lines
1.6 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"mtusi2026lab2/internal/model"
|
|
)
|
|
|
|
type SessionService struct {
|
|
db *AuthStore
|
|
cache *SessionCache
|
|
}
|
|
|
|
func NewSessionService(
|
|
db *AuthStore,
|
|
cache *SessionCache,
|
|
) *SessionService {
|
|
return &SessionService{
|
|
db: db,
|
|
cache: cache,
|
|
}
|
|
}
|
|
|
|
func (s *SessionService) CreateSession(
|
|
ctx context.Context,
|
|
token string,
|
|
userID uuid.UUID,
|
|
createdAt time.Time,
|
|
expiresAt time.Time,
|
|
) error {
|
|
if err := s.db.CreateSession(
|
|
ctx, token, userID, createdAt, expiresAt,
|
|
); err != nil {
|
|
return err
|
|
}
|
|
|
|
if s.cache != nil {
|
|
cacheCtx, cancel := context.WithTimeout(
|
|
context.Background(), 2*time.Second,
|
|
)
|
|
defer cancel()
|
|
|
|
_ = s.cache.Set(cacheCtx, token, userID, expiresAt)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *SessionService) GetSessionUser(
|
|
ctx context.Context,
|
|
token string,
|
|
) (model.User, error) {
|
|
// PostgreSQL remains the source of truth.
|
|
user, err := s.db.GetSessionUser(ctx, token)
|
|
if err != nil {
|
|
return model.User{}, err
|
|
}
|
|
|
|
// Redis is best-effort and cannot extend a session.
|
|
if s.cache != nil {
|
|
cacheCtx, cancel := context.WithTimeout(
|
|
context.Background(), 2*time.Second,
|
|
)
|
|
defer cancel()
|
|
|
|
_, _, _ = s.cache.Get(cacheCtx, token)
|
|
}
|
|
|
|
return user, nil
|
|
}
|
|
|
|
func (s *SessionService) RevokeSession(
|
|
ctx context.Context,
|
|
token string,
|
|
) error {
|
|
if err := s.db.RevokeSession(ctx, token); err != nil {
|
|
return err
|
|
}
|
|
|
|
if s.cache != nil {
|
|
cacheCtx, cancel := context.WithTimeout(
|
|
context.Background(), 2*time.Second,
|
|
)
|
|
defer cancel()
|
|
|
|
_ = s.cache.Delete(cacheCtx, token)
|
|
}
|
|
|
|
return nil
|
|
}
|