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
+4202
-3606
No files matched your search
+290
-8
@@ -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) {
|
||||||
@@ -170,10 +172,14 @@ 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"`
|
||||||
Username string `json:"username,omitempty"`
|
ID int64 `json:"id,omitempty"`
|
||||||
Email string `json:"email,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 {
|
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
@@ -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 {
|
||||||
|
|||||||
@@ -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))
|
||||||
|
|
||||||
|
|||||||
Generated
+3628
-3571
File diff suppressed because it is too large.
Load diff
+47
-2
@@ -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}
|
||||||
/>
|
/>
|
||||||
@@ -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">
|
||||||
|
|||||||
Reference in new issue
Block a user