Исправил отзыв сессии без доверия к кэшу и добавил недостающие тесты

This commit is contained in:
gera
2026-11-19 21:38:31 +03:00
parent 27fafc6725
commit 583013fa06
12 changed files with 597 additions and 160 deletions
+10 -51
View File
@@ -49,7 +49,6 @@ type errorBody struct {
type App struct {
db *pgxpool.Pool
cache *Cache
log *slog.Logger
ready atomic.Bool
sessionTTL time.Duration
@@ -60,8 +59,8 @@ type App struct {
fault string
}
func NewApp(db *pgxpool.Pool, cache *Cache, log *slog.Logger, sessionTTL, idempotencyTTL time.Duration, store *Store, lim limits) *App {
a := &App{db: db, cache: cache, log: log, sessionTTL: sessionTTL, idempotencyTTL: idempotencyTTL, store: store, limits: lim, uploads: make(chan struct{}, lim.uploadSlots), fault: os.Getenv("FAULT_POINT")}
func NewApp(db *pgxpool.Pool, log *slog.Logger, sessionTTL, idempotencyTTL time.Duration, store *Store, lim limits) *App {
a := &App{db: db, log: log, sessionTTL: sessionTTL, idempotencyTTL: idempotencyTTL, store: store, limits: lim, uploads: make(chan struct{}, lim.uploadSlots), fault: os.Getenv("FAULT_POINT")}
a.ready.Store(true)
return a
}
@@ -268,23 +267,6 @@ func userJSON(u *User) map[string]any {
}
}
func (a *App) getUserByID(ctx context.Context, id string) (*User, error) {
ctx, cancel := dbCtx(ctx)
defer cancel()
var u User
err := a.db.QueryRow(ctx, `
select id::text, username, display_name, password_hash, created_at
from users where id = $1::uuid`, id).Scan(
&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &u, nil
}
func (a *App) authUser(w http.ResponseWriter, r *http.Request) (*User, string) {
token, ok := parseBearer(r.Header.Get("Authorization"))
if !ok {
@@ -293,26 +275,15 @@ func (a *App) authUser(w http.ResponseWriter, r *http.Request) (*User, string) {
}
hash, hashHex := tokenHash(token)
if cs, hit := a.cache.GetSession(r.Context(), hashHex); hit {
u, err := a.getUserByID(r.Context(), cs.UserID)
if err != nil {
a.writeErr(w, reqIDFrom(r), 503, "unavailable", "database unavailable")
return nil, ""
}
if u == nil {
a.writeUnauthorized(w, r, "Bearer")
return nil, ""
}
return u, hashHex
}
ctx, cancel := dbCtx(r.Context())
defer cancel()
var userID string
var u User
var expiresAt time.Time
err := a.db.QueryRow(ctx, `
select user_id::text, expires_at from sessions
where token_hash = $1 and expires_at > now()`, hash).Scan(&userID, &expiresAt)
select u.id::text, u.username, u.display_name, u.password_hash, u.created_at, s.expires_at
from sessions s join users u on u.id = s.user_id
where s.token_hash = $1 and s.expires_at > now()`, hash).Scan(
&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt, &expiresAt)
if errors.Is(err, pgx.ErrNoRows) {
a.writeUnauthorized(w, r, "Bearer")
return nil, ""
@@ -321,17 +292,7 @@ func (a *App) authUser(w http.ResponseWriter, r *http.Request) (*User, string) {
a.writeErr(w, reqIDFrom(r), 503, "unavailable", "database unavailable")
return nil, ""
}
u, err := a.getUserByID(r.Context(), userID)
if err != nil {
a.writeErr(w, reqIDFrom(r), 503, "unavailable", "database unavailable")
return nil, ""
}
if u == nil {
a.writeUnauthorized(w, r, "Bearer")
return nil, ""
}
a.cache.SetSession(r.Context(), hashHex, userID, expiresAt)
return u, hashHex
return &u, hashHex
}
func (a *App) handleCreateUser(w http.ResponseWriter, r *http.Request) {
@@ -423,7 +384,7 @@ func (a *App) handleCreateSession(w http.ResponseWriter, r *http.Request) {
a.writeUnauthorized(w, r, "Basic")
return
}
token, hash, hashHex, err := newToken()
token, hash, _, err := newToken()
if err != nil {
a.writeErr(w, reqID, 500, "internal_error", "internal error")
return
@@ -437,7 +398,6 @@ func (a *App) handleCreateSession(w http.ResponseWriter, r *http.Request) {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
a.cache.SetSession(r.Context(), hashHex, u.ID, expiresAt)
a.writeJSON(w, 201, map[string]any{
"token": token,
"token_type": "Bearer",
@@ -453,7 +413,7 @@ func (a *App) handleRevokeSession(w http.ResponseWriter, r *http.Request) {
a.writeUnauthorized(w, r, "Bearer")
return
}
hash, hashHex := tokenHash(token)
hash, _ := tokenHash(token)
ctx, cancel := dbCtx(r.Context())
defer cancel()
tag, err := a.db.Exec(ctx, `
@@ -462,7 +422,6 @@ func (a *App) handleRevokeSession(w http.ResponseWriter, r *http.Request) {
a.writeErr(w, reqID, 503, "unavailable", "database unavailable")
return
}
a.cache.DelSession(r.Context(), hashHex)
if tag.RowsAffected() == 0 {
a.writeUnauthorized(w, r, "Bearer")
return