forked from mtusi2026/mtusi2026lab2
Implement lab2 messenger API with PostgreSQL Redis and Docker
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user