feat(auth): enhance authentication flow with TOTP and admin reset features
- Added TOTP setup, enable, and disable functions to the API. - Implemented admin reset request and confirmation functionalities. - Updated AuthPage to handle new reset functionalities and TOTP inputs. - Enhanced auth store to manage user creation, deletion, and listing. - Improved AppShell and SettingsDialog to support user management features. - Refactored API calls for better organization and clarity.
This commit is contained in:
1 parent
ac08be0248
commit
652e81dacb
9 files changed
+4333
-3737
No files matched your search
+290
-8
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -35,10 +36,11 @@ var (
|
||||
type AuthService struct {
|
||||
db *DB
|
||||
secureCookie bool
|
||||
reset *sharedauth.ResetManager
|
||||
}
|
||||
|
||||
func newAuthService(db *DB, secureCookie bool) *AuthService {
|
||||
return &AuthService{db: db, secureCookie: secureCookie}
|
||||
return &AuthService{db: db, secureCookie: secureCookie, reset: sharedauth.NewResetManager()}
|
||||
}
|
||||
|
||||
func normalizeUsername(value string) (string, error) {
|
||||
@@ -170,10 +172,14 @@ func extractBearer(r *http.Request) string {
|
||||
}
|
||||
|
||||
type authStatusResponse struct {
|
||||
SetupRequired bool `json:"setupRequired"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
SetupRequired bool `json:"setupRequired"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
ID int64 `json:"id,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Role string `json:"role,omitempty"`
|
||||
CanManageUsers bool `json:"canManageUsers,omitempty"`
|
||||
TotpEnabled bool `json:"totpEnabled,omitempty"`
|
||||
}
|
||||
|
||||
type credentialsRequest struct {
|
||||
@@ -181,6 +187,7 @@ type credentialsRequest struct {
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
TotpToken string `json:"totpToken"`
|
||||
}
|
||||
|
||||
func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -203,7 +210,43 @@ func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, CanManageUsers: sharedauth.CanManageUsers(user.Role), TotpEnabled: user.TOTPEnabled})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleResetRequest(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if _, err := a.reset.Request(); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Unable to create reset code")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleResetConfirm(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil || strings.TrimSpace(request.Code) == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Code required")
|
||||
return
|
||||
}
|
||||
if !a.reset.Confirm(request.Code) {
|
||||
writeJSONError(w, http.StatusUnauthorized, "Invalid or expired code")
|
||||
return
|
||||
}
|
||||
if err := a.db.deleteAllUsers(r.Context()); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Reset failed")
|
||||
return
|
||||
}
|
||||
a.clearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -256,7 +299,7 @@ func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, CanManageUsers: sharedauth.CanManageUsers(user.Role)})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -287,11 +330,84 @@ func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
||||
return
|
||||
}
|
||||
if user.TOTPEnabled && !sharedauth.VerifyTOTP(user.TOTPSecret, request.TotpToken, time.Now()) {
|
||||
writeJSONError(w, http.StatusUnauthorized, "two-factor authentication code required")
|
||||
return
|
||||
}
|
||||
if err := a.startSession(r.Context(), w, user.ID); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, CanManageUsers: sharedauth.CanManageUsers(user.Role), TotpEnabled: user.TOTPEnabled})
|
||||
}
|
||||
|
||||
type totpTokenRequest struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
func (a *AuthService) handleTOTPStatus(w http.ResponseWriter, _ *http.Request, user *AuthUser) {
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"enabled": user.TOTPEnabled})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleTOTPSetup(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
||||
if user.TOTPEnabled {
|
||||
writeJSONError(w, http.StatusConflict, "disable two-factor authentication before setting up a new secret")
|
||||
return
|
||||
}
|
||||
secret, err := sharedauth.GenerateTOTPSecret()
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "unable to create two-factor setup")
|
||||
return
|
||||
}
|
||||
if err := a.db.setTOTPSecret(r.Context(), user.ID, secret); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "unable to create two-factor setup")
|
||||
return
|
||||
}
|
||||
account := user.Email
|
||||
if account == "" {
|
||||
account = user.Username
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"secret": secret,
|
||||
"otpauthUrl": sharedauth.TOTPProvisioningURI("CollabTable", account, secret),
|
||||
"enabled": false,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleTOTPEnable(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
||||
var request totpTokenRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
secret, _, err := a.db.getTOTPState(r.Context(), user.ID)
|
||||
if err != nil || !sharedauth.VerifyTOTP(secret, request.Token, time.Now()) {
|
||||
writeJSONError(w, http.StatusUnauthorized, "invalid two-factor authentication code")
|
||||
return
|
||||
}
|
||||
if err := a.db.enableTOTP(r.Context(), user.ID); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "unable to enable two-factor authentication")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"enabled": true})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleTOTPDisable(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
||||
var request totpTokenRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
secret, enabled, err := a.db.getTOTPState(r.Context(), user.ID)
|
||||
if err != nil || !enabled || !sharedauth.VerifyTOTP(secret, request.Token, time.Now()) {
|
||||
writeJSONError(w, http.StatusUnauthorized, "invalid two-factor authentication code")
|
||||
return
|
||||
}
|
||||
if err := a.db.disableTOTP(r.Context(), user.ID); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "unable to disable two-factor authentication")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"enabled": false})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request, _ *AuthUser) {
|
||||
@@ -388,3 +504,169 @@ func (a *AuthService) handleTokenRegenerate(w http.ResponseWriter, r *http.Reque
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"token": token})
|
||||
}
|
||||
|
||||
type managedUserResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Role string `json:"role"`
|
||||
TotpEnabled bool `json:"totpEnabled"`
|
||||
}
|
||||
|
||||
type managedUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Role *string `json:"role"`
|
||||
}
|
||||
|
||||
func managedUserView(user AuthUser) managedUserResponse {
|
||||
return managedUserResponse{ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, TotpEnabled: user.TOTPEnabled}
|
||||
}
|
||||
|
||||
func (a *AuthService) requireUserManager(w http.ResponseWriter, user *AuthUser) bool {
|
||||
if sharedauth.CanManageUsers(user.Role) {
|
||||
return true
|
||||
}
|
||||
writeJSONError(w, http.StatusForbidden, "administrator access required")
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *AuthService) handleUsers(w http.ResponseWriter, r *http.Request, actor *AuthUser) {
|
||||
if !a.requireUserManager(w, actor) {
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
users, err := a.db.listUsers(r.Context())
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Unable to list users")
|
||||
return
|
||||
}
|
||||
result := make([]managedUserResponse, 0, len(users))
|
||||
for _, user := range users {
|
||||
result = append(result, managedUserView(user))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
case http.MethodPost:
|
||||
var request managedUserRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
username, err := normalizeUsername(request.Username)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
email, err := normalizeEmail(request.Email)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := validatePassword(request.Password); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
hash, err := sharedauth.HashPassword(request.Password)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Unable to create user")
|
||||
return
|
||||
}
|
||||
role := string(sharedauth.RoleUser)
|
||||
if actor.Role == string(sharedauth.RoleSuperAdmin) && request.Role != nil {
|
||||
role = string(sharedauth.NormalizeRole(*request.Role))
|
||||
}
|
||||
created, err := a.db.createManagedUser(r.Context(), username, email, string(hash), role)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusConflict, "Username or email is already in use")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, managedUserView(*created))
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *AuthService) handleUser(w http.ResponseWriter, r *http.Request, actor *AuthUser) {
|
||||
if !a.requireUserManager(w, actor) {
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid user id")
|
||||
return
|
||||
}
|
||||
target, err := a.db.getUserByID(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Unable to find user")
|
||||
return
|
||||
}
|
||||
if target == nil {
|
||||
writeJSONError(w, http.StatusNotFound, "User not found")
|
||||
return
|
||||
}
|
||||
if target.Role == string(sharedauth.RoleSuperAdmin) && target.ID != actor.ID {
|
||||
writeJSONError(w, http.StatusForbidden, "The superadmin account is protected")
|
||||
return
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodPut, http.MethodPatch:
|
||||
var request managedUserRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
username := target.Username
|
||||
if request.Username != "" {
|
||||
username, err = normalizeUsername(request.Username)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
email := target.Email
|
||||
if request.Email != "" {
|
||||
email, err = normalizeEmail(request.Email)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
passwordHash := target.PasswordHash
|
||||
if request.Password != "" {
|
||||
if err := validatePassword(request.Password); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
hash, hashErr := sharedauth.HashPassword(request.Password)
|
||||
if hashErr != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Unable to update user")
|
||||
return
|
||||
}
|
||||
passwordHash = string(hash)
|
||||
}
|
||||
role := target.Role
|
||||
if actor.Role == string(sharedauth.RoleSuperAdmin) && request.Role != nil && target.Role != string(sharedauth.RoleSuperAdmin) {
|
||||
role = string(sharedauth.NormalizeRole(*request.Role))
|
||||
}
|
||||
if err := a.db.updateManagedUser(r.Context(), id, username, email, passwordHash, role); err != nil {
|
||||
writeJSONError(w, http.StatusConflict, "Username or email is already in use")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
case http.MethodDelete:
|
||||
if target.ID == actor.ID || target.Role == string(sharedauth.RoleSuperAdmin) {
|
||||
writeJSONError(w, http.StatusForbidden, "This user cannot be deleted")
|
||||
return
|
||||
}
|
||||
if err := a.db.deleteUser(r.Context(), id); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Unable to delete user")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
default:
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user