Files
shared/media-backend/internal/auth/auth.go
T
Gabriel20xxandClaude Sonnet 5 ee59571552 Rename ProjectConfigurator, restructure Projects workspace, retire MediaCollection naming
- Rename MediaConfig -> ProjectConfigurator throughout; drop the Parameters
  tab/page; rename the Mounts tab to Projects and restructure it into three
  sections: Central services, Main services, Third-party services
- Add a self-describe contract (GET /api/info returning name/tabs/mountTypes)
  and a server-side discovery proxy (POST /api/discover-service) so adding a
  main service only requires a URL
- Add ProjectConfigurator HA: multiple instances now sync their settings with
  each other (GET /api/settings/export, POST /api/settings/sync, a periodic
  background puller), last-write-wins per key by updated_at
- Add a generic, project-agnostic file-storage API on CarrierNode
  (GET/POST/DELETE /api/mount/{project}/{type}[/*]) driven by the same
  configured_mounts data the Projects workspace already writes, usable by any
  registered project, not just the media family
- Add last_login_at tracking to the shared auth Store/User (schema, queries,
  UpdateLastLogin) and surface it through the shared web-ui ManagedUser type
  and UserManagement component
- Retire the "MediaCollection" name: Go module -> repos.gfranz.ch/Gabriel20xx/shared/media-backend,
  binary -> mediabackend, session cookie default -> "session", media-webui
  merged into webui, media-shared-assets renamed to legacy-assets and pruned
  to the one file MediaDesktop still uses

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-04 15:02:16 +02:00

1214 lines
44 KiB
Go

// Package auth is the shared media-backend family's /auth/... and /api/auth/...
// handlers, proxied to AuthGuard.
//
// AuthGuard migration
// ====================
// This service used to be a fully self-contained auth implementation:
// account and session state lived in this service's own PostgreSQL
// `users`/`go_sessions` tables (see the database migration, whose
// CREATE TABLE statements are kept but no longer used for identity - see
// below).
//
// It now proxies every auth operation to AuthGuard (Web/Central/AuthGuard),
// a centralized identity service other projects in this workspace share,
// via the `authclient` package (Web/Central/shared/backend/authclient,
// resolved through this module's own `repos.gfranz.ch/Gabriel20xx/shared/backend`
// dependency - same module that already provided `sharedauth`). This
// service's own /auth/... and /api/auth/... URL paths and JSON response
// shapes are UNCHANGED - the frontend (webui) was not touched - only
// what backs them changed. This mirrors the migration
// Original/GameStream/backend/cmd/gamestreamd/auth.go and
// Forks/Bitmagnet/backend/internal/auth/service.go already did; read either
// file's top-of-file doc comment for the fuller rationale behind each
// design choice below.
//
// Unlike those two, this service still has a genuinely independent
// "loginRequired" concept (RequireIfLoginRequired/RequireAdminIfLoginRequired,
// backed by the `settings` table's `auth_required` key, toggled via
// GET/PUT /api/auth/access) predating this migration - a deployment can run
// with login turned OFF entirely so every action is available to anonymous
// visitors, independent of whether AuthGuard has any accounts at all. That
// toggle is NOT touched by this migration (it stays exactly as it was); only
// what CurrentUser resolves a session against changed. See "Auth-disabled
// mode" below for how the two interact.
//
// Session cookie / token model
// -----------------------------
// AuthGuard sets its own `auth_session` cookie (authclient.DefaultCookieName)
// on register/login, whose scope is entirely controlled by AuthGuard's own
// deployment config. Rather than inventing a second cookie and a mapping
// between "this service's session token" and "AuthGuard's session token",
// this service forwards AuthGuard's Set-Cookie header straight through to
// the browser on signup/login/logout (authclient.ForwardCookies), and reads
// that same `auth_session` cookie back off every incoming request to use as
// the bearer token on its server-to-server calls to AuthGuard
// (sessionToken/CurrentUser below). This service mints no session token of
// its own any more. The pre-migration SESSION_COOKIE name (configurable,
// default "session") is retained only as something Logout
// additionally clears, so a browser that still holds one from before this
// migration doesn't keep sending a now-meaningless cookie forever.
//
// Setup flow
// ----------
// This service's "first launch: create the admin account" flow doesn't map
// onto AuthGuard, which is not single-admin-scoped and has no concept of
// "this is service X's initial account". A tiny local flag of its own -
// the `settings` table's `setup_claimed` key (isSetupClaimed/tryClaimSetup/
// unclaimSetup below, reusing the same table/mechanism as `auth_required`
// rather than a new one) - means only "has this deployment completed its
// setup screen once", with no credentials of any kind in it. Signup
// atomically claims that flag, registers the account against AuthGuard's
// POST /api/register, and unclaims it again if registration fails.
//
// The local claim alone would still show the "create account" form to a
// second `-service` deployment's own first launch (or a second
// AuthGuard-connected project entirely) even though AuthGuard already has an
// account from the first one, since accounts are centralized. AdminNeeded
// and Signup both additionally call AuthGuard's GET /api/setup-status
// (authclient.Client.SetupStatus) and treat "AuthGuard already has an
// account" the same as "already claimed locally": report no setup needed,
// refuse another registration through this flow.
//
// Known gaps versus the pre-migration behavior (AuthGuard was deliberately
// not modified for this migration, so these can only be closed by adding to
// AuthGuard itself later):
// - Self-service profile editing (PUT /auth/me) needs AuthGuard's
// admin/users endpoint, which requires CanManageUsers. A plain
// "user"-role account has no self-service way to change its own
// username/email/password via AuthGuard today; see UpdateMe.
// - The `bio`/`avatarUrl` fields the pre-migration User type carried are
// dropped entirely: AuthGuard has no such concept, and grepping the
// frontend (webui) confirms neither field was ever actually read
// or set by any UI - they were dead weight even before this migration.
//
// Auth-disabled mode (AUTHGUARD_URL unset)
// -----------------------------------------
// AUTHGUARD_URL is optional. When it is unset, Service.authGuard is nil
// (Service.enabled() reports false) and this service runs with
// authentication turned off entirely: CurrentUser always resolves to
// localProfile (a fixed placeholder superadmin identity), so every request
// is treated as already authenticated regardless of the `auth_required`
// setting - there is no login screen and nothing gated. This is an explicit
// mode for local development or a standalone deployment that doesn't want
// centralized identity, matching every other AuthGuard-migrated project's
// exact convention; it is not an error condition, and there is no
// degraded/partial "local auth" fallback state.
//
// Features that need a *real* backing identity rather than just an access
// gate - TOTP (initiate/verify/disable), self-service profile editing, and
// admin user-management's mutating calls - have nothing meaningful to do
// without AuthGuard (there is no account to attach a TOTP secret to, no
// profile to edit, no user store to create/update/delete against) and
// return a clear errFeatureRequiresAuthGuard error instead of silently
// no-opping or faking data. GET /api/auth/users is the one exception:
// consistent with "nothing gated", it returns an empty list rather than an
// error, since listing (unlike mutating) has an honest, unsurprising answer
// when there is no user store: there are no managed users to show.
//
// No local admin-reset flow
// --------------------------
// This service used to expose POST /auth/reset/request + /auth/reset/confirm,
// an out-of-band console-code flow that wiped every local account. That has
// no meaning once there is no local account to wipe - accounts are
// centralized in AuthGuard now, and only AuthGuard's own web UI exposes an
// admin-reset affordance. Those two routes are removed entirely, not
// adapted (see server.go).
package auth
import (
"context"
"encoding/json"
"errors"
"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"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
)
// User is this service's own /auth/... response shape - UNCHANGED from
// before this migration except Bio/Avatar (see the package doc comment's
// "Known gaps" section), sourced from AuthGuard's authclient.PublicUser via
// toUser rather than a local table.
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"`
MFAEnabled bool `json:"mfaEnabled"`
}
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.")
// errFeatureRequiresAuthGuard is returned by the handlers that need a
// real backing identity (not just an access gate) when AUTHGUARD_URL is
// unset; see the top-of-file doc comment's "Auth-disabled mode" section.
errFeatureRequiresAuthGuard = errors.New("This feature requires AUTHGUARD_URL to be configured.")
// errAuthGuardUnavailable is returned whenever CurrentUser/currentProfile
// propagate a non-nil error: by construction that only happens when
// AuthGuard could not be reached or gave an unusable response - a real
// "invalid or expired session" is always resolved to (nil, nil) instead,
// never an error - so every caller can safely report this same, specific
// message rather than a generic "internal error" that would be
// indistinguishable from any other server bug.
errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.")
errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.")
)
const (
loginRequiredSettingKey = "auth_required"
setupClaimedSettingKey = "setup_claimed"
minPasswordLength = 8
maxUsernameLength = 64
maxEmailLength = 254
)
// localProfile is the fixed placeholder identity CurrentUser/Signup/Login
// report when auth is disabled (AUTHGUARD_URL unset). Role is superadmin so
// CanManageUsers reports true, consistent with "nothing gated": the
// frontend's own admin-only UI sections become visible too, even though the
// underlying admin endpoints have nothing to manage.
var localProfile = User{ID: 0, Username: "local", Email: "", Role: string(sharedauth.RoleSuperAdmin), CanManageUsers: true}
type Service struct {
db *pgxpool.Pool
cookieName string
secureCookies bool
// authGuard is nil when AUTHGUARD_URL is unset; see the top-of-file doc
// comment's "Auth-disabled mode" section.
authGuard *authclient.Client
}
// New constructs a Service. cookieName/secureCookies are retained only for
// clearing the pre-migration session cookie on logout (see the package doc
// comment's "Session cookie / token model" section) - the live session
// cookie this service actually reads/sets is always AuthGuard's own
// authclient.DefaultCookieName. authGuardURL is AUTHGUARD_URL; empty means
// auth-disabled mode.
func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL string) *Service {
var client *authclient.Client
if strings.TrimSpace(authGuardURL) != "" {
client = authclient.New(authGuardURL)
}
return &Service{db: db, cookieName: cookieName, secureCookies: secureCookies, authGuard: client}
}
// enabled reports whether AUTHGUARD_URL was configured. See the top-of-file
// doc comment's "Auth-disabled mode" section.
func (s *Service) enabled() bool {
return s.authGuard != nil
}
func UserFromContext(ctx context.Context) *User {
value, _ := ctx.Value(userContextKey).(*User)
return value
}
// sessionToken reads the AuthGuard session cookie off the incoming request.
// See the top-of-file doc comment's "Session cookie / token model" section.
func (s *Service) sessionToken(r *http.Request) string {
return authproxy.SessionToken(r)
}
// clearSessionCookies clears both the AuthGuard cookie (as a fallback -
// normally AuthGuard's own Set-Cookie, forwarded via authclient.ForwardCookies,
// already does this) and the pre-migration cookie name.
func (s *Service) clearSessionCookies(w http.ResponseWriter) {
authproxy.ClearSessionCookies(w, s.cookieName, s.secureCookies)
}
// toUser translates AuthGuard's PublicUser into this service's own User
// response shape.
func toUser(profile authclient.PublicUser) *User {
return &User{
ID: profile.ID, Email: profile.Email, Username: profile.Username,
Role: profile.Role, CanManageUsers: sharedauth.CanManageUsers(profile.Role),
MFAEnabled: profile.TOTPEnabled,
}
}
// currentProfile resolves the request's AuthGuard session cookie via
// GET /api/me (which - unlike the cheaper GET /api/session/validate -
// carries TOTPEnabled directly, so this service needs no local TOTP-enabled
// cache the way GameStream's migration did), or nil if the request has no
// session cookie or AuthGuard reports it as invalid/expired.
func (s *Service) currentProfile(ctx context.Context, token string) (*authclient.PublicUser, error) {
if token == "" {
return nil, nil
}
profile, err := s.authGuard.Me(ctx, token)
if err != nil {
var apiErr *authclient.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized {
return nil, nil
}
return nil, err
}
return profile, nil
}
// CurrentUser is the single choke point every gating middleware below
// (Optional/Require/RequireAdmin/RequireUserManager/RequireIfLoginRequired/
// RequireAdminIfLoginRequired) resolves a session through - none of them
// needed to change for this migration, only what CurrentUser itself does.
func (s *Service) CurrentUser(r *http.Request) (*User, error) {
if !s.enabled() {
user := localProfile
return &user, nil
}
profile, err := s.currentProfile(r.Context(), s.sessionToken(r))
if err != nil {
return nil, err
}
if profile == nil {
return nil, nil
}
return toUser(*profile), 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, errAuthGuardUnavailable.Error())
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. This toggle is independent of AuthGuard - see
// the package doc comment's second paragraph.
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 (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 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, errAuthGuardUnavailable.Error())
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})
}
// UpdateMe lets the caller edit their own username/email/password. See the
// package doc comment's "Known gaps" section: AuthGuard only exposes
// account editing through its admin/users endpoint, which requires
// CanManageUsers, so a plain "user"-role account has no AuthGuard-backed way
// to self-edit today.
func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
return
}
current := UserFromContext(r.Context())
if current == nil {
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
if !sharedauth.CanManageUsers(current.Role) {
writeError(w, http.StatusForbidden, errSelfServiceProfile.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, err := normalizeEmail(input.Email)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
username, err := normalizeUsername(input.Username)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
managedInput := authclient.ManagedUserInput{Username: username, Email: email}
if input.Password != "" {
if err := validatePassword(input.Password); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
managedInput.Password = input.Password
}
token := s.sessionToken(r)
if err := s.authGuard.UpdateManagedUser(r.Context(), token, current.ID, managedInput); err != nil {
writeAuthGuardError(w, err, "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})
}
// AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc
// comment's "Setup flow" section.
func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false})
return
}
claimed, err := s.isSetupClaimed(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if claimed {
writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false})
return
}
setupRequired, err := s.authGuard.SetupStatus(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return
}
writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": setupRequired})
}
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) {
if !s.enabled() {
user := localProfile
writeJSON(w, http.StatusOK, map[string]any{"setupRequired": false, "authenticated": true, "authRequired": true, "user": &user})
return
}
claimed, err := s.isSetupClaimed(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
setupRequired := false
if !claimed {
setupRequired, err = s.authGuard.SetupStatus(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return
}
}
user, err := s.CurrentUser(r)
if err != nil {
writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
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{
"setupRequired": setupRequired, "authenticated": user != nil, "authRequired": loginRequired, "user": user,
})
}
// managedUserPayload translates an AuthGuard ManagedUser into this service's
// existing response shape.
func managedUserPayload(user authclient.ManagedUser) 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,
}
}
// ManagedUsers proxies admin user listing to AuthGuard's GET /api/admin/users.
// Authorization (CanManageUsers) is enforced by AuthGuard itself from the
// forwarded session token; this service does not re-implement that check
// locally, so its 401/403 responses come straight from AuthGuard via
// writeAuthGuardError.
func (s *Service) ManagedUsers(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
// Nothing is gated in auth-disabled mode, and an empty list is an
// honest answer: there is no user store to list from. See the
// top-of-file doc comment's "Auth-disabled mode" section.
writeJSON(w, http.StatusOK, []map[string]any{})
return
}
users, err := s.authGuard.ListManagedUsers(r.Context(), s.sessionToken(r))
if err != nil {
writeAuthGuardError(w, err, "users unavailable")
return
}
result := make([]map[string]any, 0, len(users))
for _, user := range users {
result = append(result, managedUserPayload(user))
}
writeJSON(w, http.StatusOK, result)
}
// ManagedCreateUser proxies admin user creation to AuthGuard's
// POST /api/admin/users. See ManagedUsers's doc comment: AuthGuard enforces
// authorization (including which roles the caller may assign) itself.
func (s *Service) ManagedCreateUser(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
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
}
managedInput := authclient.ManagedUserInput{Username: input.Username, Email: input.Email, Password: input.Password}
if role := strings.TrimSpace(input.Role); role != "" {
managedInput.Role = &role
}
created, err := s.authGuard.CreateManagedUser(r.Context(), s.sessionToken(r), managedInput)
if err != nil {
writeAuthGuardError(w, err, "user could not be created")
return
}
writeJSON(w, http.StatusCreated, managedUserPayload(*created))
}
// ManagedUpdateUser proxies admin user update to AuthGuard's
// PUT /api/admin/users/{id}. See ManagedUsers's doc comment: AuthGuard
// enforces authorization (including the "the superadmin account is
// protected" rule) itself.
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
}
if !s.enabled() {
writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
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
}
managedInput := authclient.ManagedUserInput{Username: input.Username, Email: input.Email, Password: input.Password, Role: input.Role}
if err := s.authGuard.UpdateManagedUser(r.Context(), s.sessionToken(r), id, managedInput); err != nil {
writeAuthGuardError(w, err, "user could not be updated")
return
}
users, err := s.authGuard.ListManagedUsers(r.Context(), s.sessionToken(r))
if err != nil {
writeAuthGuardError(w, err, "user could not be loaded")
return
}
for _, user := range users {
if user.ID == id {
writeJSON(w, http.StatusOK, managedUserPayload(user))
return
}
}
writeError(w, http.StatusNotFound, "user not found")
}
// ManagedDeleteUser proxies admin user deletion to AuthGuard's
// DELETE /api/admin/users/{id}. See ManagedUsers's doc comment: AuthGuard
// enforces authorization (including "this user cannot be deleted" rules)
// itself.
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
}
if !s.enabled() {
writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
return
}
if err := s.authGuard.DeleteManagedUser(r.Context(), s.sessionToken(r), id); err != nil {
writeAuthGuardError(w, err, "user could not be deleted")
return
}
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
// Signup registers this deployment's first account against AuthGuard's
// POST /api/register. See the package doc comment's "Setup flow" section for
// why this needs a small local claim flag instead of a count-based check.
func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
user := localProfile
writeJSON(w, http.StatusCreated, map[string]any{"user": &user})
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, err := normalizeEmail(input.Email)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
username := strings.TrimSpace(input.Username)
if username == "" {
writeError(w, http.StatusBadRequest, "a username is required")
return
}
if _, err := normalizeUsername(username); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := validatePassword(input.Password); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
claimed, err := s.tryClaimSetup(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
if !claimed {
writeError(w, http.StatusConflict, "Setup has already been completed.")
return
}
// Belt-and-braces: AdminNeeded already keeps the frontend from ever
// showing this form once AuthGuard has any account (see its own
// SetupStatus check), but a stale page or a direct API call could still
// reach this handler. Reject it the same way as the local claim conflict
// above rather than creating a redundant plain user account.
if setupRequired, err := s.authGuard.SetupStatus(r.Context()); err != nil || !setupRequired {
if unclaimErr := s.unclaimSetup(r.Context()); unclaimErr != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return
}
writeError(w, http.StatusConflict, "Setup has already been completed.")
return
}
result, err := s.authGuard.Register(r.Context(), username, email, input.Password)
if err != nil {
// The claim slot is only valid once actually backed by a real
// AuthGuard account; reopen it so a corrected retry can proceed.
if unclaimErr := s.unclaimSetup(r.Context()); unclaimErr != nil {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
writeAuthGuardError(w, err, "could not create account")
return
}
authclient.ForwardCookies(w, result.Cookies)
writeJSON(w, http.StatusCreated, map[string]any{"user": toUser(result.User)})
}
func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
user := localProfile
writeJSON(w, http.StatusOK, map[string]any{"user": &user})
return
}
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)
}
if identifier == "" {
writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
return
}
result, err := s.authGuard.Login(r.Context(), identifier, input.Password, input.TOTPToken)
if err != nil {
var apiErr *authclient.APIError
if errors.As(err, &apiErr) {
if apiErr.TOTPRequired {
writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "Two-factor authentication code required.", "mfaRequired": true})
return
}
if apiErr.StatusCode == http.StatusUnauthorized {
writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
return
}
writeAuthGuardError(w, err, "could not authenticate")
return
}
// A non-APIError here means the call to AuthGuard itself failed
// (transport/connectivity); see errAuthGuardUnavailable.
writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return
}
authclient.ForwardCookies(w, result.Cookies)
writeJSON(w, http.StatusOK, map[string]any{"user": toUser(result.User)})
}
func (s *Service) Logout(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
return
}
if token := s.sessionToken(r); token != "" {
cookies, err := s.authGuard.Logout(r.Context(), token)
if err != nil {
var apiErr *authclient.APIError
if !errors.As(err, &apiErr) {
writeError(w, http.StatusInternalServerError, "internal error")
return
}
// An already-invalid/expired session is fine to treat as
// "already logged out" rather than an error.
} else {
authclient.ForwardCookies(w, cookies)
}
}
s.clearSessionCookies(w)
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
writeJSON(w, http.StatusOK, map[string]any{"enabled": false, "mfaEnabled": false})
return
}
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})
}
// TOTPInitiate provisions a pending TOTP secret via AuthGuard's POST
// /api/totp/enable (AuthGuard's "enable" is this service's "initiate" step -
// naming differs, the two-step provision-then-confirm flow is identical).
func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
return
}
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
}
result, err := s.authGuard.TOTPEnable(r.Context(), s.sessionToken(r))
if err != nil {
writeAuthGuardError(w, err, "could not create authenticator secret")
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"secret": result.Secret, "otpauth": result.OTPAuthURL, "otpauthUrl": result.OTPAuthURL, "enabled": result.Enabled,
}})
}
// TOTPVerify confirms a generated code via AuthGuard's POST /api/totp/verify,
// activating two-factor authentication (AuthGuard's "verify" is this
// service's "verify" step too; see TOTPInitiate).
func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
return
}
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
}
token := strings.TrimSpace(input.TOTPToken)
if token == "" {
token = strings.TrimSpace(input.Token)
}
if err := s.authGuard.TOTPVerify(r.Context(), s.sessionToken(r), token); err != nil {
writeError(w, http.StatusUnauthorized, "Invalid authenticator code.")
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) {
if !s.enabled() {
writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
return
}
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
}
token := strings.TrimSpace(input.TOTPToken)
if token == "" {
token = strings.TrimSpace(input.Token)
}
if err := s.authGuard.TOTPDisable(r.Context(), s.sessionToken(r), token); err != nil {
writeError(w, http.StatusUnauthorized, "Invalid authenticator code.")
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": false, "enabled": false}})
}
// isSetupClaimed/tryClaimSetup/unclaimSetup back the local one-time setup
// flag described in the package doc comment's "Setup flow" section, reusing
// the pre-existing `settings` key/value table (same mechanism as
// LoginRequired's `auth_required` key) rather than a new table.
func (s *Service) isSetupClaimed(ctx context.Context) (bool, error) {
var value string
err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key = $1`, setupClaimedSettingKey).Scan(&value)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, err
}
return value == "true", nil
}
func (s *Service) tryClaimSetup(ctx context.Context) (bool, error) {
tag, err := s.db.Exec(ctx, `
INSERT INTO settings (key, value, updated_at) VALUES ($1, 'true', NOW())
ON CONFLICT (key) DO NOTHING
`, setupClaimedSettingKey)
if err != nil {
return false, err
}
return tag.RowsAffected() > 0, nil
}
func (s *Service) unclaimSetup(ctx context.Context) error {
_, err := s.db.Exec(ctx, `DELETE FROM settings WHERE key = $1`, setupClaimedSettingKey)
return err
}
// --- Moderatable platform users (unrelated to admin login identity) --------
//
// The methods below (CreateUser/ListUsers/UpdateUser/SetPassword/DeleteUser)
// back internal/server/admin_storage.go's mountModeratorRoutes
// (adminUsers/adminCreateUser/adminUpdateUser/adminDeleteUser/adminUserActions
// - the ModerationHub service's "manage platform participants" admin panel).
// This is a DIFFERENT concept from "who can log into this service's own
// admin panel" (the Signup/Login/ManagedUsers family above, now proxied to
// AuthGuard): these are content-uploading end users of the media platform
// being moderated, not administrators. They happen to share the local
// `users`/`go_sessions` table's schema from before this migration, but that
// table's role here is now purely "the local platform-user directory" - it
// is no longer consulted for anything related to *this service's own*
// authentication, which is entirely AuthGuard's job now. Left untouched by
// this migration.
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": normalizeRole(user.Role),
"createdAt": user.CreatedAt,
}
}
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
}
// writeAuthGuardError translates an authclient error into this service's
// {"error": "..."} response shape. AuthGuard's own httpapi handlers were
// built from this workspace's various local implementations, so their
// status codes and messages already match closely - AuthGuard's *APIError
// is forwarded close to verbatim rather than re-mapped by hand. A
// non-APIError (a transport failure actually reaching AuthGuard) falls back
// to a generic 500 with fallbackMessage.
func writeAuthGuardError(w http.ResponseWriter, err error, fallbackMessage string) {
if statusCode, message, ok := authproxy.APIErrorResponse(err); ok {
writeError(w, statusCode, message)
return
}
writeError(w, http.StatusInternalServerError, fallbackMessage)
}
func normalizeUsername(value string) (string, error) {
value = strings.TrimSpace(value)
if value == "" {
return "", nil
}
if len([]rune(value)) > maxUsernameLength {
return "", errors.New("username is too long")
}
return value, nil
}
func normalizeEmail(value string) (string, error) {
value = strings.ToLower(strings.TrimSpace(value))
if !strings.Contains(value, "@") || len(value) > maxEmailLength {
return "", errors.New("a valid email is required")
}
return value, nil
}
func validatePassword(password string) error {
if len([]rune(password)) < minPasswordLength || len([]rune(password)) > 1024 {
return errors.New("Password must be at least 8 characters.")
}
return nil
}
// normalizeCredentials validates email/password format (username is
// optional here - Signup separately requires it be non-empty; kept this way
// to preserve this package's existing test coverage/contract).
func normalizeCredentials(email, username, password string) (string, string, string, error) {
email, err := normalizeEmail(email)
if err != nil {
return "", "", "", err
}
username, err = normalizeUsername(username)
if err != nil {
return "", "", "", err
}
if err := validatePassword(password); err != nil {
return "", "", "", err
}
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 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) }