forked from mtusi2026/mtusi2026lab2
99 lines
2.6 KiB
Go
99 lines
2.6 KiB
Go
package domain
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
type SessionStore struct {
|
|
store *Store
|
|
cache *SessionCache
|
|
ttl time.Duration
|
|
}
|
|
|
|
func NewSessionStore(store *Store, cache *SessionCache, ttl time.Duration) *SessionStore {
|
|
return &SessionStore{store: store, cache: cache, ttl: ttl}
|
|
}
|
|
|
|
func newToken() (string, error) {
|
|
b := make([]byte, 32) // 256 бит
|
|
if _, err := rand.Read(b); err != nil {
|
|
return "", classifyDBError(err)
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(b), nil
|
|
}
|
|
|
|
// Create — пишем сессию в БД (источник истины) и кэшируем публичные данные User.
|
|
func (s *SessionStore) Create(ctx context.Context, user User) (*Session, error) {
|
|
token, err := newToken()
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
expires := time.Now().UTC().Add(s.ttl)
|
|
if _, err := s.store.pool.Exec(ctx,
|
|
`INSERT INTO sessions (token, user_id, expires_at) VALUES ($1,$2,$3)`,
|
|
token, user.ID, expires); err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
if s.cache != nil {
|
|
s.cache.SetUser(ctx, user.ID, user, expires)
|
|
}
|
|
return &Session{
|
|
Token: token,
|
|
TokenType: "Bearer",
|
|
ExpiresAt: expires,
|
|
User: user,
|
|
}, nil
|
|
}
|
|
|
|
// Lookup ВСЕГДА обращается к PostgreSQL за фактом существования сессии.
|
|
// Кэш используется только для публичных данных User.
|
|
func (s *SessionStore) Lookup(ctx context.Context, token string) (*User, error) {
|
|
var (
|
|
userID string
|
|
expiresAt time.Time
|
|
)
|
|
err := s.store.pool.QueryRow(ctx,
|
|
`SELECT user_id, expires_at FROM sessions WHERE token=$1`, token,
|
|
).Scan(&userID, &expiresAt)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrUnauthorized
|
|
}
|
|
if err != nil {
|
|
return nil, classifyDBError(err)
|
|
}
|
|
if time.Now().UTC().After(expiresAt) {
|
|
_, _ = s.store.pool.Exec(ctx, `DELETE FROM sessions WHERE token=$1`, token)
|
|
return nil, ErrUnauthorized
|
|
}
|
|
|
|
if s.cache != nil {
|
|
if u, ok := s.cache.GetUser(ctx, userID); ok {
|
|
return &u, nil
|
|
}
|
|
}
|
|
|
|
u, err := s.store.GetUserByID(ctx, userID)
|
|
if err != nil {
|
|
return nil, ErrUnauthorized
|
|
}
|
|
if s.cache != nil {
|
|
s.cache.SetUser(ctx, userID, *u, expiresAt)
|
|
}
|
|
return u, nil
|
|
}
|
|
|
|
func (s *SessionStore) Revoke(ctx context.Context, token string) error {
|
|
// Достаём user_id, чтобы потом сбросить кэш User (не обязательно, но полезно).
|
|
var userID string
|
|
_ = s.store.pool.QueryRow(ctx,
|
|
`DELETE FROM sessions WHERE token=$1 RETURNING user_id`, token,
|
|
).Scan(&userID)
|
|
return nil
|
|
}
|