Add local auth: users, sessions, register/login/logout/me (#4)
Build image / build-and-push (push) Successful in 8s
Gadfly review (reusable) / review (pull_request) Successful in 7m7s
Adversarial Review (Gadfly) / review (pull_request) Successful in 7m7s

Implements pansy's local (email + password) authentication and the
session layer that OIDC (#5) will also reuse.

- store: users.go (create/get-by-id/get-by-email/count) and sessions.go
  (create/get/touch/delete/delete-expired), scanning the existing 0001
  schema.
- service: the business-logic seam. auth.go (Register/Login/session
  lifecycle/Providers) + password.go (argon2id, 64 MiB/1/4, PHC-encoded,
  constant-time verify) + service.go (Service, clock injection, token
  hashing). First user is admin; closed registration still allows the
  bootstrap user; unknown-email and wrong-password are indistinguishable
  (same error, same argon2 work via a dummy hash).
- api: POST /auth/register|login|logout, GET /auth/me|providers, plus a
  requireAuth middleware that resolves the HttpOnly session cookie
  (SameSite=Lax, Secure under https) to the actor. Handlers stay thin.
- main: wires the service and a periodic expired-session sweep; sessions
  are also dropped lazily on access. Sliding 30-day expiry.
- tests: service (register/login/expiry/renewal/cleanup, password) and
  api (cookie flow, middleware, validation, providers).

Verified end-to-end via curl: register -> me -> restart -> session
persists -> logout -> 401.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
2026-07-18 16:38:03 -04:00
co-authored by Claude Opus 4.8
parent 8305acf4b2
commit 0e41ccd95a
14 changed files with 1275 additions and 7 deletions
+80
View File
@@ -0,0 +1,80 @@
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
)
// CreateSession inserts a session row. The raw bearer token is never stored;
// s.TokenHash is its sha256 (computed by the service layer). ExpiresAt is an
// ISO-8601 UTC string, lexicographically comparable to the schema's timestamps.
func (d *DB) CreateSession(ctx context.Context, s *domain.Session) error {
_, err := d.sql.ExecContext(ctx,
`INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (?, ?, ?)`,
s.TokenHash, s.UserID, s.ExpiresAt,
)
if err != nil {
return fmt.Errorf("store: insert session: %w", err)
}
return nil
}
// GetSession returns the session for a token hash, or domain.ErrNotFound. It
// does not check expiry — that is the service layer's concern (which also
// implements sliding renewal).
func (d *DB) GetSession(ctx context.Context, tokenHash string) (*domain.Session, error) {
var s domain.Session
err := d.sql.QueryRowContext(ctx,
`SELECT token_hash, user_id, expires_at, created_at FROM sessions WHERE token_hash = ?`,
tokenHash,
).Scan(&s.TokenHash, &s.UserID, &s.ExpiresAt, &s.CreatedAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("store: get session: %w", err)
}
return &s, nil
}
// TouchSession moves a session's expiry forward (sliding-expiry renewal).
func (d *DB) TouchSession(ctx context.Context, tokenHash, expiresAt string) error {
_, err := d.sql.ExecContext(ctx,
`UPDATE sessions SET expires_at = ? WHERE token_hash = ?`, expiresAt, tokenHash,
)
if err != nil {
return fmt.Errorf("store: touch session: %w", err)
}
return nil
}
// DeleteSession removes a session (logout, or lazy cleanup of an expired one).
// Deleting a nonexistent session is not an error.
func (d *DB) DeleteSession(ctx context.Context, tokenHash string) error {
if _, err := d.sql.ExecContext(ctx,
`DELETE FROM sessions WHERE token_hash = ?`, tokenHash,
); err != nil {
return fmt.Errorf("store: delete session: %w", err)
}
return nil
}
// DeleteExpiredSessions removes every session that expired at or before now
// (an ISO-8601 UTC string) and returns how many rows were deleted.
func (d *DB) DeleteExpiredSessions(ctx context.Context, now string) (int64, error) {
res, err := d.sql.ExecContext(ctx,
`DELETE FROM sessions WHERE expires_at <= ?`, now,
)
if err != nil {
return 0, fmt.Errorf("store: delete expired sessions: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return 0, fmt.Errorf("store: expired sessions affected: %w", err)
}
return n, nil
}
+101
View File
@@ -0,0 +1,101 @@
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
)
// userColumns lists the users columns in the fixed order scanUser expects.
const userColumns = `id, email, display_name, password_hash, oidc_issuer, oidc_subject, is_admin, version, created_at, updated_at`
// scanner is satisfied by both *sql.Row and *sql.Rows, so scanUser works for
// single-row and multi-row queries alike.
type scanner interface {
Scan(dest ...any) error
}
// scanUser reads one users row. is_admin is stored as INTEGER 0/1 (the driver
// returns it as int64, which does not convert straight to bool), so it is read
// into an int and mapped.
func scanUser(s scanner) (*domain.User, error) {
var (
u domain.User
isAdmin int64
)
if err := s.Scan(
&u.ID, &u.Email, &u.DisplayName, &u.PasswordHash,
&u.OIDCIssuer, &u.OIDCSubject, &isAdmin, &u.Version,
&u.CreatedAt, &u.UpdatedAt,
); err != nil {
return nil, err
}
u.IsAdmin = isAdmin != 0
return &u, nil
}
// CreateUser inserts a new user and returns the stored row (with generated id
// and timestamps). PasswordHash/OIDCIssuer/OIDCSubject may be nil.
func (d *DB) CreateUser(ctx context.Context, u *domain.User) (*domain.User, error) {
res, err := d.sql.ExecContext(ctx,
`INSERT INTO users (email, display_name, password_hash, oidc_issuer, oidc_subject, is_admin)
VALUES (?, ?, ?, ?, ?, ?)`,
u.Email, u.DisplayName, u.PasswordHash, u.OIDCIssuer, u.OIDCSubject, boolToInt(u.IsAdmin),
)
if err != nil {
return nil, fmt.Errorf("store: insert user: %w", err)
}
id, err := res.LastInsertId()
if err != nil {
return nil, fmt.Errorf("store: user insert id: %w", err)
}
return d.GetUserByID(ctx, id)
}
// GetUserByID returns the user with the given id, or domain.ErrNotFound.
func (d *DB) GetUserByID(ctx context.Context, id int64) (*domain.User, error) {
u, err := scanUser(d.sql.QueryRowContext(ctx,
`SELECT `+userColumns+` FROM users WHERE id = ?`, id))
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("store: get user by id: %w", err)
}
return u, nil
}
// GetUserByEmail returns the user with the given email (case-insensitive via the
// column's NOCASE collation), or domain.ErrNotFound.
func (d *DB) GetUserByEmail(ctx context.Context, email string) (*domain.User, error) {
u, err := scanUser(d.sql.QueryRowContext(ctx,
`SELECT `+userColumns+` FROM users WHERE email = ?`, email))
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("store: get user by email: %w", err)
}
return u, nil
}
// CountUsers returns the number of user rows. Used to decide first-user-is-admin
// and to allow bootstrap registration when signup is otherwise closed.
func (d *DB) CountUsers(ctx context.Context) (int, error) {
var n int
if err := d.sql.QueryRowContext(ctx, `SELECT count(*) FROM users`).Scan(&n); err != nil {
return 0, fmt.Errorf("store: count users: %w", err)
}
return n, nil
}
// boolToInt maps a Go bool to the 0/1 SQLite stores for INTEGER "boolean" columns.
func boolToInt(b bool) int {
if b {
return 1
}
return 0
}