package db import ( "context" "database/sql" "errors" "time" ) // PasswordResetRepo stores single-use password-reset tokens. // // Only the SHA-256 hash of the token is persisted — the plain value exists // solely inside the emailed link — so a database leak does not hand out // working reset URLs. Issuing a token deletes the user's previous ones (the // newest link wins), and consumption is one transaction guarded by row lock // so two concurrent resets with the same token cannot both succeed. type PasswordResetRepo struct{ db *DB } func NewPasswordResetRepo(d *DB) *PasswordResetRepo { return &PasswordResetRepo{db: d} } // Create stores a fresh token hash for the user, replacing any outstanding // tokens, and sweeps that user's expired/used rows to keep the table small. func (r *PasswordResetRepo) Create(ctx context.Context, userID, tokenHash string, expiresAt time.Time) error { return Transaction(ctx, r.db, func(tx *sql.Tx) error { if _, err := tx.ExecContext(ctx, `DELETE FROM "PasswordResetToken" WHERE "userId"=$1`, userID); err != nil { return err } _, err := tx.ExecContext(ctx, `INSERT INTO "PasswordResetToken"(id,"userId","tokenHash","expiresAt") VALUES($1,$2,$3,$4)`, NewID(), userID, tokenHash, expiresAt) return err }) } // Consume marks a valid (unexpired, unused) token as used and returns the // owning user id. Anything else — unknown hash, expired, already used — // reports ErrNotFound without revealing which case applied. func (r *PasswordResetRepo) Consume(ctx context.Context, tokenHash string) (string, error) { var userID string err := Transaction(ctx, r.db, func(tx *sql.Tx) error { err := tx.QueryRowContext(ctx, `SELECT "userId" FROM "PasswordResetToken" WHERE "tokenHash"=$1 AND "usedAt" IS NULL AND "expiresAt">now() FOR UPDATE`, tokenHash).Scan(&userID) if errors.Is(err, sql.ErrNoRows) { return ErrNotFound } if err != nil { return err } _, err = tx.ExecContext(ctx, `UPDATE "PasswordResetToken" SET "usedAt"=now() WHERE "tokenHash"=$1`, tokenHash) return err }) if err != nil { return "", err } return userID, nil }