This commit is contained in:
1 parent
9a6ec940f7
commit
fd32419371
114 files changed
+21997
-96
No files matched your search
@@ -0,0 +1,956 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID int64 `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Role string `json:"role,omitempty"`
|
||||
CanManageUsers bool `json:"canManageUsers"`
|
||||
Bio string `json:"bio,omitempty"`
|
||||
Avatar string `json:"avatarUrl,omitempty"`
|
||||
MFAEnabled bool `json:"mfaEnabled"`
|
||||
}
|
||||
|
||||
type storedUser struct {
|
||||
User
|
||||
PasswordHash string
|
||||
Disabled bool
|
||||
TOTPSecret string
|
||||
}
|
||||
|
||||
type contextKey struct{}
|
||||
|
||||
var userContextKey contextKey
|
||||
|
||||
var (
|
||||
ErrUnauthorized = errors.New("authentication required")
|
||||
ErrForbidden = errors.New("administrator access required")
|
||||
ErrInvalidLogin = errors.New("Invalid username or password.")
|
||||
)
|
||||
|
||||
const loginRequiredSettingKey = "auth_required"
|
||||
|
||||
type Service struct {
|
||||
db *pgxpool.Pool
|
||||
cookieName string
|
||||
secureCookies bool
|
||||
sessionTTL time.Duration
|
||||
resetManager *sharedauth.ResetManager
|
||||
}
|
||||
|
||||
func New(db *pgxpool.Pool, cookieName string, secureCookies bool) *Service {
|
||||
return &Service{
|
||||
db: db,
|
||||
cookieName: cookieName,
|
||||
secureCookies: secureCookies,
|
||||
sessionTTL: 7 * 24 * time.Hour,
|
||||
resetManager: sharedauth.NewResetManager(),
|
||||
}
|
||||
}
|
||||
|
||||
func UserFromContext(ctx context.Context) *User {
|
||||
value, _ := ctx.Value(userContextKey).(*User)
|
||||
return value
|
||||
}
|
||||
|
||||
func (s *Service) CurrentUser(r *http.Request) (*User, error) {
|
||||
cookie, err := r.Cookie(s.cookieName)
|
||||
if errors.Is(err, http.ErrNoCookie) || cookie.Value == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
var user User
|
||||
var disabled bool
|
||||
err = s.db.QueryRow(ctx, `
|
||||
SELECT u.id, u.email, COALESCE(u.username, ''), COALESCE(u.role, 'user'),
|
||||
COALESCE(u.bio, ''), COALESCE(u.avatar_url, ''), u.disabled, COALESCE(u.mfa_enabled, false)
|
||||
FROM go_sessions session
|
||||
JOIN users u ON u.id = session.user_id
|
||||
WHERE session.token_hash = $1 AND session.expires_at > NOW()
|
||||
`, tokenHash(cookie.Value)).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Bio, &user.Avatar, &disabled, &user.MFAEnabled)
|
||||
if errors.Is(err, pgx.ErrNoRows) || disabled {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
user.CanManageUsers = sharedauth.CanManageUsers(user.Role)
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *Service) Optional(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := s.CurrentUser(r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "authentication lookup failed")
|
||||
return
|
||||
}
|
||||
if user != nil {
|
||||
r = r.WithContext(context.WithValue(r.Context(), userContextKey, user))
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) Require(next http.Handler) http.Handler {
|
||||
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if UserFromContext(r.Context()) == nil {
|
||||
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
}))
|
||||
}
|
||||
|
||||
// RequireIfLoginRequired protects actions when the application has login
|
||||
// enabled, while allowing explicitly public installations to use actions that
|
||||
// do not need a user identity.
|
||||
func (s *Service) RequireIfLoginRequired(next http.Handler) http.Handler {
|
||||
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if UserFromContext(r.Context()) != nil {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
loginRequired, err := s.LoginRequired(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||
return
|
||||
}
|
||||
if !loginRequired {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||
}))
|
||||
}
|
||||
|
||||
func (s *Service) RequireAdmin(next http.Handler) http.Handler {
|
||||
return s.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user := UserFromContext(r.Context())
|
||||
if !IsAdmin(user) {
|
||||
writeError(w, http.StatusForbidden, ErrForbidden.Error())
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
}))
|
||||
}
|
||||
|
||||
// RequireAdminIfLoginRequired keeps administrative actions protected for
|
||||
// authenticated users, while allowing explicitly public installations to use
|
||||
// configuration endpoints that do not require a user identity.
|
||||
func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler {
|
||||
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user := UserFromContext(r.Context())
|
||||
if user == nil {
|
||||
loginRequired, err := s.LoginRequired(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||
return
|
||||
}
|
||||
if !loginRequired {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||
return
|
||||
}
|
||||
if !IsAdmin(user) {
|
||||
writeError(w, http.StatusForbidden, ErrForbidden.Error())
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
}))
|
||||
}
|
||||
|
||||
func IsAdmin(user *User) bool {
|
||||
if user == nil {
|
||||
return false
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(user.Role)) {
|
||||
case "admin", "superadmin", "moderator":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) Me(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := s.CurrentUser(r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "authentication lookup failed")
|
||||
return
|
||||
}
|
||||
count, err := s.CountUsers(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||
return
|
||||
}
|
||||
loginRequired, err := s.LoginRequired(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"user": user,
|
||||
"authRequired": loginRequired,
|
||||
"setupRequired": count == 0,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
||||
user := UserFromContext(r.Context())
|
||||
if user == nil {
|
||||
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var input struct {
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSON(r, &input); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
|
||||
email := strings.ToLower(strings.TrimSpace(input.Email))
|
||||
username := strings.TrimSpace(input.Username)
|
||||
if !strings.Contains(email, "@") || len(email) > 254 {
|
||||
writeError(w, http.StatusBadRequest, "a valid email is required")
|
||||
return
|
||||
}
|
||||
if username == "" || len([]rune(username)) > 64 {
|
||||
writeError(w, http.StatusBadRequest, "a username is required")
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash := ""
|
||||
if input.Password != "" {
|
||||
if err := validatePassword(input.Password); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "password could not be updated")
|
||||
return
|
||||
}
|
||||
passwordHash = string(hash)
|
||||
}
|
||||
|
||||
if _, err := s.db.Exec(r.Context(), `
|
||||
UPDATE users
|
||||
SET email = $1, username = $2, password_hash = COALESCE(NULLIF($3, ''), password_hash)
|
||||
WHERE id = $4
|
||||
`, email, username, passwordHash, user.ID); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "profile could not be updated")
|
||||
return
|
||||
}
|
||||
|
||||
updated, err := s.CurrentUser(r)
|
||||
if err != nil || updated == nil {
|
||||
writeError(w, http.StatusInternalServerError, "profile could not be loaded")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": updated})
|
||||
}
|
||||
|
||||
func (s *Service) RequireUserManager(next http.Handler) http.Handler {
|
||||
return s.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user := UserFromContext(r.Context())
|
||||
if !sharedauth.CanManageUsers(user.Role) {
|
||||
writeError(w, http.StatusForbidden, ErrForbidden.Error())
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
}))
|
||||
}
|
||||
|
||||
func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
|
||||
count, err := s.CountUsers(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": count == 0})
|
||||
}
|
||||
|
||||
func (s *Service) LoginRequired(ctx context.Context) (bool, error) {
|
||||
var value string
|
||||
err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key = $1`, loginRequiredSettingKey).Scan(&value)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "false", "0", "no", "off":
|
||||
return false, nil
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) {
|
||||
loginRequired, err := s.LoginRequired(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "access settings unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"loginRequired": loginRequired})
|
||||
}
|
||||
|
||||
func (s *Service) UpdateAccessSettings(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
LoginRequired *bool `json:"loginRequired"`
|
||||
}
|
||||
if err := decodeJSON(r, &input); err != nil || input.LoginRequired == nil {
|
||||
writeError(w, http.StatusBadRequest, "loginRequired must be a boolean")
|
||||
return
|
||||
}
|
||||
if _, err := s.db.Exec(r.Context(), `
|
||||
INSERT INTO settings (key, value, updated_at)
|
||||
VALUES ($1, $2, NOW())
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
|
||||
`, loginRequiredSettingKey, strconv.FormatBool(*input.LoginRequired)); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "access setting could not be saved")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"loginRequired": *input.LoginRequired})
|
||||
}
|
||||
|
||||
func (s *Service) Status(w http.ResponseWriter, r *http.Request) {
|
||||
count, err := s.CountUsers(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||
return
|
||||
}
|
||||
user, _ := s.CurrentUser(r)
|
||||
loginRequired, err := s.LoginRequired(r.Context())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"setupRequired": count == 0,
|
||||
"authenticated": user != nil,
|
||||
"authRequired": loginRequired,
|
||||
"user": user,
|
||||
})
|
||||
}
|
||||
|
||||
type managedAccount struct {
|
||||
ID int64
|
||||
Email string
|
||||
Username string
|
||||
Role string
|
||||
Disabled bool
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (s *Service) managedAccount(ctx context.Context, id int64) (*managedAccount, error) {
|
||||
var user managedAccount
|
||||
err := s.db.QueryRow(ctx, `
|
||||
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at
|
||||
FROM users WHERE id = $1
|
||||
`, id).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Disabled, &user.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func managedAccountPayload(user *managedAccount) map[string]any {
|
||||
return map[string]any{
|
||||
"id": user.ID,
|
||||
"username": user.Username,
|
||||
"email": user.Email,
|
||||
"role": string(sharedauth.NormalizeRole(user.Role)),
|
||||
"createdAt": user.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) ManagedUsers(w http.ResponseWriter, r *http.Request) {
|
||||
rows, err := s.db.Query(r.Context(), `
|
||||
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at
|
||||
FROM users ORDER BY created_at, id
|
||||
`)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "users unavailable")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
users := make([]map[string]any, 0)
|
||||
for rows.Next() {
|
||||
var user managedAccount
|
||||
if err := rows.Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Disabled, &user.CreatedAt); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "users unavailable")
|
||||
return
|
||||
}
|
||||
users = append(users, managedAccountPayload(&user))
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "users unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, users)
|
||||
}
|
||||
|
||||
func (s *Service) ManagedCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
if err := decodeJSON(r, &input); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
actor := UserFromContext(r.Context())
|
||||
role := sharedauth.NormalizeRole(input.Role)
|
||||
if role == sharedauth.RoleSuperAdmin {
|
||||
writeError(w, http.StatusBadRequest, "a new user cannot be a superadmin")
|
||||
return
|
||||
}
|
||||
if actor == nil || sharedauth.NormalizeRole(actor.Role) != sharedauth.RoleSuperAdmin {
|
||||
role = sharedauth.RoleUser
|
||||
}
|
||||
user, err := s.CreateUser(r.Context(), input.Email, input.Username, input.Password, string(role))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
created, err := s.managedAccount(r.Context(), user.ID)
|
||||
if err != nil || created == nil {
|
||||
writeError(w, http.StatusInternalServerError, "user could not be loaded")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, managedAccountPayload(created))
|
||||
}
|
||||
|
||||
func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid user id")
|
||||
return
|
||||
}
|
||||
target, err := s.managedAccount(r.Context(), id)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "user could not be loaded")
|
||||
return
|
||||
}
|
||||
if target == nil {
|
||||
writeError(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Role *string `json:"role"`
|
||||
}
|
||||
if err := decodeJSON(r, &input); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
actor := UserFromContext(r.Context())
|
||||
targetRole := sharedauth.NormalizeRole(target.Role)
|
||||
role := targetRole
|
||||
if targetRole != sharedauth.RoleSuperAdmin && actor != nil && sharedauth.NormalizeRole(actor.Role) == sharedauth.RoleSuperAdmin && input.Role != nil {
|
||||
requested := sharedauth.NormalizeRole(*input.Role)
|
||||
if requested == sharedauth.RoleSuperAdmin {
|
||||
writeError(w, http.StatusBadRequest, "the superadmin role is protected")
|
||||
return
|
||||
}
|
||||
role = requested
|
||||
}
|
||||
if err := s.UpdateUser(r.Context(), id, input.Email, input.Username, string(role), nil); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "user could not be updated")
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(input.Password) != "" {
|
||||
if err := s.SetPassword(r.Context(), id, input.Password); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "password could not be updated")
|
||||
return
|
||||
}
|
||||
}
|
||||
updated, err := s.managedAccount(r.Context(), id)
|
||||
if err != nil || updated == nil {
|
||||
writeError(w, http.StatusInternalServerError, "user could not be loaded")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, managedAccountPayload(updated))
|
||||
}
|
||||
|
||||
func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid user id")
|
||||
return
|
||||
}
|
||||
target, err := s.managedAccount(r.Context(), id)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "user could not be loaded")
|
||||
return
|
||||
}
|
||||
if target == nil {
|
||||
writeError(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
actor := UserFromContext(r.Context())
|
||||
if actor == nil || actor.ID == target.ID || sharedauth.NormalizeRole(target.Role) == sharedauth.RoleSuperAdmin {
|
||||
writeError(w, http.StatusForbidden, "the current or first account cannot be removed")
|
||||
return
|
||||
}
|
||||
if err := s.DeleteUser(r.Context(), id); err != nil {
|
||||
writeError(w, http.StatusNotFound, "user not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSON(r, &input); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
email, username, password, err := normalizeCredentials(input.Email, input.Username, input.Password)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if username == "" {
|
||||
writeError(w, http.StatusBadRequest, "a username is required")
|
||||
return
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not secure password")
|
||||
return
|
||||
}
|
||||
var user User
|
||||
err = s.db.QueryRow(r.Context(), `
|
||||
INSERT INTO users (email, username, password_hash, role)
|
||||
SELECT $1, $2, $3, 'superadmin'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM users)
|
||||
RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'superadmin')
|
||||
`, email, username, string(hash)).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusConflict, "Setup has already been completed.")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not create account")
|
||||
return
|
||||
}
|
||||
user.CanManageUsers = sharedauth.CanManageUsers(user.Role)
|
||||
if err := s.startSession(w, r.Context(), user.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not start session")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"user": user})
|
||||
}
|
||||
|
||||
func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
Identifier string `json:"identifier"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
TOTPToken string `json:"totpToken"`
|
||||
}
|
||||
if err := decodeJSON(r, &input); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
identifier := strings.TrimSpace(input.Identifier)
|
||||
if identifier == "" {
|
||||
identifier = strings.TrimSpace(input.Email)
|
||||
}
|
||||
var user storedUser
|
||||
err := s.db.QueryRow(r.Context(), `
|
||||
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), COALESCE(bio, ''),
|
||||
COALESCE(avatar_url, ''), password_hash, disabled, COALESCE(mfa_enabled, false), COALESCE(totp_secret, '')
|
||||
FROM users WHERE LOWER(email) = LOWER($1) OR LOWER(COALESCE(username, '')) = LOWER($1)
|
||||
LIMIT 1
|
||||
`, identifier).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Bio, &user.Avatar, &user.PasswordHash, &user.Disabled, &user.MFAEnabled, &user.TOTPSecret)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not authenticate")
|
||||
return
|
||||
}
|
||||
user.User.CanManageUsers = sharedauth.CanManageUsers(user.Role)
|
||||
if user.Disabled || bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(input.Password)) != nil {
|
||||
writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
|
||||
return
|
||||
}
|
||||
if user.MFAEnabled && !sharedauth.VerifyTOTP(user.TOTPSecret, strings.TrimSpace(input.TOTPToken), time.Now()) {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "Two-factor authentication code required.", "mfaRequired": true})
|
||||
return
|
||||
}
|
||||
_, _ = s.db.Exec(r.Context(), `UPDATE users SET last_login_at = NOW() WHERE id = $1`, user.ID)
|
||||
if err := s.startSession(w, r.Context(), user.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not start session")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": user.User})
|
||||
}
|
||||
|
||||
func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) {
|
||||
user := UserFromContext(r.Context())
|
||||
if user == nil {
|
||||
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"enabled": user.MFAEnabled, "mfaEnabled": user.MFAEnabled})
|
||||
}
|
||||
|
||||
func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) {
|
||||
user := UserFromContext(r.Context())
|
||||
if user == nil {
|
||||
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||
return
|
||||
}
|
||||
if user.MFAEnabled {
|
||||
writeError(w, http.StatusConflict, "multi-factor authentication is already enabled")
|
||||
return
|
||||
}
|
||||
secret, err := sharedauth.GenerateTOTPSecret()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not create authenticator secret")
|
||||
return
|
||||
}
|
||||
if _, err := s.db.Exec(r.Context(), `UPDATE users SET totp_secret = $1, mfa_enabled = false WHERE id = $2`, secret, user.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not save authenticator secret")
|
||||
return
|
||||
}
|
||||
account := user.Username
|
||||
if account == "" {
|
||||
account = user.Email
|
||||
}
|
||||
uri := sharedauth.TOTPProvisioningURI("MediaCollection", account, secret)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"secret": secret, "otpauth": uri, "otpauthUrl": uri, "enabled": false}})
|
||||
}
|
||||
|
||||
func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) {
|
||||
user := UserFromContext(r.Context())
|
||||
if user == nil {
|
||||
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Token string `json:"token"`
|
||||
TOTPToken string `json:"totpToken"`
|
||||
}
|
||||
if err := decodeJSON(r, &input); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
var secret string
|
||||
if err := s.db.QueryRow(r.Context(), `SELECT COALESCE(totp_secret, '') FROM users WHERE id = $1`, user.ID).Scan(&secret); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not load authenticator secret")
|
||||
return
|
||||
}
|
||||
token := strings.TrimSpace(input.TOTPToken)
|
||||
if token == "" {
|
||||
token = strings.TrimSpace(input.Token)
|
||||
}
|
||||
if !sharedauth.VerifyTOTP(secret, token, time.Now()) {
|
||||
writeError(w, http.StatusUnauthorized, "Invalid authenticator code.")
|
||||
return
|
||||
}
|
||||
if _, err := s.db.Exec(r.Context(), `UPDATE users SET mfa_enabled = true WHERE id = $1 AND totp_secret <> ''`, user.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not enable multi-factor authentication")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": true, "enabled": true, "backupCodes": []string{}}})
|
||||
}
|
||||
|
||||
func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) {
|
||||
user := UserFromContext(r.Context())
|
||||
if user == nil {
|
||||
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
Token string `json:"token"`
|
||||
TOTPToken string `json:"totpToken"`
|
||||
}
|
||||
if err := decodeJSON(r, &input); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
var secret string
|
||||
var enabled bool
|
||||
if err := s.db.QueryRow(r.Context(), `SELECT COALESCE(totp_secret, ''), COALESCE(mfa_enabled, false) FROM users WHERE id = $1`, user.ID).Scan(&secret, &enabled); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not load authenticator state")
|
||||
return
|
||||
}
|
||||
token := strings.TrimSpace(input.TOTPToken)
|
||||
if token == "" {
|
||||
token = strings.TrimSpace(input.Token)
|
||||
}
|
||||
if !enabled || !sharedauth.VerifyTOTP(secret, token, time.Now()) {
|
||||
writeError(w, http.StatusUnauthorized, "Invalid authenticator code.")
|
||||
return
|
||||
}
|
||||
if _, err := s.db.Exec(r.Context(), `UPDATE users SET mfa_enabled = false, totp_secret = NULL WHERE id = $1`, user.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not disable multi-factor authentication")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": false, "enabled": false}})
|
||||
}
|
||||
|
||||
func (s *Service) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
if cookie, err := r.Cookie(s.cookieName); err == nil && cookie.Value != "" {
|
||||
_, _ = s.db.Exec(r.Context(), `DELETE FROM go_sessions WHERE token_hash = $1`, tokenHash(cookie.Value))
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: s.cookieName, Value: "", Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, MaxAge: -1})
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Service) RequestAdminReset(w http.ResponseWriter, _ *http.Request) {
|
||||
if _, err := s.resetManager.Request(); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not create reset code")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Service) ConfirmAdminReset(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
if err := decodeJSON(r, &input); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
if !s.resetManager.Confirm(input.Code) {
|
||||
writeError(w, http.StatusUnauthorized, "Invalid or expired reset code.")
|
||||
return
|
||||
}
|
||||
if _, err := s.db.Exec(r.Context(), `DELETE FROM users`); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "could not reset administrator accounts")
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: s.cookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: s.secureCookies,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: -1,
|
||||
})
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (s *Service) CountUsers(ctx context.Context) (int64, error) {
|
||||
var count int64
|
||||
err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users`).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (s *Service) CreateUser(ctx context.Context, email, username, password, role string) (*User, error) {
|
||||
email, username, password, err := normalizeCredentials(email, username, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
role = normalizeRole(role)
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var user User
|
||||
err = s.db.QueryRow(ctx, `
|
||||
INSERT INTO users (email, username, password_hash, role)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'user')
|
||||
`, email, username, string(hash), role).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *Service) ListUsers(ctx context.Context, search string, limit, offset int) ([]map[string]any, int64, error) {
|
||||
search = strings.TrimSpace(search)
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
pattern := "%" + search + "%"
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at, last_login_at
|
||||
FROM users
|
||||
WHERE ($1 = '' OR email ILIKE $2 OR COALESCE(username, '') ILIKE $2)
|
||||
ORDER BY id DESC LIMIT $3 OFFSET $4
|
||||
`, search, pattern, limit, offset)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
users := make([]map[string]any, 0)
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
var email, username, role string
|
||||
var disabled bool
|
||||
var created time.Time
|
||||
var lastLogin *time.Time
|
||||
if err := rows.Scan(&id, &email, &username, &role, &disabled, &created, &lastLogin); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
users = append(users, map[string]any{"id": id, "email": email, "username": username, "role": role, "disabled": disabled, "createdAt": created, "lastLoginAt": lastLogin})
|
||||
}
|
||||
var total int64
|
||||
err = s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users WHERE ($1 = '' OR email ILIKE $2 OR COALESCE(username, '') ILIKE $2)`, search, pattern).Scan(&total)
|
||||
return users, total, err
|
||||
}
|
||||
|
||||
func (s *Service) DeleteUser(ctx context.Context, id int64) error {
|
||||
_, err := s.db.Exec(ctx, `DELETE FROM users WHERE id = $1`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Service) UpdateUser(ctx context.Context, id int64, email, username, role string, disabled *bool) error {
|
||||
role = strings.ToLower(strings.TrimSpace(role))
|
||||
if role != "" {
|
||||
role = normalizeRole(role)
|
||||
}
|
||||
_, err := s.db.Exec(ctx, `
|
||||
UPDATE users SET email = COALESCE(NULLIF($2, ''), email), username = COALESCE(NULLIF($3, ''), username),
|
||||
role = COALESCE(NULLIF($4, ''), role), disabled = COALESCE($5, disabled) WHERE id = $1
|
||||
`, id, strings.TrimSpace(email), strings.TrimSpace(username), role, disabled)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Service) SetPassword(ctx context.Context, id int64, password string) error {
|
||||
if err := validatePassword(password); err != nil {
|
||||
return err
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.Exec(ctx, `UPDATE users SET password_hash=$2 WHERE id=$1`, id, string(hash))
|
||||
return err
|
||||
}
|
||||
|
||||
func validatePassword(password string) error {
|
||||
if len([]rune(password)) < 8 || len([]rune(password)) > 1024 {
|
||||
return fmt.Errorf("Password must be at least 8 characters.")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) startSession(w http.ResponseWriter, ctx context.Context, userID int64) error {
|
||||
token, err := randomToken()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
expires := time.Now().Add(s.sessionTTL)
|
||||
if _, err := s.db.Exec(ctx, `INSERT INTO go_sessions (token_hash, user_id, expires_at) VALUES ($1, $2, $3)`, tokenHash(token), userID, expires); err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = s.db.Exec(ctx, `DELETE FROM go_sessions WHERE expires_at <= NOW()`)
|
||||
http.SetCookie(w, &http.Cookie{Name: s.cookieName, Value: token, Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, Expires: expires, MaxAge: int(s.sessionTTL.Seconds())})
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeCredentials(email, username, password string) (string, string, string, error) {
|
||||
email = strings.ToLower(strings.TrimSpace(email))
|
||||
username = strings.TrimSpace(username)
|
||||
if !strings.Contains(email, "@") || len(email) > 254 {
|
||||
return "", "", "", fmt.Errorf("a valid email is required")
|
||||
}
|
||||
if len([]rune(username)) > 64 {
|
||||
return "", "", "", fmt.Errorf("username is too long")
|
||||
}
|
||||
if len([]rune(password)) < 8 || len([]rune(password)) > 1024 {
|
||||
return "", "", "", fmt.Errorf("Password must be at least 8 characters.")
|
||||
}
|
||||
return email, username, password, nil
|
||||
}
|
||||
|
||||
func normalizeRole(role string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(role)) {
|
||||
case "admin", "superadmin", "moderator":
|
||||
return strings.ToLower(strings.TrimSpace(role))
|
||||
default:
|
||||
return "user"
|
||||
}
|
||||
}
|
||||
|
||||
func randomToken() (string, error) {
|
||||
data := make([]byte, 32)
|
||||
if _, err := rand.Read(data); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
func tokenHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, target any) error {
|
||||
defer r.Body.Close()
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024))
|
||||
return decoder.Decode(target)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, message string) {
|
||||
writeJSON(w, status, map[string]string{"error": message, "message": message})
|
||||
}
|
||||
|
||||
func (u User) String() string { return strconv.FormatInt(u.ID, 10) }
|
||||
@@ -0,0 +1,28 @@
|
||||
package auth
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizeCredentials(t *testing.T) {
|
||||
email, username, password, err := normalizeCredentials(" User@Example.com ", "user", "correct horse battery staple")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if email != "user@example.com" || username != "user" || password == "" {
|
||||
t.Fatalf("normalized credentials = %q, %q, %q", email, username, password)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCredentialsAllowsAdminEmailOnly(t *testing.T) {
|
||||
if _, _, _, err := normalizeCredentials("admin@example.com", "", "correct horse battery staple"); err != nil {
|
||||
t.Fatalf("empty optional username rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRole(t *testing.T) {
|
||||
if normalizeRole("MODERATOR") != "moderator" {
|
||||
t.Fatal("moderator role was not normalized")
|
||||
}
|
||||
if normalizeRole("unknown") != "user" {
|
||||
t.Fatal("unknown role was not reduced to user")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user