2026-09-07 15:06:06 +02:00
// Package mediaauth is the shared media-backend family's /auth/... and /api/auth/...
// 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 15:06:06 +02:00
// MediaViewer, ContentScanner, CraftStudio) use one copy instead of
// duplicating it.
2026-09-02 21:45:19 +02:00
//
2026-09-13 12:16:17 +02:00
// Unified auth proxy
// ==================
// This package used to be 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 Store adapter over
// whatever local table they already used for their "login required" toggle
// and one-time setup-claim flag (see the Store 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 Store implementation backed by the shared
// `settings` table.
//
// 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-07 16:00:08 +02:00
// via the `authclient` package (Web/Core/shared/backend/authclient,
2026-09-02 21:45:19 +02:00
// 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
2026-09-04 15:02:16 +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:02:16 +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.
// - The `bio`/`avatarUrl` fields the pre-migration User type carried are
// dropped entirely: AuthGuard has no such concept, and grepping the
2026-09-04 15:02:16 +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.
//
// 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).
2026-09-07 15:06:06 +02:00
package mediaauth
2026-08-31 22:06:29 +02:00
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"
2026-09-02 21:45:19 +02:00
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
2026-09-03 00:14:01 +02:00
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
2026-08-31 22:06:29 +02:00
)
2026-09-02 21:45:19 +02:00
// 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.
2026-08-31 22:06:29 +02:00
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." )
2026-09-02 21:45:19 +02:00
// 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." )
2026-08-31 22:06:29 +02:00
)
2026-09-02 21:45:19 +02:00
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 }
2026-08-31 22:06:29 +02:00
2026-09-13 12:16:17 +02:00
// Store 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
// 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.
type Store interface {
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-08-31 22:06:29 +02:00
type Service struct {
2026-09-13 12:16:17 +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-08-31 22:06:29 +02:00
db * pgxpool . Pool
2026-09-13 12:16:17 +02:00
store Store
2026-08-31 22:06:29 +02:00
cookieName string
secureCookies bool
2026-09-02 21:45:19 +02:00
// authGuard is nil when AUTHGUARD_URL is unset; see the top-of-file doc
// comment's "Auth-disabled mode" section.
authGuard * authclient . Client
2026-08-31 22:06:29 +02:00
}
2026-09-13 12:16:17 +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-02 21:45:19 +02:00
// authclient.DefaultCookieName. authGuardURL is AUTHGUARD_URL; empty means
2026-09-13 12:16:17 +02:00
// auth-disabled mode. 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 ) * Service {
service := NewWithStore ( pgSettingsStore { db : db }, cookieName , secureCookies , authGuardURL , projectKey )
service . db = db
return service
}
// NewWithStore constructs a Service against any Store 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).
func NewWithStore ( store Store , cookieName string , secureCookies bool , authGuardURL , projectKey string ) * Service {
2026-09-02 21:45:19 +02:00
var client * authclient . Client
if strings . TrimSpace ( authGuardURL ) != "" {
2026-09-13 12:16:17 +02:00
client = authclient . New ( authGuardURL , authclient . WithProjectKey ( projectKey ))
2026-08-31 22:06:29 +02:00
}
2026-09-13 12:16:17 +02:00
return & Service { store : store , cookieName : cookieName , secureCookies : secureCookies , authGuard : client }
}
// pgSettingsStore is the default Store New builds over the media family's
// shared `settings` key/value table (see mediacore.SettingValue/
// SaveSetting) - unchanged behavior from before this package accepted a
// pluggable Store.
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
}
// 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
2026-08-31 22:06:29 +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
// projects" section) so a live authguard_url change applies without a
// restart, the same as a project holding its own *authclient.Client
// directly. A no-op if this Service was constructed in auth-disabled mode
// (AUTHGUARD_URL unset at startup - see the "Auth-disabled mode" section):
// there is no client to retarget, and this package has no path to start
// authenticating requests it previously always let through.
func ( s * Service ) SetAuthGuardBaseURL ( baseURL string ) {
if s . authGuard != nil {
s . authGuard . SetBaseURL ( baseURL )
}
}
2026-08-31 22:06:29 +02:00
func UserFromContext ( ctx context . Context ) * User {
value , _ := ctx . Value ( userContextKey ).( * User )
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:14:01 +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:14:01 +02:00
authproxy . ClearSessionCookies ( w , s . cookieName , s . secureCookies )
2026-09-02 21:45:19 +02:00
}
// 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.
2026-08-31 22:06:29 +02:00
func ( s * Service ) CurrentUser ( r * http . Request ) ( * User , error ) {
2026-09-02 21:45:19 +02:00
if ! s . enabled () {
user := localProfile
return & user , nil
2026-08-31 22:06:29 +02:00
}
2026-09-02 21:45:19 +02:00
profile , err := s . currentProfile ( r . Context (), s . sessionToken ( r ))
2026-08-31 22:06:29 +02:00
if err != nil {
return nil , err
}
2026-09-02 21:45:19 +02:00
if profile == nil {
2026-08-31 22:06:29 +02:00
return nil , nil
}
2026-09-02 21:45:19 +02:00
return toUser ( * profile ), nil
2026-08-31 22:06:29 +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-02 21:45:19 +02:00
writeError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-08-31 22:06:29 +02:00
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
2026-09-02 21:45:19 +02:00
// do not need a user identity. This toggle is independent of AuthGuard - see
// the package doc comment's second paragraph.
2026-08-31 22:06:29 +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
}
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 )
}))
}
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 ())
if ! sharedauth . CanManageUsers ( user . Role ) {
writeError ( w , http . StatusForbidden , ErrForbidden . Error ())
return
}
next . ServeHTTP ( w , r )
}))
}
2026-08-31 22:06:29 +02:00
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 {
2026-09-02 21:45:19 +02:00
writeError ( w , http . StatusInternalServerError , errAuthGuardUnavailable . Error ())
2026-08-31 22:06:29 +02:00
return
}
loginRequired , err := s . LoginRequired ( r . Context ())
if err != nil {
writeError ( w , http . StatusInternalServerError , "authentication status unavailable" )
return
}
2026-09-02 21:45:19 +02:00
writeJSON ( w , http . StatusOK , map [ string ] any { "user" : user , "authRequired" : loginRequired })
2026-08-31 22:06:29 +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-08-31 22:06:29 +02:00
func ( s * Service ) UpdateMe ( w http . ResponseWriter , r * http . Request ) {
2026-09-02 21:45:19 +02:00
if ! s . enabled () {
writeError ( w , http . StatusConflict , errFeatureRequiresAuthGuard . Error ())
return
}
current := UserFromContext ( r . Context ())
if current == nil {
2026-08-31 22:06:29 +02:00
writeError ( w , http . StatusUnauthorized , ErrUnauthorized . Error ())
return
}
2026-09-02 21:45:19 +02:00
if ! sharedauth . CanManageUsers ( current . Role ) {
writeError ( w , http . StatusForbidden , errSelfServiceProfile . Error ())
return
}
2026-08-31 22:06:29 +02:00
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
}
2026-09-02 21:45:19 +02:00
email , err := normalizeEmail ( input . Email )
if err != nil {
writeError ( w , http . StatusBadRequest , err . Error ())
2026-08-31 22:06:29 +02:00
return
}
2026-09-02 21:45:19 +02:00
username , err := normalizeUsername ( input . Username )
if err != nil {
writeError ( w , http . StatusBadRequest , err . Error ())
2026-08-31 22:06:29 +02:00
return
}
2026-09-02 21:45:19 +02:00
managedInput := authclient . ManagedUserInput { Username : username , Email : email }
2026-08-31 22:06:29 +02:00
if input . Password != "" {
if err := validatePassword ( input . Password ); err != nil {
writeError ( w , http . StatusBadRequest , err . Error ())
return
}
2026-09-02 21:45:19 +02:00
managedInput . Password = input . Password
2026-08-31 22:06:29 +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-08-31 22:06:29 +02:00
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 })
}
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-08-31 22:06:29 +02:00
func ( s * Service ) AdminNeeded ( w http . ResponseWriter , r * http . Request ) {
2026-09-02 21:45:19 +02:00
if ! s . enabled () {
writeJSON ( w , http . StatusOK , map [ string ] bool { "adminNeeded" : false })
return
}
claimed , err := s . isSetupClaimed ( r . Context ())
2026-08-31 22:06:29 +02:00
if err != nil {
writeError ( w , http . StatusInternalServerError , "authentication status unavailable" )
return
}
2026-09-02 21:45:19 +02:00
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 })
2026-08-31 22:06:29 +02:00
}
func ( s * Service ) LoginRequired ( ctx context . Context ) ( bool , error ) {
2026-09-13 12:16:17 +02:00
return s . store . LoginRequired ( ctx )
2026-08-31 22:06:29 +02:00
}
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
}
2026-09-09 22:24:03 +02:00
if err := s . SetLoginRequired ( r . Context (), * input . LoginRequired ); err != nil {
2026-08-31 22:06:29 +02:00
writeError ( w , http . StatusInternalServerError , "access setting could not be saved" )
return
}
writeJSON ( w , http . StatusOK , map [ string ] bool { "loginRequired" : * input . LoginRequired })
}
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-09-13 12:16:17 +02:00
return s . store . SetLoginRequired ( ctx , required )
2026-09-09 22:24:03 +02:00
}
2026-08-31 22:06:29 +02:00
func ( s * Service ) Status ( w http . ResponseWriter , r * http . Request ) {
2026-09-02 21:45:19 +02:00
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 ())
2026-08-31 22:06:29 +02:00
if err != nil {
writeError ( w , http . StatusInternalServerError , "authentication status unavailable" )
return
}
2026-09-02 21:45:19 +02:00
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
}
2026-08-31 22:06:29 +02:00
loginRequired , err := s . LoginRequired ( r . Context ())
if err != nil {
writeError ( w , http . StatusInternalServerError , "authentication status unavailable" )
return
}
writeJSON ( w , http . StatusOK , map [ string ] any {
2026-09-02 21:45:19 +02:00
"setupRequired" : setupRequired , "authenticated" : user != nil , "authRequired" : loginRequired , "user" : user ,
2026-08-31 22:06:29 +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 ,
"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 ) {
2026-09-13 12:16:17 +02:00
id , err := strconv . ParseInt ( idURLParam ( r ), 10 , 64 )
2026-09-02 21:45:19 +02:00
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 ) {
2026-09-13 12:16:17 +02:00
id , err := strconv . ParseInt ( idURLParam ( r ), 10 , 64 )
2026-09-02 21:45:19 +02:00
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 ) {
2026-09-13 12:16:17 +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:16:17 +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:16:17 +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
// this migration.
2026-08-31 22:06:29 +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-02 21:45:19 +02:00
"role" : normalizeRole ( user . Role ),
2026-08-31 22:06:29 +02:00
"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
}
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:14:01 +02:00
if statusCode , message , ok := authproxy . APIErrorResponse ( err ); ok {
writeError ( w , statusCode , message )
2026-09-02 21:45:19 +02:00
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
}
2026-08-31 22:06:29 +02:00
func validatePassword ( password string ) error {
2026-09-02 21:45:19 +02:00
if len ([] rune ( password )) < minPasswordLength || len ([] rune ( password )) > 1024 {
return errors . New ( "Password must be at least 8 characters." )
2026-08-31 22:06:29 +02:00
}
return nil
}
2026-09-02 21:45:19 +02:00
// 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).
2026-08-31 22:06:29 +02:00
func normalizeCredentials ( email , username , password string ) ( string , string , string , error ) {
2026-09-02 21:45:19 +02:00
email , err := normalizeEmail ( email )
if err != nil {
return "" , "" , "" , err
2026-08-31 22:06:29 +02:00
}
2026-09-02 21:45:19 +02:00
username , err = normalizeUsername ( username )
if err != nil {
return "" , "" , "" , err
2026-08-31 22:06:29 +02:00
}
2026-09-02 21:45:19 +02:00
if err := validatePassword ( password ); err != nil {
return "" , "" , "" , err
2026-08-31 22:06:29 +02:00
}
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"
}
}
2026-09-13 12:16:17 +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-08-31 22:06:29 +02:00
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 ) }