271 lines
8.6 KiB
Go
271 lines
8.6 KiB
Go
// Package auth contains the shared single-account/session persistence used by
|
|
// the self-hosted web services. HTTP handlers, cookies, authorization policy,
|
|
// and application-specific roles remain in each service.
|
|
package auth
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// User is the shared account record. PasswordHash should never be serialized
|
|
// into an API response.
|
|
type User struct {
|
|
ID int64
|
|
Username string
|
|
Email string
|
|
PasswordHash string
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
}
|
|
|
|
// Store performs common auth persistence against a caller-owned pool.
|
|
type Store struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
// NewStore creates an auth store. The pool remains owned by the caller.
|
|
func NewStore(pool *pgxpool.Pool) *Store {
|
|
return &Store{pool: pool}
|
|
}
|
|
|
|
// SchemaOptions controls optional auth schema features.
|
|
type SchemaOptions struct {
|
|
// SingleUser adds a constraint that allows exactly one account. This is the
|
|
// default model for GameStream, SimpleCollection, and home-server tools.
|
|
SingleUser bool
|
|
// APITokens creates the optional per-user API token table.
|
|
APITokens bool
|
|
}
|
|
|
|
// DefaultSchemaOptions returns the single-account schema used by most small
|
|
// self-hosted services.
|
|
func DefaultSchemaOptions() SchemaOptions {
|
|
return SchemaOptions{SingleUser: true}
|
|
}
|
|
|
|
// EnsureSchema creates the shared auth tables and indexes idempotently.
|
|
func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions) error {
|
|
if pool == nil {
|
|
return errors.New("auth postgres pool is nil")
|
|
}
|
|
|
|
_, err := pool.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS auth_users (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
username TEXT NOT NULL UNIQUE,
|
|
email TEXT NOT NULL DEFAULT '',
|
|
password_hash TEXT NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
|
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
|
|
ON auth_users (lower(email)) WHERE email <> '';
|
|
|
|
CREATE TABLE IF NOT EXISTS auth_sessions (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
|
token_hash TEXT NOT NULL UNIQUE,
|
|
expires_at TIMESTAMPTZ NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
|
|
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
|
|
`)
|
|
if err != nil {
|
|
return fmt.Errorf("ensure auth schema: %w", err)
|
|
}
|
|
|
|
if options.SingleUser {
|
|
if _, err := pool.Exec(ctx, `
|
|
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
|
`); err != nil {
|
|
return fmt.Errorf("ensure single-user auth constraint: %w", err)
|
|
}
|
|
}
|
|
|
|
if options.APITokens {
|
|
if _, err := pool.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS auth_api_tokens (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
|
token_hash TEXT NOT NULL UNIQUE,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS auth_api_tokens_user_idx ON auth_api_tokens (user_id);
|
|
`); err != nil {
|
|
return fmt.Errorf("ensure auth API-token schema: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CountUsers returns the number of configured accounts.
|
|
func (s *Store) CountUsers(ctx context.Context) (int, error) {
|
|
if err := s.validate(); err != nil {
|
|
return 0, err
|
|
}
|
|
var count int
|
|
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM auth_users`).Scan(&count); err != nil {
|
|
return 0, fmt.Errorf("count auth users: %w", err)
|
|
}
|
|
return count, nil
|
|
}
|
|
|
|
// CreateUser inserts an account and returns ErrUserExists for a uniqueness
|
|
// conflict, including the single-user constraint.
|
|
func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash string) (*User, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
var user User
|
|
err := s.pool.QueryRow(ctx, `
|
|
INSERT INTO auth_users (username, email, password_hash, updated_at)
|
|
VALUES ($1, $2, $3, now())
|
|
RETURNING id, username, email, password_hash, created_at, updated_at
|
|
`, username, email, passwordHash).Scan(
|
|
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt, &user.UpdatedAt,
|
|
)
|
|
if err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
return nil, ErrUserExists
|
|
}
|
|
return nil, fmt.Errorf("create auth user: %w", err)
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
// FindByIdentifier looks up a user by exact username or case-insensitive email.
|
|
func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
return s.find(ctx, `
|
|
SELECT id, username, email, password_hash, created_at, updated_at
|
|
FROM auth_users
|
|
WHERE username = $1 OR lower(email) = lower($1)
|
|
`, identifier)
|
|
}
|
|
|
|
// FindByID looks up a user by primary key.
|
|
func (s *Store) FindByID(ctx context.Context, id int64) (*User, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
return s.find(ctx, `
|
|
SELECT id, username, email, password_hash, created_at, updated_at
|
|
FROM auth_users WHERE id = $1
|
|
`, id)
|
|
}
|
|
|
|
// UpdateCredentials updates the normalized account fields and password hash.
|
|
func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email, passwordHash string) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
_, err := s.pool.Exec(ctx, `
|
|
UPDATE auth_users
|
|
SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
|
WHERE id = $4
|
|
`, username, email, passwordHash, id)
|
|
if err != nil {
|
|
return fmt.Errorf("update auth credentials: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CreateSession stores a hash of a session token until expiresAt.
|
|
func (s *Store) CreateSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
_, err := s.pool.Exec(ctx, `
|
|
INSERT INTO auth_sessions (user_id, token_hash, expires_at)
|
|
VALUES ($1, $2, $3)
|
|
`, userID, tokenHash, expiresAt)
|
|
if err != nil {
|
|
return fmt.Errorf("create auth session: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// FindSessionUser resolves an unexpired session to its user.
|
|
func (s *Store) FindSessionUser(ctx context.Context, tokenHash string) (*User, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
return s.find(ctx, `
|
|
SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at
|
|
FROM auth_sessions s
|
|
JOIN auth_users u ON u.id = s.user_id
|
|
WHERE s.token_hash = $1 AND s.expires_at > now()
|
|
`, tokenHash)
|
|
}
|
|
|
|
// DeleteSession removes one session, typically during logout.
|
|
func (s *Store) DeleteSession(ctx context.Context, tokenHash string) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE token_hash = $1`, tokenHash); err != nil {
|
|
return fmt.Errorf("delete auth session: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteSessionsForUser invalidates all sessions after credential changes.
|
|
func (s *Store) DeleteSessionsForUser(ctx context.Context, userID int64) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID); err != nil {
|
|
return fmt.Errorf("delete auth sessions for user: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteExpiredSessions performs the periodic session cleanup shared by the
|
|
// services. A caller can run it from its own scheduler.
|
|
func (s *Store) DeleteExpiredSessions(ctx context.Context) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
|
return fmt.Errorf("delete expired auth sessions: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var ErrUserExists = errors.New("auth user already exists")
|
|
|
|
func (s *Store) validate() error {
|
|
if s == nil || s.pool == nil {
|
|
return errors.New("auth store has no postgres pool")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Store) find(ctx context.Context, query string, arg any) (*User, error) {
|
|
var user User
|
|
err := s.pool.QueryRow(ctx, query, arg).Scan(
|
|
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt, &user.UpdatedAt,
|
|
)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("find auth user: %w", err)
|
|
}
|
|
return &user, nil
|
|
}
|