feat(auth): implement TOTP setup and management
Lint / Lint (Node/Svelte) (push) Successful in 24s
Lint / Lint (Go) (push) Successful in 28s
Lint / Lint (Python) (push) Failing after 14s
Tests / Test (Node/Svelte) (push) Successful in 18s
Tests / Test (Go) (push) Successful in 25s
Tests / Test (Python) (push) Successful in 12s

- Added TOTP support for two-factor authentication in the auth module.
- Introduced new types and interfaces for TOTP setup and token actions in the web UI.
- Created backend logic for generating and verifying TOTP secrets and tokens.
- Implemented user management features including role assignments and user CRUD operations.
- Enhanced UI components for managing users and TOTP settings.
- Added styles for optional labels and authentication reset links.
- Implemented reset code generation and validation for admin accounts.
This commit is contained in:
Gabriel20xx committed 2026-08-05 14:57:01 +02:00
1 parent 2f57554154
commit da97fd4fb1
30 files changed
+2145 -27

No files matched your search

+172 -7
View File
@@ -21,6 +21,7 @@ type User struct {
Username string
Email string
PasswordHash string
Role Role
CreatedAt time.Time
UpdatedAt time.Time
}
@@ -62,12 +63,21 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
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 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;
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();
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');
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
ON auth_users (lower(email)) WHERE email <> '';
@@ -91,6 +101,8 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
`); err != nil {
return fmt.Errorf("ensure single-user auth constraint: %w", err)
}
} 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)
}
if options.APITokens {
@@ -109,6 +121,65 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
return nil
}
// 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
}
// CountUsers returns the number of configured accounts.
func (s *Store) CountUsers(ctx context.Context) (int, error) {
if err := s.validate(); err != nil {
@@ -129,11 +200,13 @@ func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash st
}
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
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())
RETURNING id, username, email, password_hash, role, created_at, updated_at
`, username, email, passwordHash).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt, &user.UpdatedAt,
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt,
)
if err != nil {
var pgErr *pgconn.PgError
@@ -151,7 +224,7 @@ func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User,
return nil, err
}
return s.find(ctx, `
SELECT id, username, email, password_hash, created_at, updated_at
SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users
WHERE username = $1 OR lower(email) = lower($1)
`, identifier)
@@ -163,7 +236,7 @@ func (s *Store) FindByID(ctx context.Context, id int64) (*User, error) {
return nil, err
}
return s.find(ctx, `
SELECT id, username, email, password_hash, created_at, updated_at
SELECT id, username, email, password_hash, role, created_at, updated_at
FROM auth_users WHERE id = $1
`, id)
}
@@ -184,6 +257,86 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email
return nil
}
// 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, `
SELECT id, username, email, role, created_at, updated_at
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
if err := rows.Scan(&user.ID, &user.Username, &user.Email, &user.Role, &user.CreatedAt, &user.UpdatedAt); err != nil {
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())
RETURNING id, username, email, password_hash, role, created_at, updated_at
`, username, email, passwordHash, role).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &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 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
}
// 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
}
// 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 {
@@ -205,7 +358,7 @@ func (s *Store) FindSessionUser(ctx context.Context, tokenHash string) (*User, e
return nil, err
}
return s.find(ctx, `
SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at
SELECT u.id, u.username, u.email, u.password_hash, u.role, 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()
@@ -234,6 +387,18 @@ func (s *Store) DeleteSessionsForUser(ctx context.Context, userID int64) error {
return nil
}
// 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
}
// 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 {