2026-09-13 18:43:16 +02:00
// This file holds the shared media-backend family's /auth/... and /api/auth/...
2026-09-07 16:00:08 +02:00
// handlers, proxied to AuthGuard. Promoted from each service's own
// internal/auth into this shared library so all 7 independent media-family
2026-09-12 15:48:17 +02:00
// backends (CarrierNode, ModerationHub, ProjectConfigurator, KioskDisplay,
2026-09-07 16:00:08 +02:00
// MediaViewer, ContentScanner, CraftStudio) use one copy instead of
2026-09-13 18:43:16 +02:00
// duplicating it. Originally its own "mediaauth" package; merged into this
// package (2026-09-13) since it is no longer media-specific - see "Unified
// auth proxy" below - and "auth" is the more accurate name for what it now
// is. ProxyUser/ProxyStore/Service/New/NewWithStore below are this file's
// exports; everything else in this package (Store, User, Role, TOTP,
// password, token, reset) is the lower-level local-account persistence
// layer these proxy against AuthGuard instead of using directly.
2026-09-02 21:45:19 +02:00
//
2026-09-13 12:18:24 +02:00
// Unified auth proxy
// ==================
2026-09-13 18:43:16 +02:00
// This file used to be its own package, specific to the 7 media-family
// backends (each built via New, wired directly to their own shared Postgres
// `settings` table). It is now the ONE shared auth-proxy engine for every
// project in this workspace that centralizes identity through AuthGuard -
// GameStream, Bitmagnet, and OmniLogger, which each used to independently
// reimplement this same session/login/TOTP/admin-user proxy against their
// own storage, now build a Service via NewWithStore against a small
// ProxyStore adapter over whatever local table they already used for their
// "login required" toggle and one-time setup-claim flag (see the ProxyStore
// interface below), instead of duplicating this file's logic. New (the
// original media-family constructor) is unchanged and is really just
// NewWithStore plus pgSettingsStore, the default ProxyStore implementation
// backed by the shared `settings` table.
2026-09-13 12:18:24 +02:00
//
// ProjectKey (New/NewWithStore's last parameter) identifies the calling
// project to AuthGuard on every request (authclient.WithProjectKey), so an
// administrator can restrict which projects a given AuthGuard account may
// authenticate against; see AuthGuard's project-scope admin UI. Leave it ""
// to opt out (every account is then unrestricted for this project, the
// pre-existing behavior).
//
2026-09-02 21:45:19 +02:00
// 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).
//
2026-09-07 16:00:08 +02:00
// It now proxies every auth operation to AuthGuard (Web/Core/AuthGuard),
2026-09-02 21:45:19 +02:00
// a centralized identity service other projects in this workspace share,
2026-09-13 18:43:16 +02:00
// via the `authclient` package (Web/Core/shared/backend/authclient). This
2026-09-02 21:45:19 +02:00
// service's own /auth/... and /api/auth/... URL paths and JSON response
2026-09-04 15:07:02 +02:00
// shapes are UNCHANGED - the frontend (webui) was not touched - only
2026-09-02 21:45:19 +02:00
// what backs them changed. This mirrors the migration
// Original/GameStream/backend/cmd/gamestreamd/auth.go and
2026-09-07 16:00:08 +02:00
// Fork/Bitmagnet/backend/internal/auth/service.go already did; read either
2026-09-02 21:45:19 +02:00
// 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,
2026-09-04 15:07:02 +02:00
// default "session") is retained only as something Logout
2026-09-02 21:45:19 +02:00
// 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.
2026-09-13 18:43:16 +02:00
// - The `bio`/`avatarUrl` fields the pre-migration ProxyUser type carried
// are dropped entirely: AuthGuard has no such concept, and grepping the
2026-09-04 15:07:02 +02:00
// frontend (webui) confirms neither field was ever actually read
2026-09-02 21:45:19 +02:00
// or set by any UI - they were dead weight even before this migration.
//
2026-09-14 09:35:45 +02:00
// Auth-disabled mode (the Disabled() option)
// -------------------------------------------
// Passing Disabled() to New/NewWithStore turns authentication off entirely
// for a Service: Service.authGuard is nil (Service.enabled() reports false),
2026-09-16 23:58:00 +02:00
// CurrentUser always resolves to adminProfile (a fixed placeholder
2026-09-14 09:35:45 +02:00
// 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 at all; it is
// not an error condition, and there is no degraded/partial "local auth"
// fallback state.
//
// Without Disabled(), a Service is always "enabled" - including when
// authGuardURL is empty at construction. That used to also mean disabled,
// but made AUTHGUARD_URL a de-facto requirement: a Service built with no URL
// could never start authenticating later, since a live retarget
// (SetAuthGuardBaseURL, wired as ProjectConfigurator's coreconfig push) had
// no client to retarget. Now an empty authGuardURL just means "pending": the
// Service still gates every request, but its calls to AuthGuard fail (with
// errAuthGuardUnavailable, a 401) until a URL arrives - normally within
// ProjectConfigurator's periodic re-push window (coreconfig's doc comment),
// converging on its own with no restart needed, the same way a live
// AuthGuard URL *change* already did before this pending mode existed. A
// project that wants no AuthGuard integration at all (the old meaning of an
// unset AUTHGUARD_URL) must now say so explicitly via Disabled().
2026-09-02 21:45:19 +02:00
//
// 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
2026-09-14 09:35:45 +02:00
// in Disabled() mode (there is no account to attach a TOTP secret to, no
2026-09-02 21:45:19 +02:00
// 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
2026-09-14 09:35:45 +02:00
// when there is no user store: there are no managed users to show. In
// pending mode (enabled, but no URL yet) these same calls are attempted for
// real and fail closed with errAuthGuardUnavailable instead, since AuthGuard
// integration genuinely is turned on here - it just isn't reachable yet.
2026-09-02 21:45:19 +02:00
//
// 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).
2026-09-13 18:43:16 +02:00
package auth
2026-09-01 08:43:25 +02:00
import (
"context"
2026-10-19 21:46:52 +00:00
"crypto/subtle"
2026-09-01 08:43:25 +02:00
"encoding/json"
"errors"
"io"
2026-10-19 21:46:52 +00:00
"mime"
"net"
2026-09-01 08:43:25 +02:00
"net/http"
2026-09-15 23:27:42 +02:00
"os"
2026-09-01 08:43:25 +02:00
"strconv"
"strings"
2026-09-17 00:14:56 +02:00
"sync"
2026-09-01 08:43:25 +02:00
"time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
2026-09-02 21:45:19 +02:00
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
2026-09-03 00:16:55 +02:00
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
2026-09-01 08:43:25 +02:00
)
2026-09-13 18:43:16 +02:00
// ProxyUser is this service's own /auth/... response shape - UNCHANGED from
2026-09-02 21:45:19 +02:00
// before this migration except Bio/Avatar (see the package doc comment's
// "Known gaps" section), sourced from AuthGuard's authclient.PublicUser via
2026-09-13 18:43:16 +02:00
// toUser rather than a local table. Distinct from User (this package's own
// local-account DB row): ProxyUser is the identity resolved through
// AuthGuard for a proxying project, User is a row this package itself owns
// in a project's local database (AuthGuard's own database, in AuthGuard's
// case).
type ProxyUser struct {
2026-09-01 08:43:25 +02:00
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"`
}
2026-09-13 18:43:16 +02:00
type proxyContextKey struct {}
2026-09-01 08:43:25 +02:00
2026-09-13 18:43:16 +02:00
var proxyUserContextKey proxyContextKey
2026-09-01 08:43:25 +02:00
var (
ErrUnauthorized = errors . New ( "authentication required" )
ErrForbidden = errors . New ( "administrator access required" )
ErrInvalidLogin = errors . New ( "Invalid username or password." )
2026-09-02 21:45:19 +02:00
// errFeatureRequiresAuthGuard is returned by the handlers that need a
2026-09-14 09:35:45 +02:00
// real backing identity (not just an access gate) when this Service was
// constructed with Disabled(); see the top-of-file doc comment's
// "Auth-disabled mode" section.
errFeatureRequiresAuthGuard = errors . New ( "This feature requires AuthGuard to be enabled." )
2026-09-02 21:45:19 +02:00
// 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." )
2026-09-15 23:27:42 +02:00
errSecretNotSet = errors . New ( "SECRET environment variable is not set." )
2026-10-19 21:46:52 +00:00
errTooManyAttempts = errors . New ( "Too many attempts. Try again later." )
errSetupRequiresLogin = errors . New ( "Account setup is only available while login is required." )
errNoLoginRequiredStore = errors . New ( "the login-required setting has no store to save to" )
errCrossSiteRequest = errors . New ( "cross-site request refused" )
errJSONContentType = errors . New ( "request body must be application/json" )
2026-09-02 21:45:19 +02:00
errSelfServiceProfile = errors . New ( "Self-service profile editing is only available to administrator accounts; ask an administrator to update this account." )
2026-09-01 08:43:25 +02:00
)
2026-09-02 21:45:19 +02:00
const (
loginRequiredSettingKey = "auth_required"
setupClaimedSettingKey = "setup_claimed"
2026-09-13 18:43:16 +02:00
proxyMinPasswordLength = 8
2026-10-19 21:46:52 +00:00
// maxBcryptPasswordBytes is the longest password bcrypt hashes in full.
maxBcryptPasswordBytes = 72
2026-09-13 18:43:16 +02:00
proxyMaxUsernameLength = 64
proxyMaxEmailLength = 254
2026-09-02 21:45:19 +02:00
)
2026-09-16 23:58:00 +02:00
// adminProfile is the fixed placeholder identity used when authentication is
// disabled, either explicitly through Disabled() or through a project's
// ProjectConfigurator "Require Login" toggle. Role is superadmin so all
// application routes see the same administrator identity even though no
// credentials were supplied.
var adminProfile = ProxyUser { ID : 0 , Username : "Admin" , Email : "" , Role : string ( RoleSuperAdmin ), CanManageUsers : true }
2026-09-01 08:43:25 +02:00
2026-09-13 18:43:16 +02:00
// ProxyStore is the small piece of local, project-owned persistence a
// Service needs beyond AuthGuard itself: the independent "require login"
// toggle (RequireIfLoginRequired/RequireAdminIfLoginRequired predate the
// AuthGuard migration - see the package doc comment's second paragraph) and
// the one-time "has this deployment's setup screen been completed" claim
// flag (see the "Setup flow" section below). pgSettingsStore is the
2026-09-13 12:18:24 +02:00
// implementation New builds automatically over the media family's shared
// `settings` table; NewWithStore accepts any other implementation, letting a
// project with its own storage (GameStream's/Bitmagnet's/OmniLogger's own
// tables) reuse this package without adopting that generic table.
2026-09-13 18:43:16 +02:00
type ProxyStore interface {
2026-09-13 12:18:24 +02:00
LoginRequired ( ctx context . Context ) ( bool , error )
SetLoginRequired ( ctx context . Context , required bool ) error
IsSetupClaimed ( ctx context . Context ) ( bool , error )
TryClaimSetup ( ctx context . Context ) ( bool , error )
UnclaimSetup ( ctx context . Context ) error
}
2026-09-01 08:43:25 +02:00
type Service struct {
2026-09-13 12:18:24 +02:00
// db backs only the "moderatable platform users" section at the bottom
// of this file (CreateUser/ListUsers/UpdateUser/SetPassword/DeleteUser),
// a media-family-specific concept unrelated to AuthGuard identity - see
// that section's own doc comment. nil for a Service built via
// NewWithStore; those methods are simply never called by a project with
// no such local platform-user table.
2026-09-01 08:43:25 +02:00
db * pgxpool . Pool
2026-09-13 18:43:16 +02:00
store ProxyStore
2026-09-01 08:43:25 +02:00
cookieName string
secureCookies bool
2026-09-14 09:35:45 +02:00
// authGuard is nil only when this Service was built with Disabled(); see
// the top-of-file doc comment's "Auth-disabled mode" section. A "pending"
// Service (auth turned on, but no URL known yet) still has a non-nil
// client, just one whose calls fail until SetAuthGuardBaseURL supplies a
// real base URL.
2026-09-15 23:27:42 +02:00
authGuard * authclient . Client
configurationError error
2026-10-19 21:46:52 +00:00
loginCacheMu sync . Mutex
loginCacheValue bool
loginCacheSet bool
loginCacheExpires time . Time
// Attempt counters for the credential endpoints; see ratelimit.go.
loginAccountAttempts * attemptLimiter
loginClientAttempts * attemptLimiter
totpAttempts * attemptLimiter
// trustedProxies are the peers whose X-Forwarded-For header is honoured;
// see clientAddress in clientip.go.
trustedProxies [] * net . IPNet
2026-09-01 08:43:25 +02:00
}
2026-09-14 09:35:45 +02:00
// ServiceOption configures optional New/NewWithStore construction behavior.
// Variadic and trailing, so every existing call site keeps compiling
// unchanged; only a project that wants Disabled() needs to pass one.
type ServiceOption func ( * serviceOptions )
type serviceOptions struct {
2026-10-19 21:46:52 +00:00
disabled bool
requireSecret bool
trustedProxies [] * net . IPNet
2026-09-14 09:35:45 +02:00
}
// Disabled explicitly builds a Service in auth-disabled mode (see the
// package doc comment's "Auth-disabled mode" section): nothing gated, a
// fixed superadmin placeholder identity for every request, regardless of
// authGuardURL. This is the explicit opt-out for a genuine standalone/
// local-dev deployment that doesn't want centralized identity at all -
// without it, an empty authGuardURL now means "pending" (auth integration
// is on, but no URL is known yet), not disabled.
func Disabled () ServiceOption {
return func ( o * serviceOptions ) { o . disabled = true }
}
2026-09-15 23:27:42 +02:00
// RequireSecret keeps the service available when SECRET is omitted, but makes
// the public auth status/me endpoints report the configuration error so the
// frontend can show it in the auth screen. Internal-service routes remain
// fail-closed until a secret is configured.
func RequireSecret () ServiceOption {
return func ( o * serviceOptions ) { o . requireSecret = true }
}
2026-10-19 21:46:52 +00:00
// WithTrustedProxies sets the reverse proxies whose X-Forwarded-For header is
// honoured when a login's client address is taken. Build the list from the
// TRUSTED_PROXIES setting with ParseTrustedProxies. Without it, the TCP peer
// is always the client address.
func WithTrustedProxies ( networks [] * net . IPNet ) ServiceOption {
return func ( o * serviceOptions ) { o . trustedProxies = networks }
}
2026-09-13 12:18:24 +02:00
// New constructs a Service backed by the media family's shared `settings`
// table (pgSettingsStore) for the login-required toggle and setup-claim
// flag, and by db directly for the unrelated "moderatable platform users"
// section. 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
2026-09-14 09:35:45 +02:00
// authclient.DefaultCookieName. authGuardURL is this project's currently
// known AuthGuard base URL - typically empty at construction now that
// ProjectConfigurator pushes it live (coreconfig.Store.OnUpdate ->
// SetAuthGuardBaseURL); see the "Auth-disabled mode" section for what an
// empty authGuardURL means without Disabled(). projectKey identifies this
// project to AuthGuard for per-user project-access restriction; see the
// "Unified auth proxy" section above.
func New ( db * pgxpool . Pool , cookieName string , secureCookies bool , authGuardURL , projectKey string , opts ... ServiceOption ) * Service {
service := NewWithStore ( pgSettingsStore { db : db }, cookieName , secureCookies , authGuardURL , projectKey , opts ... )
2026-09-13 12:18:24 +02:00
service . db = db
return service
}
2026-09-13 18:43:16 +02:00
// NewWithStore constructs a Service against any ProxyStore implementation,
// for a project whose login-required toggle and setup-claim flag live in
// its own storage rather than the media family's shared `settings` table.
// Its resulting Service has no db (the "moderatable platform users" section
// is unavailable - a project adopting this package fresh has no such
// feature to preserve).
2026-09-14 09:35:45 +02:00
func NewWithStore ( store ProxyStore , cookieName string , secureCookies bool , authGuardURL , projectKey string , opts ... ServiceOption ) * Service {
var options serviceOptions
for _ , opt := range opts {
opt ( & options )
}
2026-09-02 21:45:19 +02:00
var client * authclient . Client
2026-09-14 09:35:45 +02:00
if ! options . disabled {
// authclient.New/SetBaseURL/Validate/call all tolerate an empty base
// URL (every call fails cleanly with "client has no base URL" rather
// than panicking or building a malformed request), which is exactly
// what makes "pending" mode safe: a Service constructed with no URL
// yet still has a real, non-nil client ready to be retargeted the
// moment one arrives.
client = authclient . New ( strings . TrimSpace ( authGuardURL ), authclient . WithProjectKey ( projectKey ))
2026-09-01 08:43:25 +02:00
}
2026-09-15 23:27:42 +02:00
var configurationError error
if options . requireSecret && ! options . disabled && strings . TrimSpace ( os . Getenv ( "SECRET" )) == "" {
configurationError = errSecretNotSet
}
2026-10-19 21:46:52 +00:00
return & Service {
store : store ,
cookieName : cookieName ,
secureCookies : secureCookies ,
authGuard : client ,
configurationError : configurationError ,
loginAccountAttempts : newAttemptLimiter ( attemptWindow , loginAccountLimit ),
loginClientAttempts : newAttemptLimiter ( attemptWindow , loginClientLimit ),
totpAttempts : newAttemptLimiter ( attemptWindow , totpAttemptLimit ),
trustedProxies : options . trustedProxies ,
}
2026-09-13 12:18:24 +02:00
}
2026-09-13 18:43:16 +02:00
// pgSettingsStore is the default ProxyStore New builds over the media
// family's shared `settings` key/value table (see mediacore.SettingValue/
2026-09-13 12:18:24 +02:00
// SaveSetting) - unchanged behavior from before this package accepted a
2026-09-13 18:43:16 +02:00
// pluggable ProxyStore.
2026-09-13 12:18:24 +02:00
type pgSettingsStore struct {
db * pgxpool . Pool
}
func ( s pgSettingsStore ) 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 pgSettingsStore ) SetLoginRequired ( ctx context . Context , required bool ) error {
_ , err := s . db . Exec ( ctx , `
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 ( required ))
return err
}
func ( s pgSettingsStore ) 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 pgSettingsStore ) 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 pgSettingsStore ) UnclaimSetup ( ctx context . Context ) error {
_ , err := s . db . Exec ( ctx , `DELETE FROM settings WHERE key = $1` , setupClaimedSettingKey )
return err
2026-09-02 21:45:19 +02:00
}
2026-09-14 09:35:45 +02:00
// enabled reports whether this Service was NOT built with Disabled() - true
// for both a fully-configured Service and a "pending" one still waiting for
// its first AuthGuard URL. See the top-of-file doc comment's "Auth-disabled
// mode" section.
2026-09-02 21:45:19 +02:00
func ( s * Service ) enabled () bool {
return s . authGuard != nil
2026-09-01 08:43:25 +02:00
}
2026-09-13 12:30:19 +02:00
// SetAuthGuardBaseURL retargets the AuthGuard base URL this Service's
// internal authclient.Client calls, taking effect on its very next call -
// wire it as a coreconfig.Store's OnUpdate callback (see
// ProjectConfigurator/README.md's "Pushing core service info to other
2026-09-14 09:35:45 +02:00
// projects" section) so a live authguard_url push applies without a
// restart, whether it's the very first URL a "pending" Service ever
// receives or a later change to one already configured, the same as a
// project holding its own *authclient.Client directly. A no-op only if this
// Service was constructed with Disabled() (see the "Auth-disabled mode"
// section): there is no client to retarget, and this package has no path to
// start authenticating requests it was explicitly told to always let
// through.
2026-09-13 12:30:19 +02:00
func ( s * Service ) SetAuthGuardBaseURL ( baseURL string ) {
if s . authGuard != nil {
s . authGuard . SetBaseURL ( baseURL )
}
}
2026-09-13 18:43:16 +02:00
func UserFromContext ( ctx context . Context ) * ProxyUser {
value , _ := ctx . Value ( proxyUserContextKey ).( * ProxyUser )
2026-09-01 08:43:25 +02:00
return value
}
2026-09-02 21:45:19 +02:00
// 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 {
2026-09-03 00:16:55 +02:00
return authproxy . SessionToken ( r )
2026-09-02 21:45:19 +02:00
}
// 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 ) {
2026-09-03 00:16:55 +02:00
authproxy . ClearSessionCookies ( w , s . cookieName , s . secureCookies )
2026-09-02 21:45:19 +02:00
}
2026-09-13 18:43:16 +02:00
// toUser translates AuthGuard's PublicUser into this service's own
// ProxyUser response shape.
func toUser ( profile authclient . PublicUser ) * ProxyUser {
return & ProxyUser {
2026-09-02 21:45:19 +02:00
ID : profile . ID , Email : profile . Email , Username : profile . Username ,
2026-09-13 18:43:16 +02:00
Role : profile . Role , CanManageUsers : CanManageUsers ( profile . Role ),
2026-09-02 21:45:19 +02:00
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.
2026-09-13 18:43:16 +02:00
func ( s * Service ) CurrentUser ( r * http . Request ) ( * ProxyUser , error ) {
2026-09-15 23:27:42 +02:00
if s . configurationError != nil {
return nil , s . configurationError
}
2026-09-02 21:45:19 +02:00
if ! s . enabled () {
2026-09-16 23:58:00 +02:00
user := adminProfile
return & user , nil
}
loginRequired , err := s . LoginRequired ( r . Context ())
if err != nil {
return nil , err
}
if ! loginRequired {
user := adminProfile
2026-09-02 21:45:19 +02:00
return & user , nil
2026-09-01 08:43:25 +02:00
}
2026-09-02 21:45:19 +02:00
profile , err := s . currentProfile ( r . Context (), s . sessionToken ( r ))
2026-09-01 08:43:25 +02:00
if err != nil {
return nil , err
}
2026-09-02 21:45:19 +02:00
if profile == nil {
2026-09-01 08:43:25 +02:00
return nil , nil
}
2026-09-02 21:45:19 +02:00
return toUser ( * profile ), nil
2026-09-01 08:43:25 +02:00
}
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 {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-09-01 08:43:25 +02:00
return
}
if user != nil {
2026-09-13 18:43:16 +02:00
r = r . WithContext ( context . WithValue ( r . Context (), proxyUserContextKey , user ))
2026-09-01 08:43:25 +02:00
}
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 {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , ErrUnauthorized . Error ())
2026-09-01 08:43:25 +02:00
return
}
next . ServeHTTP ( w , r )
}))
}
// RequireIfLoginRequired protects actions when the application has login
2026-09-16 23:58:00 +02:00
// enabled. When login is disabled, CurrentUser supplies the synthetic Admin
// superadmin identity, so handlers can use the same authenticated code path
// without requiring credentials. This toggle is independent of AuthGuard -
// see the package doc comment's second paragraph.
2026-09-01 08:43:25 +02:00
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
}
2026-10-19 21:46:52 +00:00
// CurrentUser returns no user only when login is required (it returns the
// synthetic admin for every other case), so no second settings read is needed.
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , ErrUnauthorized . Error ())
2026-09-01 08:43:25 +02:00
}))
}
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 ) {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusForbidden , ErrForbidden . Error ())
2026-09-01 08:43:25 +02:00
return
}
next . ServeHTTP ( w , r )
}))
}
// RequireAdminIfLoginRequired keeps administrative actions protected for
2026-09-16 23:58:00 +02:00
// authenticated users. When login is disabled, CurrentUser supplies the
// synthetic Admin superadmin identity so configuration endpoints remain
// available without credentials.
2026-09-01 08:43:25 +02:00
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 {
2026-10-19 21:46:52 +00:00
// As in RequireIfLoginRequired, a nil user means login is required.
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , ErrUnauthorized . Error ())
2026-09-01 08:43:25 +02:00
return
}
if ! IsAdmin ( user ) {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusForbidden , ErrForbidden . Error ())
2026-09-01 08:43:25 +02:00
return
}
next . ServeHTTP ( w , r )
}))
}
2026-09-02 21:45:19 +02:00
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 ())
2026-09-13 18:43:16 +02:00
if ! CanManageUsers ( user . Role ) {
writeProxyError ( w , http . StatusForbidden , ErrForbidden . Error ())
2026-09-02 21:45:19 +02:00
return
}
next . ServeHTTP ( w , r )
}))
}
2026-09-13 18:43:16 +02:00
func IsAdmin ( user * ProxyUser ) bool {
2026-09-01 08:43:25 +02:00
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 ) {
2026-09-15 23:27:42 +02:00
if s . configurationError != nil {
writeProxyError ( w , http . StatusInternalServerError , s . configurationError . Error ())
return
}
2026-09-01 08:43:25 +02:00
user , err := s . CurrentUser ( r )
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-09-01 08:43:25 +02:00
return
}
loginRequired , err := s . LoginRequired ( r . Context ())
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , "authentication status unavailable" )
2026-09-01 08:43:25 +02:00
return
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] any { "user" : user , "authRequired" : loginRequired })
2026-09-01 08:43:25 +02:00
}
2026-09-02 21:45:19 +02:00
// 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.
2026-09-01 08:43:25 +02:00
func ( s * Service ) UpdateMe ( w http . ResponseWriter , r * http . Request ) {
2026-09-02 21:45:19 +02:00
if ! s . enabled () {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
2026-09-02 21:45:19 +02:00
return
}
current := UserFromContext ( r . Context ())
if current == nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , ErrUnauthorized . Error ())
2026-09-01 08:43:25 +02:00
return
}
2026-09-13 18:43:16 +02:00
if ! CanManageUsers ( current . Role ) {
writeProxyError ( w , http . StatusForbidden , errSelfServiceProfile . Error ())
2026-09-02 21:45:19 +02:00
return
}
2026-09-01 08:43:25 +02:00
var input struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
}
2026-09-13 18:43:16 +02:00
if err := decodeProxyJSON ( r , & input ); err != nil {
writeProxyError ( w , http . StatusBadRequest , "invalid JSON body" )
2026-09-01 08:43:25 +02:00
return
}
2026-09-13 18:43:16 +02:00
email , err := normalizeProxyEmail ( input . Email )
2026-09-02 21:45:19 +02:00
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusBadRequest , err . Error ())
2026-09-01 08:43:25 +02:00
return
}
2026-09-13 18:43:16 +02:00
username , err := normalizeProxyUsername ( input . Username )
2026-09-02 21:45:19 +02:00
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusBadRequest , err . Error ())
2026-09-01 08:43:25 +02:00
return
}
2026-09-02 21:45:19 +02:00
managedInput := authclient . ManagedUserInput { Username : username , Email : email }
2026-09-01 08:43:25 +02:00
if input . Password != "" {
2026-09-13 18:43:16 +02:00
if err := validateProxyPassword ( input . Password ); err != nil {
writeProxyError ( w , http . StatusBadRequest , err . Error ())
2026-09-01 08:43:25 +02:00
return
}
2026-09-02 21:45:19 +02:00
managedInput . Password = input . Password
2026-09-01 08:43:25 +02:00
}
2026-09-02 21:45:19 +02:00
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" )
2026-09-01 08:43:25 +02:00
return
}
updated , err := s . CurrentUser ( r )
if err != nil || updated == nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , "profile could not be loaded" )
2026-09-01 08:43:25 +02:00
return
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] any { "user" : updated })
2026-09-01 08:43:25 +02:00
}
2026-09-02 21:45:19 +02:00
// AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc
// comment's "Setup flow" section.
2026-09-01 08:43:25 +02:00
func ( s * Service ) AdminNeeded ( w http . ResponseWriter , r * http . Request ) {
2026-09-15 23:27:42 +02:00
if s . configurationError != nil {
writeProxyError ( w , http . StatusInternalServerError , s . configurationError . Error ())
return
}
2026-09-02 21:45:19 +02:00
if ! s . enabled () {
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] bool { "adminNeeded" : false })
2026-09-02 21:45:19 +02:00
return
}
2026-09-16 23:58:00 +02:00
loginRequired , err := s . LoginRequired ( r . Context ())
if err != nil {
writeProxyError ( w , http . StatusInternalServerError , "authentication status unavailable" )
return
}
if ! loginRequired {
writeProxyJSON ( w , http . StatusOK , map [ string ] bool { "adminNeeded" : false })
return
}
2026-09-02 21:45:19 +02:00
claimed , err := s . isSetupClaimed ( r . Context ())
2026-09-01 08:43:25 +02:00
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , "authentication status unavailable" )
2026-09-01 08:43:25 +02:00
return
}
2026-09-02 21:45:19 +02:00
if claimed {
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] bool { "adminNeeded" : false })
2026-09-02 21:45:19 +02:00
return
}
setupRequired , err := s . authGuard . SetupStatus ( r . Context ())
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-09-02 21:45:19 +02:00
return
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] bool { "adminNeeded" : setupRequired })
2026-09-01 08:43:25 +02:00
}
2026-10-19 21:46:52 +00:00
// LoginRequired caches the store's value briefly to avoid a database read for
// every authenticated route. Updates through this Service clear the cache
// immediately; changes made by another replica become visible within two seconds.
2026-09-01 08:43:25 +02:00
func ( s * Service ) LoginRequired ( ctx context . Context ) ( bool , error ) {
2026-09-17 00:14:56 +02:00
if s . store == nil {
return true , nil
}
2026-10-19 21:46:52 +00:00
now := time . Now ()
s . loginCacheMu . Lock ()
if s . loginCacheSet && now . Before ( s . loginCacheExpires ) {
value := s . loginCacheValue
s . loginCacheMu . Unlock ()
return value , nil
}
s . loginCacheMu . Unlock ()
value , err := s . store . LoginRequired ( ctx )
if err != nil {
return false , err
}
s . loginCacheMu . Lock ()
if s . loginCacheSet && time . Now (). Before ( s . loginCacheExpires ) {
cached := s . loginCacheValue
s . loginCacheMu . Unlock ()
return cached , nil
}
s . loginCacheValue = value
s . loginCacheSet = true
s . loginCacheExpires = time . Now (). Add ( 2 * time . Second )
s . loginCacheMu . Unlock ()
return value , nil
2026-09-01 08:43:25 +02:00
}
func ( s * Service ) AccessSettings ( w http . ResponseWriter , r * http . Request ) {
loginRequired , err := s . LoginRequired ( r . Context ())
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , "access settings unavailable" )
2026-09-01 08:43:25 +02:00
return
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] bool { "loginRequired" : loginRequired })
2026-09-01 08:43:25 +02:00
}
func ( s * Service ) UpdateAccessSettings ( w http . ResponseWriter , r * http . Request ) {
var input struct {
LoginRequired * bool `json:"loginRequired"`
}
2026-09-13 18:43:16 +02:00
if err := decodeProxyJSON ( r , & input ); err != nil || input . LoginRequired == nil {
writeProxyError ( w , http . StatusBadRequest , "loginRequired must be a boolean" )
2026-09-01 08:43:25 +02:00
return
}
2026-09-09 22:24:03 +02:00
if err := s . SetLoginRequired ( r . Context (), * input . LoginRequired ); err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , "access setting could not be saved" )
2026-09-01 08:43:25 +02:00
return
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] bool { "loginRequired" : * input . LoginRequired })
2026-09-01 08:43:25 +02:00
}
2026-09-09 22:24:03 +02:00
// SetLoginRequired writes the auth_required flag directly, the same one UpdateAccessSettings
// exposes to a manager-authenticated session - callers reach this from an X-Internal-Auth-gated
// route instead (see each service's own setLoginRequiredInternal), letting ProjectConfigurator's
// central "Require Login" toggle (ConfigWorkspace.svelte's loginControls) apply here without an
// admin session of its own.
func ( s * Service ) SetLoginRequired ( ctx context . Context , required bool ) error {
2026-10-19 21:46:52 +00:00
if s . store == nil {
return errNoLoginRequiredStore
2026-09-17 00:14:56 +02:00
}
2026-10-19 21:46:52 +00:00
if err := s . store . SetLoginRequired ( ctx , required ); err != nil {
return err
}
// Drop the cached value rather than setting it, so the next read comes from the store and a
// store that discards writes cannot leave this process with its own login setting.
s . loginCacheMu . Lock ()
s . loginCacheSet = false
s . loginCacheMu . Unlock ()
2026-09-17 00:14:56 +02:00
return nil
}
// SetLoginRequiredInternal returns the X-Internal-Auth-gated handler used by
// ProjectConfigurator to apply its per-project "Require Login" setting. It
// lives on the shared service so projects outside the core-service family can
// expose the same propagation endpoint without duplicating its JSON handling.
func ( s * Service ) SetLoginRequiredInternal ( secret string ) http . Handler {
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
2026-10-19 21:46:52 +00:00
if strings . TrimSpace ( secret ) == "" || subtle . ConstantTimeCompare ([] byte ( r . Header . Get ( "X-Internal-Auth" )), [] byte ( secret )) != 1 {
2026-09-17 00:14:56 +02:00
writeProxyError ( w , http . StatusUnauthorized , "internal service authentication required" )
return
}
var input struct {
LoginRequired * bool `json:"loginRequired"`
}
if err := decodeProxyJSON ( r , & input ); err != nil || input . LoginRequired == nil {
writeProxyError ( w , http . StatusBadRequest , "loginRequired must be a boolean" )
return
}
if err := s . SetLoginRequired ( r . Context (), * input . LoginRequired ); err != nil {
writeProxyError ( w , http . StatusInternalServerError , "access setting could not be saved" )
return
}
writeProxyJSON ( w , http . StatusOK , map [ string ] bool { "loginRequired" : * input . LoginRequired })
})
2026-09-09 22:24:03 +02:00
}
2026-09-01 08:43:25 +02:00
func ( s * Service ) Status ( w http . ResponseWriter , r * http . Request ) {
2026-09-15 23:27:42 +02:00
if s . configurationError != nil {
writeProxyError ( w , http . StatusInternalServerError , s . configurationError . Error ())
return
}
2026-09-02 21:45:19 +02:00
if ! s . enabled () {
2026-09-16 23:58:00 +02:00
user := adminProfile
writeProxyJSON ( w , http . StatusOK , map [ string ] any { "setupRequired" : false , "authenticated" : true , "authRequired" : false , "user" : & user })
return
}
loginRequired , err := s . LoginRequired ( r . Context ())
if err != nil {
writeProxyError ( w , http . StatusInternalServerError , "authentication status unavailable" )
return
}
if ! loginRequired {
user := adminProfile
writeProxyJSON ( w , http . StatusOK , map [ string ] any {
"setupRequired" : false , "authenticated" : true , "authRequired" : false , "user" : & user ,
})
2026-09-02 21:45:19 +02:00
return
}
claimed , err := s . isSetupClaimed ( r . Context ())
2026-09-01 08:43:25 +02:00
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , "authentication status unavailable" )
2026-09-01 08:43:25 +02:00
return
}
2026-09-02 21:45:19 +02:00
setupRequired := false
if ! claimed {
setupRequired , err = s . authGuard . SetupStatus ( r . Context ())
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-09-02 21:45:19 +02:00
return
}
}
user , err := s . CurrentUser ( r )
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-09-02 21:45:19 +02:00
return
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] any {
2026-09-02 21:45:19 +02:00
"setupRequired" : setupRequired , "authenticated" : user != nil , "authRequired" : loginRequired , "user" : user ,
2026-09-01 08:43:25 +02:00
})
}
2026-09-02 21:45:19 +02:00
// 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 ,
2026-09-13 18:43:16 +02:00
"role" : string ( NormalizeRole ( user . Role )), "createdAt" : user . CreatedAt ,
2026-09-02 21:45:19 +02:00
}
}
// 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.
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , [] map [ string ] any {})
2026-09-02 21:45:19 +02:00
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 ))
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , result )
2026-09-02 21:45:19 +02:00
}
// 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 () {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
2026-09-02 21:45:19 +02:00
return
}
var input struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
Role string `json:"role"`
}
2026-09-13 18:43:16 +02:00
if err := decodeProxyJSON ( r , & input ); err != nil {
writeProxyError ( w , http . StatusBadRequest , "invalid JSON body" )
2026-09-02 21:45:19 +02:00
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
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusCreated , managedUserPayload ( * created ))
2026-09-02 21:45:19 +02:00
}
// 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 ) {
2026-09-13 12:18:24 +02:00
id , err := strconv . ParseInt ( idURLParam ( r ), 10 , 64 )
2026-09-02 21:45:19 +02:00
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusBadRequest , "invalid user id" )
2026-09-02 21:45:19 +02:00
return
}
if ! s . enabled () {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
2026-09-02 21:45:19 +02:00
return
}
var input struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
Role * string `json:"role"`
}
2026-09-13 18:43:16 +02:00
if err := decodeProxyJSON ( r , & input ); err != nil {
writeProxyError ( w , http . StatusBadRequest , "invalid JSON body" )
2026-09-02 21:45:19 +02:00
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 {
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , managedUserPayload ( user ))
2026-09-02 21:45:19 +02:00
return
}
}
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusNotFound , "user not found" )
2026-09-02 21:45:19 +02:00
}
// 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 ) {
2026-10-19 21:46:52 +00:00
if refuseCrossSite ( w , r ) {
return
}
2026-09-13 12:18:24 +02:00
id , err := strconv . ParseInt ( idURLParam ( r ), 10 , 64 )
2026-09-02 21:45:19 +02:00
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusBadRequest , "invalid user id" )
2026-09-02 21:45:19 +02:00
return
}
if ! s . enabled () {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
2026-09-02 21:45:19 +02:00
return
}
if err := s . authGuard . DeleteManagedUser ( r . Context (), s . sessionToken ( r ), id ); err != nil {
writeAuthGuardError ( w , err , "user could not be deleted" )
return
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] bool { "ok" : true })
2026-09-02 21:45:19 +02:00
}
// 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 () {
2026-09-16 23:58:00 +02:00
user := adminProfile
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusCreated , map [ string ] any { "user" : & user })
2026-09-02 21:45:19 +02:00
return
}
2026-10-19 21:46:52 +00:00
// First-run setup only applies while login is required. With login off, every
// caller already gets the local admin identity, and a fresh AuthGuard would make
// an anonymous signup its superadmin.
loginRequired , err := s . LoginRequired ( r . Context ())
if err != nil {
writeProxyError ( w , http . StatusInternalServerError , "authentication status unavailable" )
return
}
if ! loginRequired {
writeProxyError ( w , http . StatusConflict , errSetupRequiresLogin . Error ())
return
}
2026-09-02 21:45:19 +02:00
var input struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
}
2026-09-13 18:43:16 +02:00
if err := decodeProxyJSON ( r , & input ); err != nil {
writeProxyError ( w , http . StatusBadRequest , "invalid JSON body" )
2026-09-02 21:45:19 +02:00
return
}
2026-09-13 18:43:16 +02:00
email , err := normalizeProxyEmail ( input . Email )
2026-09-02 21:45:19 +02:00
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusBadRequest , err . Error ())
2026-09-02 21:45:19 +02:00
return
}
username := strings . TrimSpace ( input . Username )
if username == "" {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusBadRequest , "a username is required" )
2026-09-02 21:45:19 +02:00
return
}
2026-09-13 18:43:16 +02:00
if _ , err := normalizeProxyUsername ( username ); err != nil {
writeProxyError ( w , http . StatusBadRequest , err . Error ())
2026-09-02 21:45:19 +02:00
return
}
2026-09-13 18:43:16 +02:00
if err := validateProxyPassword ( input . Password ); err != nil {
writeProxyError ( w , http . StatusBadRequest , err . Error ())
2026-09-02 21:45:19 +02:00
return
}
claimed , err := s . tryClaimSetup ( r . Context ())
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , "internal error" )
2026-09-02 21:45:19 +02:00
return
}
if ! claimed {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusConflict , "Setup has already been completed." )
2026-09-02 21:45:19 +02:00
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 {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , "internal error" )
2026-09-02 21:45:19 +02:00
return
}
if err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-09-02 21:45:19 +02:00
return
}
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusConflict , "Setup has already been completed." )
2026-09-02 21:45:19 +02:00
return
}
2026-10-19 21:46:52 +00:00
result , err := s . authGuard . Register ( s . withClientIP ( r ), username , email , input . Password )
2026-09-02 21:45:19 +02:00
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 {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , "internal error" )
2026-09-02 21:45:19 +02:00
return
}
writeAuthGuardError ( w , err , "could not create account" )
return
}
authclient . ForwardCookies ( w , result . Cookies )
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusCreated , map [ string ] any { "user" : toUser ( result . User )})
2026-09-02 21:45:19 +02:00
}
func ( s * Service ) Login ( w http . ResponseWriter , r * http . Request ) {
if ! s . enabled () {
2026-09-16 23:58:00 +02:00
user := adminProfile
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] any { "user" : & user })
2026-09-02 21:45:19 +02:00
return
}
var input struct {
Identifier string `json:"identifier"`
Email string `json:"email"`
Password string `json:"password"`
TOTPToken string `json:"totpToken"`
}
2026-09-13 18:43:16 +02:00
if err := decodeProxyJSON ( r , & input ); err != nil {
writeProxyError ( w , http . StatusBadRequest , "invalid JSON body" )
2026-09-02 21:45:19 +02:00
return
}
identifier := strings . TrimSpace ( input . Identifier )
if identifier == "" {
identifier = strings . TrimSpace ( input . Email )
}
if identifier == "" {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , ErrInvalidLogin . Error ())
2026-09-02 21:45:19 +02:00
return
}
2026-10-19 21:46:52 +00:00
now := time . Now ()
if ! s . loginAccountAttempts . allow ( strings . ToLower ( identifier ), now ) || ! s . loginClientAttempts . allow ( s . clientAddress ( r ), now ) {
writeProxyError ( w , http . StatusTooManyRequests , errTooManyAttempts . Error ())
return
}
2026-09-02 21:45:19 +02:00
2026-10-19 21:46:52 +00:00
result , err := s . authGuard . Login ( s . withClientIP ( r ), identifier , input . Password , input . TOTPToken )
2026-09-02 21:45:19 +02:00
if err != nil {
var apiErr * authclient . APIError
if errors . As ( err , & apiErr ) {
if apiErr . TOTPRequired {
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusUnauthorized , map [ string ] any { "error" : "Two-factor authentication code required." , "mfaRequired" : true })
2026-09-02 21:45:19 +02:00
return
}
if apiErr . StatusCode == http . StatusUnauthorized {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , ErrInvalidLogin . Error ())
2026-09-02 21:45:19 +02:00
return
}
writeAuthGuardError ( w , err , "could not authenticate" )
return
}
// A non-APIError here means the call to AuthGuard itself failed
// (transport/connectivity); see errAuthGuardUnavailable.
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-09-02 21:45:19 +02:00
return
}
authclient . ForwardCookies ( w , result . Cookies )
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] any { "user" : toUser ( result . User )})
2026-09-02 21:45:19 +02:00
}
func ( s * Service ) Logout ( w http . ResponseWriter , r * http . Request ) {
2026-10-19 21:46:52 +00:00
if refuseCrossSite ( w , r ) {
return
}
2026-09-02 21:45:19 +02:00
if ! s . enabled () {
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] bool { "ok" : true })
2026-09-02 21:45:19 +02:00
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 ) {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , "internal error" )
2026-09-02 21:45:19 +02:00
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 )
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] bool { "ok" : true })
2026-09-02 21:45:19 +02:00
}
func ( s * Service ) TOTPStatus ( w http . ResponseWriter , r * http . Request ) {
if ! s . enabled () {
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] any { "enabled" : false , "mfaEnabled" : false })
2026-09-02 21:45:19 +02:00
return
}
user := UserFromContext ( r . Context ())
if user == nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , ErrUnauthorized . Error ())
2026-09-02 21:45:19 +02:00
return
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] any { "enabled" : user . MFAEnabled , "mfaEnabled" : user . MFAEnabled })
2026-09-02 21:45:19 +02:00
}
// 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 ) {
2026-10-19 21:46:52 +00:00
if refuseCrossSite ( w , r ) {
return
}
2026-09-02 21:45:19 +02:00
if ! s . enabled () {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
2026-09-02 21:45:19 +02:00
return
}
user := UserFromContext ( r . Context ())
if user == nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , ErrUnauthorized . Error ())
2026-09-02 21:45:19 +02:00
return
}
if user . MFAEnabled {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusConflict , "multi-factor authentication is already enabled" )
2026-09-02 21:45:19 +02:00
return
}
result , err := s . authGuard . TOTPEnable ( r . Context (), s . sessionToken ( r ))
if err != nil {
writeAuthGuardError ( w , err , "could not create authenticator secret" )
return
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] any { "data" : map [ string ] any {
2026-09-02 21:45:19 +02:00
"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 () {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
2026-09-02 21:45:19 +02:00
return
}
user := UserFromContext ( r . Context ())
if user == nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , ErrUnauthorized . Error ())
2026-09-02 21:45:19 +02:00
return
}
2026-10-19 21:46:52 +00:00
if ! s . totpAttempts . allow ( strconv . FormatInt ( user . ID , 10 ), time . Now ()) {
writeProxyError ( w , http . StatusTooManyRequests , errTooManyAttempts . Error ())
return
}
2026-09-02 21:45:19 +02:00
var input struct {
Token string `json:"token"`
TOTPToken string `json:"totpToken"`
}
2026-09-13 18:43:16 +02:00
if err := decodeProxyJSON ( r , & input ); err != nil {
writeProxyError ( w , http . StatusBadRequest , "invalid JSON body" )
2026-09-02 21:45:19 +02:00
return
}
token := strings . TrimSpace ( input . TOTPToken )
if token == "" {
token = strings . TrimSpace ( input . Token )
}
2026-10-19 21:46:52 +00:00
if err := s . authGuard . TOTPVerify ( s . withClientIP ( r ), s . sessionToken ( r ), token ); err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , "Invalid authenticator code." )
2026-09-02 21:45:19 +02:00
return
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] any { "data" : map [ string ] any { "mfaEnabled" : true , "enabled" : true , "backupCodes" : [] string {}}})
2026-09-02 21:45:19 +02:00
}
func ( s * Service ) TOTPDisable ( w http . ResponseWriter , r * http . Request ) {
if ! s . enabled () {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
2026-09-02 21:45:19 +02:00
return
}
user := UserFromContext ( r . Context ())
if user == nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , ErrUnauthorized . Error ())
2026-09-02 21:45:19 +02:00
return
}
2026-10-19 21:46:52 +00:00
if ! s . totpAttempts . allow ( strconv . FormatInt ( user . ID , 10 ), time . Now ()) {
writeProxyError ( w , http . StatusTooManyRequests , errTooManyAttempts . Error ())
return
}
2026-09-02 21:45:19 +02:00
var input struct {
Token string `json:"token"`
TOTPToken string `json:"totpToken"`
}
2026-09-13 18:43:16 +02:00
if err := decodeProxyJSON ( r , & input ); err != nil {
writeProxyError ( w , http . StatusBadRequest , "invalid JSON body" )
2026-09-02 21:45:19 +02:00
return
}
token := strings . TrimSpace ( input . TOTPToken )
if token == "" {
token = strings . TrimSpace ( input . Token )
}
2026-10-19 21:46:52 +00:00
if err := s . authGuard . TOTPDisable ( s . withClientIP ( r ), s . sessionToken ( r ), token ); err != nil {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusUnauthorized , "Invalid authenticator code." )
2026-09-02 21:45:19 +02:00
return
}
2026-09-13 18:43:16 +02:00
writeProxyJSON ( w , http . StatusOK , map [ string ] any { "data" : map [ string ] any { "mfaEnabled" : false , "enabled" : false }})
2026-09-02 21:45:19 +02:00
}
// 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 ) {
2026-09-13 12:18:24 +02:00
return s . store . IsSetupClaimed ( ctx )
2026-09-02 21:45:19 +02:00
}
func ( s * Service ) tryClaimSetup ( ctx context . Context ) ( bool , error ) {
2026-09-13 12:18:24 +02:00
return s . store . TryClaimSetup ( ctx )
2026-09-02 21:45:19 +02:00
}
func ( s * Service ) unclaimSetup ( ctx context . Context ) error {
2026-09-13 12:18:24 +02:00
return s . store . UnclaimSetup ( ctx )
2026-09-02 21:45:19 +02:00
}
// --- 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
2026-09-13 18:43:16 +02:00
// this migration. Note these methods are on *Service (the AuthGuard-proxy
// engine), a different receiver type than *Store (this package's own
// local-account persistence) - CreateUser/ListUsers/UpdateUser/DeleteUser
// exist on both with different signatures/purposes; Go's per-type method
// scoping means this is not a naming conflict.
2026-09-02 21:45:19 +02:00
2026-09-01 08:43:25 +02:00
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 ,
2026-09-13 18:43:16 +02:00
"role" : normalizePlatformRole ( user . Role ),
2026-09-01 08:43:25 +02:00
"createdAt" : user . CreatedAt ,
}
}
2026-09-13 18:43:16 +02:00
func ( s * Service ) CreateUser ( ctx context . Context , email , username , password , role string ) ( * ProxyUser , error ) {
email , username , password , err := normalizeProxyCredentials ( email , username , password )
2026-09-01 08:43:25 +02:00
if err != nil {
return nil , err
}
2026-09-13 18:43:16 +02:00
role = normalizePlatformRole ( role )
2026-10-19 21:46:52 +00:00
hash , err := HashPassword ( password )
2026-09-01 08:43:25 +02:00
if err != nil {
return nil , err
}
2026-09-13 18:43:16 +02:00
var user ProxyUser
2026-09-01 08:43:25 +02:00
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')
2026-10-19 21:46:52 +00:00
` , email , username , hash , role ). Scan ( & user . ID , & user . Email , & user . Username , & user . Role )
2026-09-01 08:43:25 +02:00
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 != "" {
2026-09-13 18:43:16 +02:00
role = normalizePlatformRole ( role )
2026-09-01 08:43:25 +02:00
}
_ , 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 {
2026-09-13 18:43:16 +02:00
if err := validateProxyPassword ( password ); err != nil {
2026-09-01 08:43:25 +02:00
return err
}
2026-10-19 21:46:52 +00:00
hash , err := HashPassword ( password )
2026-09-01 08:43:25 +02:00
if err != nil {
return err
}
2026-10-19 21:46:52 +00:00
_ , err = s . db . Exec ( ctx , `UPDATE users SET password_hash=$2 WHERE id=$1` , id , hash )
2026-09-01 08:43:25 +02:00
return err
}
2026-09-02 21:45:19 +02:00
// 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 ) {
2026-09-03 00:16:55 +02:00
if statusCode , message , ok := authproxy . APIErrorResponse ( err ); ok {
2026-09-13 18:43:16 +02:00
writeProxyError ( w , statusCode , message )
2026-09-02 21:45:19 +02:00
return
}
2026-09-13 18:43:16 +02:00
writeProxyError ( w , http . StatusInternalServerError , fallbackMessage )
2026-09-02 21:45:19 +02:00
}
2026-09-13 18:43:16 +02:00
func normalizeProxyUsername ( value string ) ( string , error ) {
2026-09-02 21:45:19 +02:00
value = strings . TrimSpace ( value )
if value == "" {
return "" , nil
}
2026-09-13 18:43:16 +02:00
if len ([] rune ( value )) > proxyMaxUsernameLength {
2026-09-02 21:45:19 +02:00
return "" , errors . New ( "username is too long" )
}
2026-10-19 21:46:52 +00:00
// An identifier containing "@" could be read as another account's email at login.
if strings . Contains ( value , "@" ) {
return "" , errors . New ( "username cannot contain @" )
}
2026-09-02 21:45:19 +02:00
return value , nil
}
2026-09-13 18:43:16 +02:00
func normalizeProxyEmail ( value string ) ( string , error ) {
2026-09-02 21:45:19 +02:00
value = strings . ToLower ( strings . TrimSpace ( value ))
2026-09-13 18:43:16 +02:00
if ! strings . Contains ( value , "@" ) || len ( value ) > proxyMaxEmailLength {
2026-09-02 21:45:19 +02:00
return "" , errors . New ( "a valid email is required" )
}
return value , nil
}
2026-09-13 18:43:16 +02:00
func validateProxyPassword ( password string ) error {
if len ([] rune ( password )) < proxyMinPasswordLength || len ([] rune ( password )) > 1024 {
2026-09-02 21:45:19 +02:00
return errors . New ( "Password must be at least 8 characters." )
2026-09-01 08:43:25 +02:00
}
2026-10-19 21:46:52 +00:00
// bcrypt uses only the first 72 bytes, so a longer password would be refused at hashing time.
if len ( password ) > maxBcryptPasswordBytes {
return errors . New ( "Password must be at most 72 bytes." )
}
2026-09-01 08:43:25 +02:00
return nil
}
2026-09-13 18:43:16 +02:00
// normalizeProxyCredentials validates email/password format (username is
2026-09-02 21:45:19 +02:00
// optional here - Signup separately requires it be non-empty; kept this way
// to preserve this package's existing test coverage/contract).
2026-09-13 18:43:16 +02:00
func normalizeProxyCredentials ( email , username , password string ) ( string , string , string , error ) {
email , err := normalizeProxyEmail ( email )
2026-09-02 21:45:19 +02:00
if err != nil {
return "" , "" , "" , err
2026-09-01 08:43:25 +02:00
}
2026-09-13 18:43:16 +02:00
username , err = normalizeProxyUsername ( username )
2026-09-02 21:45:19 +02:00
if err != nil {
return "" , "" , "" , err
2026-09-01 08:43:25 +02:00
}
2026-09-13 18:43:16 +02:00
if err := validateProxyPassword ( password ); err != nil {
2026-09-02 21:45:19 +02:00
return "" , "" , "" , err
2026-09-01 08:43:25 +02:00
}
return email , username , password , nil
}
2026-09-13 18:43:16 +02:00
// normalizePlatformRole normalizes a "moderatable platform user" role (see
// that section's doc comment above) - a different, looser role set
// (moderator included) than the account-login Role type NormalizeRole
// governs elsewhere in this package.
func normalizePlatformRole ( role string ) string {
2026-09-01 08:43:25 +02:00
switch strings . ToLower ( strings . TrimSpace ( role )) {
case "admin" , "superadmin" , "moderator" :
return strings . ToLower ( strings . TrimSpace ( role ))
default :
return "user"
}
}
2026-09-13 12:18:24 +02:00
// idURLParam extracts the "{id}" path segment from ManagedUpdateUser's/
// ManagedDeleteUser's route regardless of which router mounted it: chi's
// URLParam for the (7) media-family services that route through chi, or the
// standard library's 1.22+ ServeMux PathValue (what GameStream, OmniLogger,
// and other non-chi consumers of this package use) when chi reports none.
func idURLParam ( r * http . Request ) string {
if id := chi . URLParam ( r , "id" ); id != "" {
return id
}
return r . PathValue ( "id" )
}
2026-10-19 21:46:52 +00:00
// decodeProxyJSON reads a JSON request body. It refuses a body that is not sent as
// application/json, which a cross-site HTML form cannot produce, and any request the browser
// marks as cross-site.
// refuseCrossSite answers a state-changing request that carries no JSON body (logout, TOTP
// initiate, user delete) when the browser says it came from another site. Simple cross-site
// forms cannot send a JSON body, so decodeProxyJSON already refuses them; this covers the rest.
func refuseCrossSite ( w http . ResponseWriter , r * http . Request ) bool {
if r . Header . Get ( "Sec-Fetch-Site" ) == "cross-site" {
writeProxyError ( w , http . StatusForbidden , errCrossSiteRequest . Error ())
return true
}
return false
}
2026-09-13 18:43:16 +02:00
func decodeProxyJSON ( r * http . Request , target any ) error {
2026-09-01 08:43:25 +02:00
defer r . Body . Close ()
2026-10-19 21:46:52 +00:00
if r . Header . Get ( "Sec-Fetch-Site" ) == "cross-site" {
return errCrossSiteRequest
}
mediaType , _ , err := mime . ParseMediaType ( r . Header . Get ( "Content-Type" ))
if err != nil || mediaType != "application/json" {
return errJSONContentType
}
2026-09-01 08:43:25 +02:00
decoder := json . NewDecoder ( io . LimitReader ( r . Body , 128 * 1024 ))
return decoder . Decode ( target )
}
2026-09-13 18:43:16 +02:00
func writeProxyJSON ( w http . ResponseWriter , status int , value any ) {
2026-09-01 08:43:25 +02:00
w . Header (). Set ( "Content-Type" , "application/json; charset=utf-8" )
w . WriteHeader ( status )
_ = json . NewEncoder ( w ). Encode ( value )
}
2026-09-13 18:43:16 +02:00
func writeProxyError ( w http . ResponseWriter , status int , message string ) {
writeProxyJSON ( w , status , map [ string ] string { "error" : message , "message" : message })
2026-09-01 08:43:25 +02:00
}
2026-09-13 18:43:16 +02:00
func ( u ProxyUser ) String () string { return strconv . FormatInt ( u . ID , 10 ) }