forked from mtusi2026/mtusi2026lab2
feat:level4
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
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 "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// Create создаёт сессию: сначала пишем в PostgreSQL (источник истины), затем кэш.
|
||||
func (s *SessionStore) Create(ctx context.Context, user User) (*Session, error) {
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
expires := time.Now().UTC().Add(s.ttl)
|
||||
_, err = s.store.pool.Exec(ctx,
|
||||
`INSERT INTO sessions (token, user_id, expires_at) VALUES ($1,$2,$3)`,
|
||||
token, user.ID, expires)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Set(ctx, token, user, expires)
|
||||
}
|
||||
return &Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expires,
|
||||
User: user,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Lookup проверяет токен. Сначала кэш; при miss — PostgreSQL.
|
||||
// Истёкшие сессии удаляются лениво.
|
||||
func (s *SessionStore) Lookup(ctx context.Context, token string) (*User, error) {
|
||||
if s.cache != nil {
|
||||
if u, ok := s.cache.Get(ctx, token); ok {
|
||||
return &u, nil
|
||||
}
|
||||
}
|
||||
|
||||
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, err
|
||||
}
|
||||
if time.Now().UTC().After(expiresAt) {
|
||||
_, _ = s.store.pool.Exec(ctx, `DELETE FROM sessions WHERE token=$1`, token)
|
||||
if s.cache != nil {
|
||||
s.cache.Del(ctx, token)
|
||||
}
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
|
||||
u, err := s.store.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Set(ctx, token, *u, expiresAt)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// Revoke удаляет сессию из БД и кэша.
|
||||
func (s *SessionStore) Revoke(ctx context.Context, token string) error {
|
||||
if _, err := s.store.pool.Exec(ctx, `DELETE FROM sessions WHERE token=$1`, token); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Del(ctx, token)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user