This commit is contained in:
@@ -37,38 +37,44 @@ func (s *SessionService) CreateSession(
|
||||
return err
|
||||
}
|
||||
|
||||
// Populate the profile cache best-effort after the authoritative INSERT.
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(
|
||||
context.Background(), 2*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
_ = s.cache.Set(cacheCtx, token, userID, expiresAt)
|
||||
user, err := s.db.GetUserByID(ctx, userID)
|
||||
if err == nil {
|
||||
cacheCtx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
|
||||
_ = s.cache.Set(cacheCtx, token, user, expiresAt)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
func (s *SessionService) GetSessionUser(ctx context.Context, token string) (model.User, error) {
|
||||
// A cheap indexed PostgreSQL check on EVERY request enforces expiry and logout,
|
||||
// even if Redis contains a stale value or its deletion fails.
|
||||
userID, err := s.db.GetActiveSessionUserID(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)
|
||||
cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
cached, hit, err := s.cache.Get(cacheCtx, token)
|
||||
cancel()
|
||||
if err == nil && hit && cached.ID == userID {
|
||||
return cached, nil
|
||||
}
|
||||
}
|
||||
user, err := s.db.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
|
||||
// Conservative short TTL on read-through; session lifetime is still checked in PostgreSQL.
|
||||
_ = s.cache.Set(cacheCtx, token, user, time.Now().Add(30*time.Second))
|
||||
cancel()
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
@@ -82,7 +88,7 @@ func (s *SessionService) RevokeSession(
|
||||
|
||||
if s.cache != nil {
|
||||
cacheCtx, cancel := context.WithTimeout(
|
||||
context.Background(), 2*time.Second,
|
||||
context.Background(), 250*time.Millisecond,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user