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
+791 -195

No files matched your search

+286 -4
View File
@@ -8,6 +8,7 @@ import (
"encoding/hex" "encoding/hex"
"errors" "errors"
"net/http" "net/http"
"strconv"
"strings" "strings"
"time" "time"
@@ -35,10 +36,11 @@ var (
type AuthService struct { type AuthService struct {
db *DB db *DB
secureCookie bool secureCookie bool
reset *sharedauth.ResetManager
} }
func newAuthService(db *DB, secureCookie bool) *AuthService { 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) { func normalizeUsername(value string) (string, error) {
@@ -172,8 +174,12 @@ func extractBearer(r *http.Request) string {
type authStatusResponse struct { type authStatusResponse struct {
SetupRequired bool `json:"setupRequired"` SetupRequired bool `json:"setupRequired"`
Authenticated bool `json:"authenticated"` Authenticated bool `json:"authenticated"`
ID int64 `json:"id,omitempty"`
Username string `json:"username,omitempty"` Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"` Email string `json:"email,omitempty"`
Role string `json:"role,omitempty"`
CanManageUsers bool `json:"canManageUsers,omitempty"`
TotpEnabled bool `json:"totpEnabled,omitempty"`
} }
type credentialsRequest struct { type credentialsRequest struct {
@@ -181,6 +187,7 @@ type credentialsRequest struct {
Username string `json:"username"` Username string `json:"username"`
Email string `json:"email"` Email string `json:"email"`
Password string `json:"password"` Password string `json:"password"`
TotpToken string `json:"totpToken"`
} }
func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) { 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{}) writeJSON(w, http.StatusOK, authStatusResponse{})
return 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) { 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") writeJSONError(w, http.StatusInternalServerError, "Internal server error")
return 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) { 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()) writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
return 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 { if err := a.startSession(r.Context(), w, user.ID); err != nil {
writeJSONError(w, http.StatusInternalServerError, "Internal server error") writeJSONError(w, http.StatusInternalServerError, "Internal server error")
return 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) { 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}) 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"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
sharedauth "repos.gfranz.ch/Gabriel20xx/SharedCode/backend/auth"
sharedpostgres "repos.gfranz.ch/Gabriel20xx/SharedCode/backend/postgres" 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, username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL DEFAULT '', email TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL, 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(), created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_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 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_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 ( CREATE TABLE IF NOT EXISTS auth_sessions (
id BIGSERIAL PRIMARY KEY, id BIGSERIAL PRIMARY KEY,
@@ -176,6 +186,9 @@ type AuthUser struct {
Username string Username string
Email string Email string
PasswordHash string PasswordHash string
TOTPSecret string
TOTPEnabled bool
Role string
} }
var ErrSingletonUserExists = errors.New("a user already exists") var ErrSingletonUserExists = errors.New("a user already exists")
@@ -188,13 +201,20 @@ func (d *DB) countUsers(ctx context.Context) (int, error) {
return count, nil 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) { func (d *DB) createUser(ctx context.Context, username, email, passwordHash string) (*AuthUser, error) {
var user AuthUser var user AuthUser
err := d.pool.QueryRow(ctx, ` err := d.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, updated_at) INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3, now()) VALUES ($1, $2, $3, 'superadmin', now())
RETURNING id, username, email RETURNING id, username, email, role
`, username, email, passwordHash).Scan(&user.ID, &user.Username, &user.Email) `, username, email, passwordHash).Scan(&user.ID, &user.Username, &user.Email, &user.Role)
if err != nil { if err != nil {
if sharedpostgres.IsUniqueViolation(err) { if sharedpostgres.IsUniqueViolation(err) {
return nil, ErrSingletonUserExists 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) { func (d *DB) getUserByIdentifier(ctx context.Context, identifier string) (*AuthUser, error) {
var user AuthUser var user AuthUser
err := d.pool.QueryRow(ctx, ` 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 FROM auth_users
WHERE username = $1 OR lower(email) = lower($1) 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) { if errors.Is(err, pgx.ErrNoRows) {
return nil, nil 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) { func (d *DB) getSessionUser(ctx context.Context, tokenHash string) (*AuthUser, error) {
var user AuthUser var user AuthUser
err := d.pool.QueryRow(ctx, ` 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 FROM auth_sessions s
JOIN auth_users u ON u.id = s.user_id JOIN auth_users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.expires_at > now() 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) { if errors.Is(err, pgx.ErrNoRows) {
return nil, nil return nil, nil
} }
@@ -269,6 +289,98 @@ func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username,
return nil 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 { func (d *DB) deleteSessionsForUser(ctx context.Context, userID int64) error {
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID) _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID)
if err != nil { 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. // Health and auth bootstrap routes are intentionally public.
mux.HandleFunc("GET /health", s.handleHealth) mux.HandleFunc("GET /health", s.handleHealth)
mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus) 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/setup", s.auth.handleSetup)
mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin) 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/logout", s.auth.requireSession(s.auth.handleLogout))
mux.Handle("POST /api/auth/credentials", s.auth.requireSession(s.auth.handleUpdateCredentials)) 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("GET /api/auth/token/status", s.auth.requireSession(s.auth.handleTokenStatus))
mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(s.auth.handleTokenRegenerate)) mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(s.auth.handleTokenRegenerate))
+222 -165
View File
@@ -8,13 +8,13 @@
"name": "collabtable-server-frontend", "name": "collabtable-server-frontend",
"version": "1.0.0", "version": "1.0.0",
"dependencies": { "dependencies": {
"@gabriel20xx/shared-code": "git+https://repos.gfranz.ch/Gabriel20xx/SharedCode.git#c95865d",
"@lucide/svelte": "latest", "@lucide/svelte": "latest",
"@tanstack/svelte-query": "latest", "@tanstack/svelte-query": "latest",
"bits-ui": "latest", "bits-ui": "latest",
"class-variance-authority": "latest", "class-variance-authority": "latest",
"clsx": "latest", "clsx": "latest",
"tailwind-merge": "latest", "tailwind-merge": "latest"
"@gabriel20xx/shared-code": "git+https://repos.gfranz.ch/Gabriel20xx/SharedCode.git#c95865d"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "latest", "@eslint/js": "latest",
@@ -218,6 +218,17 @@
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==", "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@gabriel20xx/shared-code": {
"version": "0.1.0",
"resolved": "git+https://repos.gfranz.ch/Gabriel20xx/SharedCode.git#c95865dbe2be79fce08035ecd6d0b324eea9116c",
"license": "MIT",
"workspaces": [
"packages/*"
],
"dependencies": {
"pg": "^8.17.2"
}
},
"node_modules/@humanfs/core": { "node_modules/@humanfs/core": {
"version": "0.19.2", "version": "0.19.2",
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
@@ -993,6 +1004,72 @@
"node": ">=14.0.0" "node": ">=14.0.0"
} }
}, },
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
"version": "1.11.1",
"dev": true,
"inBundle": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "1.2.2",
"tslib": "^2.4.0"
}
},
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
"version": "1.11.1",
"dev": true,
"inBundle": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
"version": "1.2.2",
"dev": true,
"inBundle": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
"version": "1.1.4",
"dev": true,
"inBundle": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@tybys/wasm-util": "^0.10.1"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"peerDependencies": {
"@emnapi/core": "^1.7.1",
"@emnapi/runtime": "^1.7.1"
}
},
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
"version": "0.10.2",
"dev": true,
"inBundle": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
"version": "2.8.1",
"dev": true,
"inBundle": true,
"license": "0BSD",
"optional": true
},
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": { "node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
"version": "4.3.3", "version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz", "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz",
@@ -2355,6 +2432,95 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/pg": {
"version": "8.22.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
"integrity": "sha512-8wih1vVIBMxoUM2oB4soJsD9tDnDpLv4OXBJ+EJzFsvycD+lfyIreC2gGHq78f8jbLLt+bvlPTFdFZfJkOuzAA==",
"license": "MIT",
"dependencies": {
"pg-connection-string": "^2.14.0",
"pg-pool": "^3.14.0",
"pg-protocol": "^1.15.0",
"pg-types": "2.2.0",
"pgpass": "1.0.5"
},
"engines": {
"node": ">= 16.0.0"
},
"optionalDependencies": {
"pg-cloudflare": "^1.4.0"
},
"peerDependencies": {
"pg-native": ">=3.0.1"
},
"peerDependenciesMeta": {
"pg-native": {
"optional": true
}
}
},
"node_modules/pg-cloudflare": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.0.tgz",
"integrity": "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==",
"license": "MIT",
"optional": true
},
"node_modules/pg-connection-string": {
"version": "2.14.0",
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.0.tgz",
"integrity": "sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg==",
"license": "MIT"
},
"node_modules/pg-int8": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
"license": "ISC",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/pg-pool": {
"version": "3.14.0",
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
"license": "MIT",
"peerDependencies": {
"pg": ">=8.0"
}
},
"node_modules/pg-protocol": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.15.0.tgz",
"integrity": "sha512-cq9sECI5s0+uPUXjbz8ioyPJni6RzsRib0US67i5IoTZKw8fNeYlVE7u8F4dG7vEJJtc5wdD1K189lCCUwqWTQ==",
"license": "MIT"
},
"node_modules/pg-types": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
"license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
"postgres-array": "~2.0.0",
"postgres-bytea": "~1.0.0",
"postgres-date": "~1.0.4",
"postgres-interval": "^1.1.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/pgpass": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
"license": "MIT",
"dependencies": {
"split2": "^4.1.0"
}
},
"node_modules/picocolors": { "node_modules/picocolors": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -2512,6 +2678,45 @@
"node": ">=4" "node": ">=4"
} }
}, },
"node_modules/postgres-array": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/postgres-bytea": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-date": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-interval": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
"license": "MIT",
"dependencies": {
"xtend": "^4.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/prelude-ls": { "node_modules/prelude-ls": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
@@ -2715,6 +2920,15 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
"license": "ISC",
"engines": {
"node": ">= 10.x"
}
},
"node_modules/style-to-object": { "node_modules/style-to-object": {
"version": "1.0.14", "version": "1.0.14",
"resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz", "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz",
@@ -3386,20 +3600,13 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/yaml": { "node_modules/xtend": {
"version": "2.9.0", "version": "4.0.2",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"extraneous": true, "license": "MIT",
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
},
"engines": { "engines": {
"node": ">= 14.6" "node": ">=0.4"
},
"funding": {
"url": "https://github.com/sponsors/eemeli"
} }
}, },
"node_modules/yocto-queue": { "node_modules/yocto-queue": {
@@ -3420,156 +3627,6 @@
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz", "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
"integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==", "integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==",
"license": "MIT" "license": "MIT"
},
"node_modules/@gabriel20xx/shared-code": {
"version": "0.1.0",
"resolved": "git+https://repos.gfranz.ch/Gabriel20xx/SharedCode.git#c95865dbe2be79fce08035ecd6d0b324eea9116c",
"license": "MIT",
"workspaces": [
"packages/*"
],
"dependencies": {
"pg": "^8.17.2"
}
},
"node_modules/pg": {
"version": "8.22.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
"integrity": "sha512-8wih1vVIBMxoUM2oB4soJsD9tDnDpLv4OXBJ+EJzFsvycD+lfyIreC2gGHq78f8jbLLt+bvlPTFdFZfJkOuzAA==",
"license": "MIT",
"dependencies": {
"pg-connection-string": "^2.14.0",
"pg-pool": "^3.14.0",
"pg-protocol": "^1.15.0",
"pg-types": "2.2.0",
"pgpass": "1.0.5"
},
"engines": {
"node": ">= 16.0.0"
},
"optionalDependencies": {
"pg-cloudflare": "^1.4.0"
},
"peerDependencies": {
"pg-native": ">=3.0.1"
},
"peerDependenciesMeta": {
"pg-native": {
"optional": true
}
}
},
"node_modules/pg-connection-string": {
"version": "2.14.0",
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.0.tgz",
"integrity": "sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg==",
"license": "MIT"
},
"node_modules/pg-pool": {
"version": "3.14.0",
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
"license": "MIT",
"peerDependencies": {
"pg": ">=8.0"
}
},
"node_modules/pg-protocol": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.15.0.tgz",
"integrity": "sha512-cq9sECI5s0+uPUXjbz8ioyPJni6RzsRib0US67i5IoTZKw8fNeYlVE7u8F4dG7vEJJtc5wdD1K189lCCUwqWTQ==",
"license": "MIT"
},
"node_modules/pg-types": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
"license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
"postgres-array": "~2.0.0",
"postgres-bytea": "~1.0.0",
"postgres-date": "~1.0.4",
"postgres-interval": "^1.1.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/pgpass": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
"license": "MIT",
"dependencies": {
"split2": "^4.1.0"
}
},
"node_modules/pg-int8": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
"license": "ISC",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/postgres-array": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/postgres-bytea": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-date": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-interval": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
"license": "MIT",
"dependencies": {
"xtend": "^4.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
"license": "ISC",
"engines": {
"node": ">= 10.x"
}
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
} }
} }
} }
+47 -2
View File
@@ -45,8 +45,37 @@ export async function setupAccount(username, email, password) {
return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, email, password }) }); return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, email, password }) });
} }
export async function login(identifier, password) { export async function login(identifier, password, totpToken = '') {
return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password }) }); return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password, totpToken }) });
}
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() { export async function logout() {
@@ -59,3 +88,19 @@ export async function updateCredentials({ newUsername, newEmail, newPassword })
body: JSON.stringify({ newUsername, newEmail, newPassword }), 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 { AuthPage as SharedAuthPage } from '@gabriel20xx/shared-code/web-ui';
import { useAuth } from '$lib/features/auth/auth.svelte.js'; import { useAuth } from '$lib/features/auth/auth.svelte.js';
let { setupRequired } = $props(); let { setupRequired, loading = false, error = '' } = $props();
const auth = useAuth(); 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 onSetup = (input) => auth.setup(input.username, input.email, input.password);
const onRequestReset = () => auth.requestAdminReset();
const onConfirmReset = (code) => auth.confirmAdminReset(code);
</script> </script>
<SharedAuthPage <SharedAuthPage
brand="CollabTable" brand="CollabTable"
tagline="Collaborative tables for your team" tagline="Collaborative tables for your team"
{setupRequired} {setupRequired}
{loading}
{error}
{onLogin} {onLogin}
{onSetup} {onSetup}
{onRequestReset}
{onConfirmReset}
/> />
+53 -4
View File
@@ -1,6 +1,22 @@
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query'; import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import { getContext, setContext } from 'svelte'; import { getContext, setContext } from 'svelte';
import { fetchAuthStatus, login, logout, setupAccount, updateCredentials } from '$lib/api.js'; 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_STATUS_KEY = ['AuthStatus'];
const AUTH_CONTEXT_KEY = Symbol('auth'); const AUTH_CONTEXT_KEY = Symbol('auth');
@@ -16,7 +32,7 @@ export function createAuthStore() {
mutationFn: ({ username, email, password }) => setupAccount(username, email, password), mutationFn: ({ username, email, password }) => setupAccount(username, email, password),
})); }));
const loginMutation = createMutation(() => ({ const loginMutation = createMutation(() => ({
mutationFn: ({ identifier, password }) => login(identifier, password), mutationFn: ({ identifier, password, totpToken }) => login(identifier, password, totpToken),
})); }));
const logoutMutation = createMutation(() => ({ const logoutMutation = createMutation(() => ({
mutationFn: () => logout(), mutationFn: () => logout(),
@@ -41,10 +57,31 @@ export function createAuthStore() {
await setupMutation.mutateAsync({ username, email, password }); await setupMutation.mutateAsync({ username, email, password });
await refresh(); await refresh();
}, },
async login(identifier, password) { async login(identifier, password, totpToken = '') {
await loginMutation.mutateAsync({ identifier, password }); await loginMutation.mutateAsync({ identifier, password, totpToken });
await refresh(); await refresh();
}, },
async totpStatus() {
const result = await fetchTotpStatus();
return result?.enabled === true;
},
async setupTotp() {
return setupTotp();
},
async enableTotp(token) {
await enableTotp(token);
await refresh();
},
async disableTotp(token) {
await disableTotp(token);
await refresh();
},
async requestAdminReset() {
await requestAdminReset();
},
async confirmAdminReset(code) {
await confirmAdminReset(code);
},
async logout() { async logout() {
await logoutMutation.mutateAsync(); await logoutMutation.mutateAsync();
await refresh(); await refresh();
@@ -53,6 +90,18 @@ export function createAuthStore() {
await updateCredentialsMutation.mutateAsync(input); await updateCredentialsMutation.mutateAsync(input);
await refresh(); await refresh();
}, },
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); setContext(AUTH_CONTEXT_KEY, store);
@@ -26,11 +26,12 @@
<Tooltip.Provider delayDuration={300}> <Tooltip.Provider delayDuration={300}>
{#if auth.loading} {#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} {:else if auth.error}
<div class="flex min-h-screen items-center justify-center px-4 text-sm text-danger"> <AuthPage
{auth.error instanceof Error ? auth.error.message : 'Request failed.'} setupRequired={auth.status?.setupRequired ?? true}
</div> error={auth.error instanceof Error ? auth.error.message : 'Request failed.'}
/>
{:else if !auth.status || auth.status.setupRequired || !auth.status.authenticated} {:else if !auth.status || auth.status.setupRequired || !auth.status.authenticated}
<AuthPage setupRequired={auth.status?.setupRequired ?? true} /> <AuthPage setupRequired={auth.status?.setupRequired ?? true} />
{:else} {:else}
@@ -44,17 +45,33 @@
onProfile={() => (credentialsOpen = true)} onProfile={() => (credentialsOpen = true)}
onSettings={() => (settingsOpen = true)} onSettings={() => (settingsOpen = true)}
> >
{#snippet children()}
{@render children?.()} {@render children?.()}
{/snippet}
</SharedAppShell> </SharedAppShell>
{/if} {/if}
</Tooltip.Provider> </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 <ProfileDialog
bind:open={credentialsOpen} bind:open={credentialsOpen}
currentUsername={auth.status?.username ?? ''} currentUsername={auth.status?.username ?? ''}
currentEmail={auth.status?.email ?? ''} 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} 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)}
/> />
@@ -6,12 +6,29 @@
import { currentLanguage, languages, setLanguage } from '$lib/language.svelte.js'; import { currentLanguage, languages, setLanguage } from '$lib/language.svelte.js';
import { themeState } from '$lib/theme.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 })); const languageItems = languages.map((language) => ({ value: language.id, label: language.label }));
</script> </script>
<SharedSettingsDialog bind:open title="Settings"> <SharedSettingsDialog
bind:open
currentRole={currentRole}
currentUserId={currentUserId}
onCreateUser={onCreateUser}
onDeleteUser={onDeleteUser}
onListUsers={onListUsers}
onUpdateUser={onUpdateUser}
title="Settings"
>
<div> <div>
<span class="mb-2 block text-sm font-medium">Theme</span> <span class="mb-2 block text-sm font-medium">Theme</span>
<div class="flex w-full rounded-md border border-border p-1"> <div class="flex w-full rounded-md border border-border p-1">