feat(auth): enhance authentication flow with TOTP and admin reset features
Docker / Docker Build & Push (push) Failing after 56s
Lint / Lint (push) Successful in 25s
Tests / Go backend (push) Failing after 19s
Tests / Dashboard checks (push) Successful in 24s

- 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:
Gabriel20xx committed 2026-08-05 14:58:07 +02:00
1 parent ac08be0248
commit 652e81dacb
9 files changed
+4333 -3737

No files matched your search

+290 -8
View File
@@ -8,6 +8,7 @@ import (
"encoding/hex"
"errors"
"net/http"
"strconv"
"strings"
"time"
@@ -35,10 +36,11 @@ var (
type AuthService struct {
db *DB
secureCookie bool
reset *sharedauth.ResetManager
}
func newAuthService(db *DB, secureCookie bool) *AuthService {
return &AuthService{db: db, secureCookie: secureCookie}
return &AuthService{db: db, secureCookie: secureCookie, reset: sharedauth.NewResetManager()}
}
func normalizeUsername(value string) (string, error) {
@@ -170,10 +172,14 @@ func extractBearer(r *http.Request) string {
}
type authStatusResponse struct {
SetupRequired bool `json:"setupRequired"`
Authenticated bool `json:"authenticated"`
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
SetupRequired bool `json:"setupRequired"`
Authenticated bool `json:"authenticated"`
ID int64 `json:"id,omitempty"`
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
Role string `json:"role,omitempty"`
CanManageUsers bool `json:"canManageUsers,omitempty"`
TotpEnabled bool `json:"totpEnabled,omitempty"`
}
type credentialsRequest struct {
@@ -181,6 +187,7 @@ type credentialsRequest struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
TotpToken string `json:"totpToken"`
}
func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
@@ -203,7 +210,43 @@ func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, authStatusResponse{})
return
}
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, CanManageUsers: sharedauth.CanManageUsers(user.Role), TotpEnabled: user.TOTPEnabled})
}
func (a *AuthService) handleResetRequest(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if _, err := a.reset.Request(); err != nil {
writeJSONError(w, http.StatusInternalServerError, "Unable to create reset code")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (a *AuthService) handleResetConfirm(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var request struct {
Code string `json:"code"`
}
if err := decodeJSON(r, &request); err != nil || strings.TrimSpace(request.Code) == "" {
writeJSONError(w, http.StatusBadRequest, "Code required")
return
}
if !a.reset.Confirm(request.Code) {
writeJSONError(w, http.StatusUnauthorized, "Invalid or expired code")
return
}
if err := a.db.deleteAllUsers(r.Context()); err != nil {
writeJSONError(w, http.StatusInternalServerError, "Reset failed")
return
}
a.clearSessionCookie(w)
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
@@ -256,7 +299,7 @@ func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
return
}
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, CanManageUsers: sharedauth.CanManageUsers(user.Role)})
}
func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
@@ -287,11 +330,84 @@ func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
return
}
if user.TOTPEnabled && !sharedauth.VerifyTOTP(user.TOTPSecret, request.TotpToken, time.Now()) {
writeJSONError(w, http.StatusUnauthorized, "two-factor authentication code required")
return
}
if err := a.startSession(r.Context(), w, user.ID); err != nil {
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
return
}
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, CanManageUsers: sharedauth.CanManageUsers(user.Role), TotpEnabled: user.TOTPEnabled})
}
type totpTokenRequest struct {
Token string `json:"token"`
}
func (a *AuthService) handleTOTPStatus(w http.ResponseWriter, _ *http.Request, user *AuthUser) {
writeJSON(w, http.StatusOK, map[string]bool{"enabled": user.TOTPEnabled})
}
func (a *AuthService) handleTOTPSetup(w http.ResponseWriter, r *http.Request, user *AuthUser) {
if user.TOTPEnabled {
writeJSONError(w, http.StatusConflict, "disable two-factor authentication before setting up a new secret")
return
}
secret, err := sharedauth.GenerateTOTPSecret()
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "unable to create two-factor setup")
return
}
if err := a.db.setTOTPSecret(r.Context(), user.ID, secret); err != nil {
writeJSONError(w, http.StatusInternalServerError, "unable to create two-factor setup")
return
}
account := user.Email
if account == "" {
account = user.Username
}
writeJSON(w, http.StatusOK, map[string]any{
"secret": secret,
"otpauthUrl": sharedauth.TOTPProvisioningURI("CollabTable", account, secret),
"enabled": false,
})
}
func (a *AuthService) handleTOTPEnable(w http.ResponseWriter, r *http.Request, user *AuthUser) {
var request totpTokenRequest
if err := decodeJSON(r, &request); err != nil {
writeJSONError(w, http.StatusBadRequest, "invalid JSON body")
return
}
secret, _, err := a.db.getTOTPState(r.Context(), user.ID)
if err != nil || !sharedauth.VerifyTOTP(secret, request.Token, time.Now()) {
writeJSONError(w, http.StatusUnauthorized, "invalid two-factor authentication code")
return
}
if err := a.db.enableTOTP(r.Context(), user.ID); err != nil {
writeJSONError(w, http.StatusInternalServerError, "unable to enable two-factor authentication")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"enabled": true})
}
func (a *AuthService) handleTOTPDisable(w http.ResponseWriter, r *http.Request, user *AuthUser) {
var request totpTokenRequest
if err := decodeJSON(r, &request); err != nil {
writeJSONError(w, http.StatusBadRequest, "invalid JSON body")
return
}
secret, enabled, err := a.db.getTOTPState(r.Context(), user.ID)
if err != nil || !enabled || !sharedauth.VerifyTOTP(secret, request.Token, time.Now()) {
writeJSONError(w, http.StatusUnauthorized, "invalid two-factor authentication code")
return
}
if err := a.db.disableTOTP(r.Context(), user.ID); err != nil {
writeJSONError(w, http.StatusInternalServerError, "unable to disable two-factor authentication")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"enabled": false})
}
func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request, _ *AuthUser) {
@@ -388,3 +504,169 @@ func (a *AuthService) handleTokenRegenerate(w http.ResponseWriter, r *http.Reque
}
writeJSON(w, http.StatusOK, map[string]string{"token": token})
}
type managedUserResponse struct {
ID int64 `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Role string `json:"role"`
TotpEnabled bool `json:"totpEnabled"`
}
type managedUserRequest struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
Role *string `json:"role"`
}
func managedUserView(user AuthUser) managedUserResponse {
return managedUserResponse{ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, TotpEnabled: user.TOTPEnabled}
}
func (a *AuthService) requireUserManager(w http.ResponseWriter, user *AuthUser) bool {
if sharedauth.CanManageUsers(user.Role) {
return true
}
writeJSONError(w, http.StatusForbidden, "administrator access required")
return false
}
func (a *AuthService) handleUsers(w http.ResponseWriter, r *http.Request, actor *AuthUser) {
if !a.requireUserManager(w, actor) {
return
}
switch r.Method {
case http.MethodGet:
users, err := a.db.listUsers(r.Context())
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Unable to list users")
return
}
result := make([]managedUserResponse, 0, len(users))
for _, user := range users {
result = append(result, managedUserView(user))
}
writeJSON(w, http.StatusOK, result)
case http.MethodPost:
var request managedUserRequest
if err := decodeJSON(r, &request); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
return
}
username, err := normalizeUsername(request.Username)
if err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
email, err := normalizeEmail(request.Email)
if err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
if err := validatePassword(request.Password); err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
hash, err := sharedauth.HashPassword(request.Password)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Unable to create user")
return
}
role := string(sharedauth.RoleUser)
if actor.Role == string(sharedauth.RoleSuperAdmin) && request.Role != nil {
role = string(sharedauth.NormalizeRole(*request.Role))
}
created, err := a.db.createManagedUser(r.Context(), username, email, string(hash), role)
if err != nil {
writeJSONError(w, http.StatusConflict, "Username or email is already in use")
return
}
writeJSON(w, http.StatusCreated, managedUserView(*created))
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func (a *AuthService) handleUser(w http.ResponseWriter, r *http.Request, actor *AuthUser) {
if !a.requireUserManager(w, actor) {
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid user id")
return
}
target, err := a.db.getUserByID(r.Context(), id)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Unable to find user")
return
}
if target == nil {
writeJSONError(w, http.StatusNotFound, "User not found")
return
}
if target.Role == string(sharedauth.RoleSuperAdmin) && target.ID != actor.ID {
writeJSONError(w, http.StatusForbidden, "The superadmin account is protected")
return
}
switch r.Method {
case http.MethodPut, http.MethodPatch:
var request managedUserRequest
if err := decodeJSON(r, &request); err != nil {
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
return
}
username := target.Username
if request.Username != "" {
username, err = normalizeUsername(request.Username)
if err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
}
email := target.Email
if request.Email != "" {
email, err = normalizeEmail(request.Email)
if err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
}
passwordHash := target.PasswordHash
if request.Password != "" {
if err := validatePassword(request.Password); err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
hash, hashErr := sharedauth.HashPassword(request.Password)
if hashErr != nil {
writeJSONError(w, http.StatusInternalServerError, "Unable to update user")
return
}
passwordHash = string(hash)
}
role := target.Role
if actor.Role == string(sharedauth.RoleSuperAdmin) && request.Role != nil && target.Role != string(sharedauth.RoleSuperAdmin) {
role = string(sharedauth.NormalizeRole(*request.Role))
}
if err := a.db.updateManagedUser(r.Context(), id, username, email, passwordHash, role); err != nil {
writeJSONError(w, http.StatusConflict, "Username or email is already in use")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
case http.MethodDelete:
if target.ID == actor.ID || target.Role == string(sharedauth.RoleSuperAdmin) {
writeJSONError(w, http.StatusForbidden, "This user cannot be deleted")
return
}
if err := a.db.deleteUser(r.Context(), id); err != nil {
writeJSONError(w, http.StatusInternalServerError, "Unable to delete user")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
+121 -9
View File
@@ -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 {
+11
View File
@@ -117,10 +117,21 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
// Health and auth bootstrap routes are intentionally public.
mux.HandleFunc("GET /health", s.handleHealth)
mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus)
mux.HandleFunc("POST /api/auth/reset/request", s.auth.handleResetRequest)
mux.HandleFunc("POST /api/auth/reset/confirm", s.auth.handleResetConfirm)
mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup)
mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin)
mux.Handle("POST /api/auth/logout", s.auth.requireSession(s.auth.handleLogout))
mux.Handle("POST /api/auth/credentials", s.auth.requireSession(s.auth.handleUpdateCredentials))
mux.Handle("GET /api/auth/users", s.auth.requireSession(s.auth.handleUsers))
mux.Handle("POST /api/auth/users", s.auth.requireSession(s.auth.handleUsers))
mux.Handle("PUT /api/auth/users/{id}", s.auth.requireSession(s.auth.handleUser))
mux.Handle("PATCH /api/auth/users/{id}", s.auth.requireSession(s.auth.handleUser))
mux.Handle("DELETE /api/auth/users/{id}", s.auth.requireSession(s.auth.handleUser))
mux.Handle("GET /api/auth/totp/status", s.auth.requireSession(s.auth.handleTOTPStatus))
mux.Handle("POST /api/auth/totp/setup", s.auth.requireSession(s.auth.handleTOTPSetup))
mux.Handle("POST /api/auth/totp/enable", s.auth.requireSession(s.auth.handleTOTPEnable))
mux.Handle("POST /api/auth/totp/disable", s.auth.requireSession(s.auth.handleTOTPDisable))
mux.Handle("GET /api/auth/token/status", s.auth.requireSession(s.auth.handleTokenStatus))
mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(s.auth.handleTokenRegenerate))
+3632 -3575
View File
File diff suppressed because it is too large. Load diff
+92 -47
View File
@@ -1,61 +1,106 @@
async function request(url, options) {
const res = await fetch(url, {
...options,
headers: options?.body ? { 'Content-Type': 'application/json', ...options?.headers } : options?.headers,
});
if (!res.ok) {
let message = `HTTP ${res.status}`;
try {
const body = await res.json();
// This backend's error responses are { error: "<category>", message: "<human text>" } -
// message is the human-readable text; error is just a category label (e.g. "Unauthorized").
if (body?.message) message = body.message;
else if (body?.error) message = body.error;
} catch {
// Response body wasn't JSON (or was empty) - keep the generic status message.
}
throw new Error(message);
}
if (res.status === 204) return undefined;
return res.json();
}
async function getJson(url) {
return request(url);
}
export async function fetchOverview() {
return getJson('/web/data');
}
export async function fetchTechStack() {
return getJson('/web/info');
}
export async function fetchHealth() {
const res = await fetch('/health');
return { up: res.ok };
}
export async function fetchAuthStatus() {
return getJson('/api/auth/status');
}
async function request(url, options) {
const res = await fetch(url, {
...options,
headers: options?.body ? { 'Content-Type': 'application/json', ...options?.headers } : options?.headers,
});
if (!res.ok) {
let message = `HTTP ${res.status}`;
try {
const body = await res.json();
// This backend's error responses are { error: "<category>", message: "<human text>" } -
// message is the human-readable text; error is just a category label (e.g. "Unauthorized").
if (body?.message) message = body.message;
else if (body?.error) message = body.error;
} catch {
// Response body wasn't JSON (or was empty) - keep the generic status message.
}
throw new Error(message);
}
if (res.status === 204) return undefined;
return res.json();
}
async function getJson(url) {
return request(url);
}
export async function fetchOverview() {
return getJson('/web/data');
}
export async function fetchTechStack() {
return getJson('/web/info');
}
export async function fetchHealth() {
const res = await fetch('/health');
return { up: res.ok };
}
export async function fetchAuthStatus() {
return getJson('/api/auth/status');
}
export async function setupAccount(username, email, password) {
return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, email, password }) });
}
export async function login(identifier, password) {
return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password }) });
export async function login(identifier, password, totpToken = '') {
return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password, totpToken }) });
}
export async function logout() {
return request('/api/auth/logout', { method: 'POST' });
export async function fetchTotpStatus() {
return request('/api/auth/totp/status');
}
export async function setupTotp() {
return request('/api/auth/totp/setup', { method: 'POST' });
}
export async function enableTotp(token) {
return request('/api/auth/totp/enable', { method: 'POST', body: JSON.stringify({ token }) });
}
export async function disableTotp(token) {
return request('/api/auth/totp/disable', { method: 'POST', body: JSON.stringify({ token }) });
}
export async function requestAdminReset() {
return request('/api/auth/reset/request', { method: 'POST' });
}
export async function confirmAdminReset(code) {
const result = await request('/api/auth/reset/confirm', {
method: 'POST',
body: JSON.stringify({ code }),
});
window.location.reload();
return result;
}
export async function logout() {
return request('/api/auth/logout', { method: 'POST' });
}
export async function updateCredentials({ newUsername, newEmail, newPassword }) {
return request('/api/auth/credentials', {
method: 'POST',
body: JSON.stringify({ newUsername, newEmail, newPassword }),
});
}
export async function listUsers() {
return getJson('/api/auth/users');
}
export async function createUser(input) {
return request('/api/auth/users', { method: 'POST', body: JSON.stringify(input) });
}
export async function updateUser(id, input) {
return request(`/api/auth/users/${encodeURIComponent(id)}`, { method: 'PUT', body: JSON.stringify(input) });
}
export async function deleteUser(id) {
return request(`/api/auth/users/${encodeURIComponent(id)}`, { method: 'DELETE' });
}
@@ -2,17 +2,23 @@
import { AuthPage as SharedAuthPage } from '@gabriel20xx/shared-code/web-ui';
import { useAuth } from '$lib/features/auth/auth.svelte.js';
let { setupRequired } = $props();
let { setupRequired, loading = false, error = '' } = $props();
const auth = useAuth();
const onLogin = (input) => auth.login(input.identifier, input.password);
const onLogin = (input) => auth.login(input.identifier, input.password, input.totpToken);
const onSetup = (input) => auth.setup(input.username, input.email, input.password);
const onRequestReset = () => auth.requestAdminReset();
const onConfirmReset = (code) => auth.confirmAdminReset(code);
</script>
<SharedAuthPage
brand="CollabTable"
tagline="Collaborative tables for your team"
{setupRequired}
{loading}
{error}
{onLogin}
{onSetup}
{onRequestReset}
{onConfirmReset}
/>
+101 -52
View File
@@ -1,68 +1,117 @@
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import { getContext, setContext } from 'svelte';
import { fetchAuthStatus, login, logout, setupAccount, updateCredentials } from '$lib/api.js';
const AUTH_STATUS_KEY = ['AuthStatus'];
const AUTH_CONTEXT_KEY = Symbol('auth');
export function createAuthStore() {
const queryClient = useQueryClient();
const statusQuery = createQuery(() => ({
queryKey: AUTH_STATUS_KEY,
queryFn: fetchAuthStatus,
}));
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import { getContext, setContext } from 'svelte';
import {
confirmAdminReset,
createUser,
deleteUser,
disableTotp,
enableTotp,
fetchAuthStatus,
fetchTotpStatus,
login,
listUsers,
logout,
requestAdminReset,
setupTotp,
setupAccount,
updateCredentials,
updateUser,
} from '$lib/api.js';
const AUTH_STATUS_KEY = ['AuthStatus'];
const AUTH_CONTEXT_KEY = Symbol('auth');
export function createAuthStore() {
const queryClient = useQueryClient();
const statusQuery = createQuery(() => ({
queryKey: AUTH_STATUS_KEY,
queryFn: fetchAuthStatus,
}));
const setupMutation = createMutation(() => ({
mutationFn: ({ username, email, password }) => setupAccount(username, email, password),
}));
const loginMutation = createMutation(() => ({
mutationFn: ({ identifier, password }) => login(identifier, password),
}));
const logoutMutation = createMutation(() => ({
mutationFn: () => logout(),
}));
const updateCredentialsMutation = createMutation(() => ({
mutationFn: (input) => updateCredentials(input),
}));
const refresh = () => queryClient.invalidateQueries({ queryKey: AUTH_STATUS_KEY });
const store = {
get status() {
return statusQuery.data;
},
get loading() {
return statusQuery.isLoading;
},
get error() {
return statusQuery.error;
},
mutationFn: ({ identifier, password, totpToken }) => login(identifier, password, totpToken),
}));
const logoutMutation = createMutation(() => ({
mutationFn: () => logout(),
}));
const updateCredentialsMutation = createMutation(() => ({
mutationFn: (input) => updateCredentials(input),
}));
const refresh = () => queryClient.invalidateQueries({ queryKey: AUTH_STATUS_KEY });
const store = {
get status() {
return statusQuery.data;
},
get loading() {
return statusQuery.isLoading;
},
get error() {
return statusQuery.error;
},
async setup(username, email, password) {
await setupMutation.mutateAsync({ username, email, password });
await refresh();
},
async login(identifier, password, totpToken = '') {
await loginMutation.mutateAsync({ identifier, password, totpToken });
await refresh();
},
async login(identifier, password) {
await loginMutation.mutateAsync({ identifier, password });
async totpStatus() {
const result = await fetchTotpStatus();
return result?.enabled === true;
},
async setupTotp() {
return setupTotp();
},
async enableTotp(token) {
await enableTotp(token);
await refresh();
},
async logout() {
await logoutMutation.mutateAsync();
async disableTotp(token) {
await disableTotp(token);
await refresh();
},
async requestAdminReset() {
await requestAdminReset();
},
async confirmAdminReset(code) {
await confirmAdminReset(code);
},
async logout() {
await logoutMutation.mutateAsync();
await refresh();
},
async updateCredentials(input) {
await updateCredentialsMutation.mutateAsync(input);
await refresh();
},
};
setContext(AUTH_CONTEXT_KEY, store);
return store;
}
export function useAuth() {
const ctx = getContext(AUTH_CONTEXT_KEY);
if (!ctx) {
throw new Error('useAuth() must be called within the root layout that calls createAuthStore()');
}
return ctx;
}
async listUsers() {
return listUsers();
},
async createUser(input) {
await createUser(input);
},
async updateUser(id, input) {
await updateUser(id, input);
},
async deleteUser(id) {
await deleteUser(id);
},
};
setContext(AUTH_CONTEXT_KEY, store);
return store;
}
export function useAuth() {
const ctx = getContext(AUTH_CONTEXT_KEY);
if (!ctx) {
throw new Error('useAuth() must be called within the root layout that calls createAuthStore()');
}
return ctx;
}
@@ -26,11 +26,12 @@
<Tooltip.Provider delayDuration={300}>
{#if auth.loading}
<div class="flex min-h-screen items-center justify-center text-sm text-muted-fg">Loading…</div>
<AuthPage setupRequired={auth.status?.setupRequired ?? true} loading />
{:else if auth.error}
<div class="flex min-h-screen items-center justify-center px-4 text-sm text-danger">
{auth.error instanceof Error ? auth.error.message : 'Request failed.'}
</div>
<AuthPage
setupRequired={auth.status?.setupRequired ?? true}
error={auth.error instanceof Error ? auth.error.message : 'Request failed.'}
/>
{:else if !auth.status || auth.status.setupRequired || !auth.status.authenticated}
<AuthPage setupRequired={auth.status?.setupRequired ?? true} />
{:else}
@@ -44,17 +45,33 @@
onProfile={() => (credentialsOpen = true)}
onSettings={() => (settingsOpen = true)}
>
{#snippet children()}
{@render children?.()}
{/snippet}
{@render children?.()}
</SharedAppShell>
{/if}
</Tooltip.Provider>
<SettingsDialog bind:open={settingsOpen} />
<SettingsDialog
bind:open={settingsOpen}
currentRole={auth.status?.role ?? 'user'}
currentUserId={auth.status?.id}
onCreateUser={(input) => auth.createUser(input)}
onDeleteUser={(id) => auth.deleteUser(id)}
onListUsers={() => auth.listUsers()}
onUpdateUser={(id, input) => auth.updateUser(id, input)}
/>
<ProfileDialog
bind:open={credentialsOpen}
currentUsername={auth.status?.username ?? ''}
currentEmail={auth.status?.email ?? ''}
currentRole={auth.status?.role ?? 'user'}
currentUserId={auth.status?.id}
onCreateUser={(input) => auth.createUser(input)}
onDeleteUser={(id) => auth.deleteUser(id)}
onListUsers={() => auth.listUsers()}
onSave={saveProfile}
onUpdateUser={(id, input) => auth.updateUser(id, input)}
onTotpStatus={() => auth.totpStatus()}
onTotpSetup={() => auth.setupTotp()}
onTotpEnable={(token) => auth.enableTotp(token)}
onTotpDisable={(token) => auth.disableTotp(token)}
/>
@@ -1,4 +1,4 @@
<script>
<script>
import { Moon, Sun, SunMoon } from '@lucide/svelte';
import Button from '$lib/components/ui/button.svelte';
import { SettingsDialog as SharedSettingsDialog } from '@gabriel20xx/shared-code/web-ui';
@@ -6,45 +6,62 @@
import { currentLanguage, languages, setLanguage } from '$lib/language.svelte.js';
import { themeState } from '$lib/theme.svelte.js';
let { open = $bindable(false) } = $props();
let {
currentRole = 'user',
currentUserId,
onCreateUser,
onDeleteUser,
onListUsers,
onUpdateUser,
open = $bindable(false)
} = $props();
const languageItems = languages.map((language) => ({ value: language.id, label: language.label }));
</script>
<SharedSettingsDialog bind:open title="Settings">
</script>
<SharedSettingsDialog
bind:open
currentRole={currentRole}
currentUserId={currentUserId}
onCreateUser={onCreateUser}
onDeleteUser={onDeleteUser}
onListUsers={onListUsers}
onUpdateUser={onUpdateUser}
title="Settings"
>
<div>
<span class="mb-2 block text-sm font-medium">Theme</span>
<div class="flex w-full rounded-md border border-border p-1">
<Button
type="button"
variant={themeState.mode === 'light' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('light')}
>
<Sun class="size-4" />
Light
</Button>
<Button
type="button"
variant={themeState.mode === 'dark' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('dark')}
>
<Moon class="size-4" />
Dark
</Button>
<Button
type="button"
variant={themeState.mode === 'system' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('system')}
>
<SunMoon class="size-4" />
System
</Button>
<div class="flex w-full rounded-md border border-border p-1">
<Button
type="button"
variant={themeState.mode === 'light' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('light')}
>
<Sun class="size-4" />
Light
</Button>
<Button
type="button"
variant={themeState.mode === 'dark' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('dark')}
>
<Moon class="size-4" />
Dark
</Button>
<Button
type="button"
variant={themeState.mode === 'system' ? 'secondary' : 'ghost'}
size="sm"
class="flex-1 gap-1.5"
onclick={() => themeState.setMode('system')}
>
<SunMoon class="size-4" />
System
</Button>
</div>
</div>
<div class="mt-5">