2026-08-04 15:17:15 +02:00
// 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
2026-08-05 14:57:01 +02:00
Role Role
2026-08-04 15:17:15 +02:00
CreatedAt time . Time
UpdatedAt time . Time
2026-09-04 15:02:16 +02:00
// LastLoginAt is nil until the account's first successful POST
// /api/login (registration alone does not set it - see UpdateLastLogin).
LastLoginAt * time . Time
2026-08-04 15:17:15 +02:00
}
// 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,
2026-08-05 14:57:01 +02:00
role TEXT NOT NULL DEFAULT 'user',
totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
2026-08-04 15:17:15 +02:00
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
2026-09-04 15:02:16 +02:00
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_login_at TIMESTAMPTZ
2026-08-04 15:17:15 +02:00
);
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
2026-08-05 14:57:01 +02:00
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
2026-08-04 15:17:15 +02:00
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();
2026-09-04 15:02:16 +02:00
-- last_login_at is nullable (NULL means "never logged in" - registration
-- alone does not count, only a successful POST /api/login) and has no
-- DEFAULT, unlike every other column here.
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
2026-08-05 14:57:01 +02:00
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
2026-08-04 15:17:15 +02:00
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 )
}
2026-08-05 14:57:01 +02:00
} else if _ , err := pool . Exec ( ctx , `DROP INDEX IF EXISTS auth_users_singleton_idx` ); err != nil {
return fmt . Errorf ( "remove single-user auth constraint: %w" , err )
2026-08-04 15:17:15 +02:00
}
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
}
2026-08-05 14:57:01 +02:00
// TOTPState is the private provisioning state for one account. Secret must
// never be included in an API response.
type TOTPState struct {
Secret string
Enabled bool
}
// GetTOTPState reads the stored TOTP provisioning state for an account.
func ( s * Store ) GetTOTPState ( ctx context . Context , userID int64 ) ( TOTPState , error ) {
if err := s . validate (); err != nil {
return TOTPState {}, err
}
var state TOTPState
err := s . pool . QueryRow ( ctx , `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1` , userID ). Scan ( & state . Secret , & state . Enabled )
if errors . Is ( err , pgx . ErrNoRows ) {
return TOTPState {}, nil
}
if err != nil {
return TOTPState {}, fmt . Errorf ( "get TOTP state: %w" , err )
}
return state , nil
}
// SetTOTPSecret stores a pending secret without enabling two-factor auth.
func ( s * Store ) SetTOTPSecret ( ctx context . Context , userID int64 , secret string ) error {
if err := s . validate (); err != nil {
return err
}
_ , err := s . pool . Exec ( ctx , `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2` , secret , userID )
if err != nil {
return fmt . Errorf ( "set TOTP secret: %w" , err )
}
return nil
}
// EnableTOTP marks a previously provisioned secret as active.
func ( s * Store ) EnableTOTP ( ctx context . Context , userID int64 ) error {
if err := s . validate (); err != nil {
return err
}
_ , err := s . pool . Exec ( ctx , `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''` , userID )
if err != nil {
return fmt . Errorf ( "enable TOTP: %w" , err )
}
return nil
}
// DisableTOTP clears both the active and pending TOTP secret.
func ( s * Store ) DisableTOTP ( ctx context . Context , userID int64 ) error {
if err := s . validate (); err != nil {
return err
}
_ , err := s . pool . Exec ( ctx , `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1` , userID )
if err != nil {
return fmt . Errorf ( "disable TOTP: %w" , err )
}
return nil
}
2026-08-04 15:17:15 +02:00
// 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 , `
2026-08-05 14:57:01 +02:00
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3,
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END,
now())
2026-09-04 15:02:16 +02:00
RETURNING id, username, email, password_hash, role, created_at, updated_at, last_login_at
2026-08-04 15:17:15 +02:00
` , username , email , passwordHash ). Scan (
2026-09-04 15:02:16 +02:00
& user . ID , & user . Username , & user . Email , & user . PasswordHash , & user . Role , & user . CreatedAt , & user . UpdatedAt , & user . LastLoginAt ,
2026-08-04 15:17:15 +02:00
)
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 , `
2026-09-04 15:02:16 +02:00
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
2026-08-04 15:17:15 +02:00
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 , `
2026-09-04 15:02:16 +02:00
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
2026-08-04 15:17:15 +02:00
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
}
2026-08-05 14:57:01 +02:00
// ListUsers returns the non-secret account fields used by the shared user
// management screen.
func ( s * Store ) ListUsers ( ctx context . Context ) ([] User , error ) {
if err := s . validate (); err != nil {
return nil , err
}
rows , err := s . pool . Query ( ctx , `
2026-09-04 15:02:16 +02:00
SELECT id, username, email, role, created_at, updated_at, last_login_at
2026-08-05 14:57:01 +02:00
FROM auth_users ORDER BY created_at, id
` )
if err != nil {
return nil , fmt . Errorf ( "list auth users: %w" , err )
}
defer rows . Close ()
users := make ([] User , 0 )
for rows . Next () {
var user User
2026-09-04 15:02:16 +02:00
if err := rows . Scan ( & user . ID , & user . Username , & user . Email , & user . Role , & user . CreatedAt , & user . UpdatedAt , & user . LastLoginAt ); err != nil {
2026-08-05 14:57:01 +02:00
return nil , fmt . Errorf ( "scan auth user: %w" , err )
}
users = append ( users , user )
}
return users , rows . Err ()
}
// CreateManagedUser creates a user with an explicit, already-authorized role.
func ( s * Store ) CreateManagedUser ( ctx context . Context , username , email , passwordHash string , role Role ) ( * User , error ) {
if err := s . validate (); err != nil {
return nil , err
}
role = NormalizeRole ( string ( role ))
var user User
err := s . pool . QueryRow ( ctx , `
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3, $4, now())
2026-09-04 15:02:16 +02:00
RETURNING id, username, email, password_hash, role, created_at, updated_at, last_login_at
2026-08-05 14:57:01 +02:00
` , username , email , passwordHash , role ). Scan (
2026-09-04 15:02:16 +02:00
& user . ID , & user . Username , & user . Email , & user . PasswordHash , & user . Role , & user . CreatedAt , & user . UpdatedAt , & user . LastLoginAt ,
2026-08-05 14:57:01 +02:00
)
if err != nil {
var pgErr * pgconn . PgError
if errors . As ( err , & pgErr ) && pgErr . Code == "23505" {
return nil , ErrUserExists
}
return nil , fmt . Errorf ( "create managed auth user: %w" , err )
}
return & user , nil
}
// UpdateUser updates account fields and, when supplied, its role.
func ( s * Store ) UpdateUser ( ctx context . Context , id int64 , username , email , passwordHash string , role * Role ) error {
if err := s . validate (); err != nil {
return err
}
if role == nil {
return s . UpdateCredentials ( ctx , id , username , email , passwordHash )
}
* role = NormalizeRole ( string ( * role ))
_ , err := s . pool . Exec ( ctx , `
UPDATE auth_users
SET username = $1, email = $2, password_hash = $3, role = $4, updated_at = now()
WHERE id = $5
` , username , email , passwordHash , * role , id )
if err != nil {
return fmt . Errorf ( "update managed auth user: %w" , err )
}
return nil
}
2026-09-04 15:02:16 +02:00
// UpdateLastLogin stamps last_login_at to now(). Callers should treat this as
// best-effort: an already-successful login (the session is live) shouldn't
// fail because this update didn't - see AuthGuard's handleLogin for the
// intended "log and continue" pattern.
func ( s * Store ) UpdateLastLogin ( ctx context . Context , id int64 ) error {
if err := s . validate (); err != nil {
return err
}
if _ , err := s . pool . Exec ( ctx , `UPDATE auth_users SET last_login_at = now() WHERE id = $1` , id ); err != nil {
return fmt . Errorf ( "update last login: %w" , err )
}
return nil
}
2026-08-05 14:57:01 +02:00
// DeleteUser removes one account. Callers enforce the superadmin/self policy.
func ( s * Store ) DeleteUser ( ctx context . Context , id int64 ) error {
if err := s . validate (); err != nil {
return err
}
if _ , err := s . pool . Exec ( ctx , `DELETE FROM auth_users WHERE id = $1` , id ); err != nil {
return fmt . Errorf ( "delete auth user: %w" , err )
}
return nil
}
2026-08-04 15:17:15 +02:00
// 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 , `
2026-09-04 15:02:16 +02:00
SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at, u.last_login_at
2026-08-04 15:17:15 +02:00
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
}
2026-08-05 14:57:01 +02:00
// DeleteAllUsers removes every shared account. The auth schema's foreign keys
// cascade this to browser sessions and API tokens, allowing a fresh bootstrap.
func ( s * Store ) DeleteAllUsers ( ctx context . Context ) error {
if err := s . validate (); err != nil {
return err
}
if _ , err := s . pool . Exec ( ctx , `DELETE FROM auth_users` ); err != nil {
return fmt . Errorf ( "delete all auth users: %w" , err )
}
return nil
}
2026-08-04 15:17:15 +02:00
// 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 (
2026-09-04 15:02:16 +02:00
& user . ID , & user . Username , & user . Email , & user . PasswordHash , & user . Role , & user . CreatedAt , & user . UpdatedAt , & user . LastLoginAt ,
2026-08-04 15:17:15 +02:00
)
if errors . Is ( err , pgx . ErrNoRows ) {
return nil , nil
}
if err != nil {
return nil , fmt . Errorf ( "find auth user: %w" , err )
}
return & user , nil
}