feat(auth): enhance authentication flow with TOTP and admin reset features
- Added TOTP setup, enable, and disable functions to the API. - Implemented admin reset request and confirmation functionalities. - Updated AuthPage to handle new reset functionalities and TOTP inputs. - Enhanced auth store to manage user creation, deletion, and listing. - Improved AppShell and SettingsDialog to support user management features. - Refactored API calls for better organization and clarity.
This commit is contained in:
1 parent
ac08be0248
commit
652e81dacb
9 files changed
+4333
-3737
No files matched your search
+121
-9
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
sharedauth "repos.gfranz.ch/Gabriel20xx/SharedCode/backend/auth"
|
||||
sharedpostgres "repos.gfranz.ch/Gabriel20xx/SharedCode/backend/postgres"
|
||||
)
|
||||
|
||||
@@ -104,12 +105,21 @@ func (d *DB) initSchema(ctx context.Context) error {
|
||||
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;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
||||
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');
|
||||
DROP INDEX IF EXISTS auth_users_singleton_idx;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
@@ -176,6 +186,9 @@ type AuthUser struct {
|
||||
Username string
|
||||
Email string
|
||||
PasswordHash string
|
||||
TOTPSecret string
|
||||
TOTPEnabled bool
|
||||
Role string
|
||||
}
|
||||
|
||||
var ErrSingletonUserExists = errors.New("a user already exists")
|
||||
@@ -188,13 +201,20 @@ func (d *DB) countUsers(ctx context.Context) (int, error) {
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (d *DB) deleteAllUsers(ctx context.Context) error {
|
||||
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_users`); err != nil {
|
||||
return fmt.Errorf("delete all users: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) createUser(ctx context.Context, username, email, passwordHash string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
INSERT INTO auth_users (username, email, password_hash, updated_at)
|
||||
VALUES ($1, $2, $3, now())
|
||||
RETURNING id, username, email
|
||||
`, username, email, passwordHash).Scan(&user.ID, &user.Username, &user.Email)
|
||||
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
||||
VALUES ($1, $2, $3, 'superadmin', now())
|
||||
RETURNING id, username, email, role
|
||||
`, username, email, passwordHash).Scan(&user.ID, &user.Username, &user.Email, &user.Role)
|
||||
if err != nil {
|
||||
if sharedpostgres.IsUniqueViolation(err) {
|
||||
return nil, ErrSingletonUserExists
|
||||
@@ -208,10 +228,10 @@ func (d *DB) createUser(ctx context.Context, username, email, passwordHash strin
|
||||
func (d *DB) getUserByIdentifier(ctx context.Context, identifier string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
SELECT id, username, email, password_hash
|
||||
SELECT id, username, email, password_hash, COALESCE(totp_secret, ''), COALESCE(totp_enabled, false), COALESCE(role, 'user')
|
||||
FROM auth_users
|
||||
WHERE username = $1 OR lower(email) = lower($1)
|
||||
`, identifier).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash)
|
||||
`, identifier).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.TOTPSecret, &user.TOTPEnabled, &user.Role)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -224,11 +244,11 @@ func (d *DB) getUserByIdentifier(ctx context.Context, identifier string) (*AuthU
|
||||
func (d *DB) getSessionUser(ctx context.Context, tokenHash string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
SELECT u.id, u.username, u.email, u.password_hash
|
||||
SELECT u.id, u.username, u.email, u.password_hash, COALESCE(u.totp_secret, ''), COALESCE(u.totp_enabled, false), COALESCE(u.role, 'user')
|
||||
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).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash)
|
||||
`, tokenHash).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.TOTPSecret, &user.TOTPEnabled, &user.Role)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -269,6 +289,98 @@ func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) listUsers(ctx context.Context) ([]AuthUser, error) {
|
||||
rows, err := d.pool.Query(ctx, `
|
||||
SELECT id, username, email, COALESCE(role, 'user'), COALESCE(totp_enabled, false)
|
||||
FROM auth_users ORDER BY created_at, id
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list users: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
users := make([]AuthUser, 0)
|
||||
for rows.Next() {
|
||||
var user AuthUser
|
||||
if err := rows.Scan(&user.ID, &user.Username, &user.Email, &user.Role, &user.TOTPEnabled); err != nil {
|
||||
return nil, fmt.Errorf("scan user: %w", err)
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
return users, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) getUserByID(ctx context.Context, id int64) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
SELECT id, username, email, password_hash, COALESCE(totp_secret, ''),
|
||||
COALESCE(totp_enabled, false), COALESCE(role, 'user')
|
||||
FROM auth_users WHERE id = $1
|
||||
`, id).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.TOTPSecret, &user.TOTPEnabled, &user.Role)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get user by id: %w", err)
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (d *DB) createManagedUser(ctx context.Context, username, email, passwordHash, role string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
||||
VALUES ($1, $2, $3, $4, now())
|
||||
RETURNING id, username, email, role
|
||||
`, username, email, passwordHash, sharedauth.NormalizeRole(role)).Scan(&user.ID, &user.Username, &user.Email, &user.Role)
|
||||
if err != nil {
|
||||
if sharedpostgres.IsUniqueViolation(err) {
|
||||
return nil, ErrSingletonUserExists
|
||||
}
|
||||
return nil, fmt.Errorf("create managed user: %w", err)
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (d *DB) updateManagedUser(ctx context.Context, id int64, username, email, passwordHash, role string) error {
|
||||
_, err := d.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, sharedauth.NormalizeRole(role), id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update managed user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) deleteUser(ctx context.Context, id int64) error {
|
||||
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_users WHERE id = $1`, id); err != nil {
|
||||
return fmt.Errorf("delete user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) getTOTPState(ctx context.Context, userID int64) (string, bool, error) {
|
||||
var secret string
|
||||
var enabled bool
|
||||
err := d.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1`, userID).Scan(&secret, &enabled)
|
||||
return secret, enabled, err
|
||||
}
|
||||
|
||||
func (d *DB) setTOTPSecret(ctx context.Context, userID int64, secret string) error {
|
||||
_, err := d.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2`, secret, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) enableTOTP(ctx context.Context, userID int64) error {
|
||||
_, err := d.pool.Exec(ctx, `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''`, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) disableTOTP(ctx context.Context, userID int64) error {
|
||||
_, err := d.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1`, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) deleteSessionsForUser(ctx context.Context, userID int64) error {
|
||||
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID)
|
||||
if err != nil {
|
||||
|
||||
Reference in new issue
Block a user