2026-08-03 18:07:40 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"crypto/rand"
|
|
|
|
|
"crypto/sha256"
|
|
|
|
|
"encoding/base64"
|
|
|
|
|
"encoding/hex"
|
|
|
|
|
"errors"
|
|
|
|
|
"net/http"
|
2026-08-05 14:58:07 +02:00
|
|
|
"strconv"
|
2026-08-03 18:07:40 +02:00
|
|
|
"strings"
|
|
|
|
|
"time"
|
|
|
|
|
|
2026-08-04 17:05:37 +02:00
|
|
|
sharedauth "repos.gfranz.ch/Gabriel20xx/SharedCode/backend/auth"
|
2026-08-03 18:07:40 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
sessionCookieName = "collabtable_session"
|
|
|
|
|
sessionTTL = 24 * time.Hour
|
|
|
|
|
minPasswordLength = 8
|
|
|
|
|
maxUsernameLength = 64
|
2026-08-03 20:31:32 +02:00
|
|
|
maxEmailLength = 254
|
2026-08-03 18:07:40 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var (
|
|
|
|
|
errAuthRequired = errors.New("Authentication required")
|
|
|
|
|
errSetupComplete = errors.New("Setup has already been completed.")
|
|
|
|
|
errInvalidCredentials = errors.New("Invalid username or password.")
|
|
|
|
|
errUsernameRequired = errors.New("Username is required.")
|
2026-08-03 20:31:32 +02:00
|
|
|
errEmailRequired = errors.New("Email is required and must be valid.")
|
2026-08-03 18:07:40 +02:00
|
|
|
errPasswordTooShort = errors.New("Password must be at least 8 characters.")
|
|
|
|
|
errCurrentPasswordBad = errors.New("Current password is incorrect.")
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type AuthService struct {
|
|
|
|
|
db *DB
|
|
|
|
|
secureCookie bool
|
2026-08-05 14:58:07 +02:00
|
|
|
reset *sharedauth.ResetManager
|
2026-08-03 18:07:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func newAuthService(db *DB, secureCookie bool) *AuthService {
|
2026-08-05 14:58:07 +02:00
|
|
|
return &AuthService{db: db, secureCookie: secureCookie, reset: sharedauth.NewResetManager()}
|
2026-08-03 18:07:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func normalizeUsername(value string) (string, error) {
|
|
|
|
|
value = strings.TrimSpace(value)
|
|
|
|
|
if value == "" || len([]rune(value)) > maxUsernameLength {
|
|
|
|
|
return "", errUsernameRequired
|
|
|
|
|
}
|
|
|
|
|
return value, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-03 20:31:32 +02:00
|
|
|
func normalizeEmail(value string) (string, error) {
|
|
|
|
|
value = strings.ToLower(strings.TrimSpace(value))
|
|
|
|
|
if value == "" || len([]rune(value)) > maxEmailLength || strings.Count(value, "@") != 1 {
|
|
|
|
|
return "", errEmailRequired
|
|
|
|
|
}
|
|
|
|
|
parts := strings.SplitN(value, "@", 2)
|
|
|
|
|
if parts[0] == "" || parts[1] == "" || !strings.Contains(parts[1], ".") {
|
|
|
|
|
return "", errEmailRequired
|
|
|
|
|
}
|
|
|
|
|
return value, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-03 18:07:40 +02:00
|
|
|
func validatePassword(value string) error {
|
|
|
|
|
if len([]rune(value)) < minPasswordLength {
|
|
|
|
|
return errPasswordTooShort
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func randomToken() (string, error) {
|
|
|
|
|
buffer := make([]byte, 32)
|
|
|
|
|
if _, err := rand.Read(buffer); err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
return base64.RawURLEncoding.EncodeToString(buffer), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func hashToken(token string) string {
|
|
|
|
|
sum := sha256.Sum256([]byte(token))
|
|
|
|
|
return hex.EncodeToString(sum[:])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) setSessionCookie(w http.ResponseWriter, token string, expiresAt time.Time) {
|
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
|
|
|
Name: sessionCookieName,
|
|
|
|
|
Value: token,
|
|
|
|
|
Path: "/",
|
|
|
|
|
HttpOnly: true,
|
|
|
|
|
Secure: a.secureCookie,
|
|
|
|
|
SameSite: http.SameSiteLaxMode,
|
|
|
|
|
Expires: expiresAt,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) clearSessionCookie(w http.ResponseWriter) {
|
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
|
|
|
Name: sessionCookieName,
|
|
|
|
|
Value: "",
|
|
|
|
|
Path: "/",
|
|
|
|
|
HttpOnly: true,
|
|
|
|
|
Secure: a.secureCookie,
|
|
|
|
|
SameSite: http.SameSiteLaxMode,
|
|
|
|
|
MaxAge: -1,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) startSession(ctx context.Context, w http.ResponseWriter, userID int64) error {
|
|
|
|
|
token, err := randomToken()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
expiresAt := time.Now().Add(sessionTTL)
|
|
|
|
|
if err := a.db.createSession(ctx, userID, hashToken(token), expiresAt); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
a.setSessionCookie(w, token, expiresAt)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) currentUser(r *http.Request) (*AuthUser, error) {
|
|
|
|
|
cookie, err := r.Cookie(sessionCookieName)
|
|
|
|
|
if err != nil || cookie.Value == "" {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return a.db.getSessionUser(r.Context(), hashToken(cookie.Value))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) requireSession(next func(http.ResponseWriter, *http.Request, *AuthUser)) http.Handler {
|
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
user, err := a.currentUser(r)
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if user == nil {
|
|
|
|
|
writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
next(w, r, user)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) requireAPIToken(next http.Handler) http.Handler {
|
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
token := extractBearer(r)
|
|
|
|
|
if token == "" {
|
|
|
|
|
writeJSONError(w, http.StatusUnauthorized, "No bearer token provided")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
userID, err := a.db.getAPITokenUserID(r.Context(), hashToken(token))
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if userID == 0 {
|
|
|
|
|
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func extractBearer(r *http.Request) string {
|
|
|
|
|
header := r.Header.Get("Authorization")
|
|
|
|
|
if !strings.HasPrefix(header, "Bearer ") {
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
return strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type authStatusResponse struct {
|
2026-08-05 14:58:07 +02:00
|
|
|
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"`
|
2026-08-03 18:07:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type credentialsRequest struct {
|
2026-08-03 20:31:32 +02:00
|
|
|
Identifier string `json:"identifier"`
|
|
|
|
|
Username string `json:"username"`
|
|
|
|
|
Email string `json:"email"`
|
|
|
|
|
Password string `json:"password"`
|
2026-08-05 14:58:07 +02:00
|
|
|
TotpToken string `json:"totpToken"`
|
2026-08-03 18:07:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
count, err := a.db.countUsers(r.Context())
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if count == 0 {
|
|
|
|
|
writeJSON(w, http.StatusOK, authStatusResponse{SetupRequired: true})
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
user, err := a.currentUser(r)
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if user == nil {
|
|
|
|
|
writeJSON(w, http.StatusOK, authStatusResponse{})
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-05 14:58:07 +02:00
|
|
|
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})
|
2026-08-03 18:07:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
var request credentialsRequest
|
|
|
|
|
if err := decodeJSON(r, &request); err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
count, err := a.db.countUsers(r.Context())
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if count > 0 {
|
|
|
|
|
writeJSONError(w, http.StatusConflict, errSetupComplete.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
username, err := normalizeUsername(request.Username)
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-03 20:31:32 +02:00
|
|
|
email, err := normalizeEmail(request.Email)
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-03 18:07:40 +02:00
|
|
|
if err := validatePassword(request.Password); err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-04 17:05:37 +02:00
|
|
|
hash, err := sharedauth.HashPassword(request.Password)
|
2026-08-03 18:07:40 +02:00
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-03 20:31:32 +02:00
|
|
|
user, err := a.db.createUser(r.Context(), username, email, string(hash))
|
2026-08-03 18:07:40 +02:00
|
|
|
if err != nil {
|
|
|
|
|
if errors.Is(err, ErrSingletonUserExists) {
|
|
|
|
|
writeJSONError(w, http.StatusConflict, errSetupComplete.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if err := a.startSession(r.Context(), w, user.ID); err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-05 14:58:07 +02:00
|
|
|
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, CanManageUsers: sharedauth.CanManageUsers(user.Role)})
|
2026-08-03 18:07:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
var request credentialsRequest
|
|
|
|
|
if err := decodeJSON(r, &request); err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-03 20:31:32 +02:00
|
|
|
identifier := strings.TrimSpace(request.Identifier)
|
|
|
|
|
if identifier == "" {
|
|
|
|
|
identifier = strings.TrimSpace(request.Username)
|
|
|
|
|
}
|
|
|
|
|
if identifier == "" {
|
2026-08-03 18:07:40 +02:00
|
|
|
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-03 20:31:32 +02:00
|
|
|
if len([]rune(identifier)) > maxEmailLength {
|
|
|
|
|
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
user, err := a.db.getUserByIdentifier(r.Context(), identifier)
|
2026-08-03 18:07:40 +02:00
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-04 17:05:37 +02:00
|
|
|
if user == nil || !sharedauth.VerifyPassword(user.PasswordHash, request.Password) {
|
2026-08-03 18:07:40 +02:00
|
|
|
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-05 14:58:07 +02:00
|
|
|
if user.TOTPEnabled && !sharedauth.VerifyTOTP(user.TOTPSecret, request.TotpToken, time.Now()) {
|
|
|
|
|
writeJSONError(w, http.StatusUnauthorized, "two-factor authentication code required")
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-03 18:07:40 +02:00
|
|
|
if err := a.startSession(r.Context(), w, user.ID); err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-05 14:58:07 +02:00
|
|
|
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})
|
2026-08-03 18:07:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request, _ *AuthUser) {
|
|
|
|
|
if cookie, err := r.Cookie(sessionCookieName); err == nil && cookie.Value != "" {
|
|
|
|
|
if err := a.db.deleteSession(r.Context(), hashToken(cookie.Value)); err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
a.clearSessionCookie(w)
|
|
|
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type updateCredentialsRequest struct {
|
2026-08-03 20:31:32 +02:00
|
|
|
CurrentPassword *string `json:"currentPassword"`
|
2026-08-03 18:07:40 +02:00
|
|
|
NewUsername *string `json:"newUsername"`
|
2026-08-03 20:31:32 +02:00
|
|
|
NewEmail *string `json:"newEmail"`
|
2026-08-03 18:07:40 +02:00
|
|
|
NewPassword *string `json:"newPassword"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
|
|
|
|
var request updateCredentialsRequest
|
|
|
|
|
if err := decodeJSON(r, &request); err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-04 17:05:37 +02:00
|
|
|
if request.CurrentPassword != nil && *request.CurrentPassword != "" && !sharedauth.VerifyPassword(user.PasswordHash, *request.CurrentPassword) {
|
2026-08-03 18:07:40 +02:00
|
|
|
writeJSONError(w, http.StatusBadRequest, errCurrentPasswordBad.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
username := user.Username
|
|
|
|
|
if request.NewUsername != nil {
|
|
|
|
|
username, _ = normalizeUsername(*request.NewUsername)
|
|
|
|
|
if username == "" {
|
|
|
|
|
writeJSONError(w, http.StatusBadRequest, errUsernameRequired.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-08-03 20:31:32 +02:00
|
|
|
email := user.Email
|
|
|
|
|
if request.NewEmail != nil {
|
|
|
|
|
normalized, err := normalizeEmail(*request.NewEmail)
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
email = normalized
|
|
|
|
|
}
|
2026-08-03 18:07:40 +02:00
|
|
|
|
|
|
|
|
passwordHash := user.PasswordHash
|
|
|
|
|
if request.NewPassword != nil && *request.NewPassword != "" {
|
|
|
|
|
if err := validatePassword(*request.NewPassword); err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-08-04 17:05:37 +02:00
|
|
|
hash, err := sharedauth.HashPassword(*request.NewPassword)
|
2026-08-03 18:07:40 +02:00
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
passwordHash = string(hash)
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-03 20:31:32 +02:00
|
|
|
if err := a.db.updateUserCredentials(r.Context(), user.ID, username, email, passwordHash); err != nil {
|
2026-08-03 18:07:40 +02:00
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if err := a.db.deleteSessionsForUser(r.Context(), user.ID); err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
a.clearSessionCookie(w)
|
|
|
|
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) handleTokenStatus(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
|
|
|
|
hasToken, err := a.db.hasAPIToken(r.Context(), user.ID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
writeJSON(w, http.StatusOK, map[string]bool{"hasToken": hasToken})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *AuthService) handleTokenRegenerate(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
|
|
|
|
token, err := randomToken()
|
|
|
|
|
if err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if err := a.db.regenerateAPIToken(r.Context(), user.ID, hashToken(token)); err != nil {
|
|
|
|
|
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
writeJSON(w, http.StatusOK, map[string]string{"token": token})
|
|
|
|
|
}
|
2026-08-05 14:58:07 +02:00
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
}
|
|
|
|
|
}
|