diff --git a/shared/backend/mediaauth/auth.go b/shared/backend/auth/proxy.go similarity index 73% rename from shared/backend/mediaauth/auth.go rename to shared/backend/auth/proxy.go index 480b3b6..eb22027 100644 --- a/shared/backend/mediaauth/auth.go +++ b/shared/backend/auth/proxy.go @@ -1,25 +1,31 @@ -// Package mediaauth is the shared media-backend family's /auth/... and /api/auth/... +// This file holds 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 // backends (CarrierNode, ModerationHub, ProjectConfigurator, KioskDisplay, // MediaViewer, ContentScanner, CraftStudio) use one copy instead of -// duplicating it. +// 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. // // 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. +// 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. // // ProjectKey (New/NewWithStore's last parameter) identifies the calling // project to AuthGuard on every request (authclient.WithProjectKey), so an @@ -38,9 +44,7 @@ // // It now proxies every auth operation to AuthGuard (Web/Core/AuthGuard), // a centralized identity service other projects in this workspace share, -// via the `authclient` package (Web/Core/shared/backend/authclient, -// resolved through this module's own `repos.gfranz.ch/Gabriel20xx/shared/backend` -// dependency - same module that already provided `sharedauth`). This +// via the `authclient` package (Web/Core/shared/backend/authclient). This // service's own /auth/... and /api/auth/... URL paths and JSON response // shapes are UNCHANGED - the frontend (webui) was not touched - only // what backs them changed. This mirrors the migration @@ -103,8 +107,8 @@ // 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 +// - The `bio`/`avatarUrl` fields the pre-migration ProxyUser type carried +// are dropped entirely: AuthGuard has no such concept, and grepping the // frontend (webui) confirms neither field was ever actually read // or set by any UI - they were dead weight even before this migration. // @@ -140,7 +144,8 @@ // centralized in AuthGuard now, and only AuthGuard's own web UI exposes an // admin-reset affordance. Those two routes are removed entirely, not // adapted (see server.go). -package mediaauth + +package auth import ( "context" @@ -156,16 +161,19 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "golang.org/x/crypto/bcrypt" - sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" "repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy" ) -// User is this service's own /auth/... response shape - UNCHANGED from +// ProxyUser is this service's own /auth/... response shape - UNCHANGED from // before this migration except Bio/Avatar (see the package doc comment's // "Known gaps" section), sourced from AuthGuard's authclient.PublicUser via -// toUser rather than a local table. -type User struct { +// 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 { ID int64 `json:"id"` Email string `json:"email"` Username string `json:"username,omitempty"` @@ -174,9 +182,9 @@ type User struct { MFAEnabled bool `json:"mfaEnabled"` } -type contextKey struct{} +type proxyContextKey struct{} -var userContextKey contextKey +var proxyUserContextKey proxyContextKey var ( ErrUnauthorized = errors.New("authentication required") @@ -201,9 +209,9 @@ const ( loginRequiredSettingKey = "auth_required" setupClaimedSettingKey = "setup_claimed" - minPasswordLength = 8 - maxUsernameLength = 64 - maxEmailLength = 254 + proxyMinPasswordLength = 8 + proxyMaxUsernameLength = 64 + proxyMaxEmailLength = 254 ) // localProfile is the fixed placeholder identity CurrentUser/Signup/Login @@ -211,19 +219,19 @@ const ( // 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} +var localProfile = ProxyUser{ID: 0, Username: "local", Email: "", Role: string(RoleSuperAdmin), CanManageUsers: true} -// 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 +// 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 // 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 { +type ProxyStore interface { LoginRequired(ctx context.Context) (bool, error) SetLoginRequired(ctx context.Context, required bool) error IsSetupClaimed(ctx context.Context) (bool, error) @@ -239,7 +247,7 @@ type Service struct { // NewWithStore; those methods are simply never called by a project with // no such local platform-user table. db *pgxpool.Pool - store Store + store ProxyStore cookieName string secureCookies bool // authGuard is nil when AUTHGUARD_URL is unset; see the top-of-file doc @@ -264,13 +272,13 @@ func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL, 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 { +// 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). +func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authGuardURL, projectKey string) *Service { var client *authclient.Client if strings.TrimSpace(authGuardURL) != "" { client = authclient.New(authGuardURL, authclient.WithProjectKey(projectKey)) @@ -278,10 +286,10 @@ func NewWithStore(store Store, cookieName string, secureCookies bool, authGuardU 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/ +// pgSettingsStore is the default ProxyStore 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. +// pluggable ProxyStore. type pgSettingsStore struct { db *pgxpool.Pool } @@ -361,8 +369,8 @@ func (s *Service) SetAuthGuardBaseURL(baseURL string) { } } -func UserFromContext(ctx context.Context) *User { - value, _ := ctx.Value(userContextKey).(*User) +func UserFromContext(ctx context.Context) *ProxyUser { + value, _ := ctx.Value(proxyUserContextKey).(*ProxyUser) return value } @@ -379,12 +387,12 @@ func (s *Service) clearSessionCookies(w http.ResponseWriter) { authproxy.ClearSessionCookies(w, s.cookieName, s.secureCookies) } -// toUser translates AuthGuard's PublicUser into this service's own User -// response shape. -func toUser(profile authclient.PublicUser) *User { - return &User{ +// toUser translates AuthGuard's PublicUser into this service's own +// ProxyUser response shape. +func toUser(profile authclient.PublicUser) *ProxyUser { + return &ProxyUser{ ID: profile.ID, Email: profile.Email, Username: profile.Username, - Role: profile.Role, CanManageUsers: sharedauth.CanManageUsers(profile.Role), + Role: profile.Role, CanManageUsers: CanManageUsers(profile.Role), MFAEnabled: profile.TOTPEnabled, } } @@ -413,7 +421,7 @@ func (s *Service) currentProfile(ctx context.Context, token string) (*authclient // (Optional/Require/RequireAdmin/RequireUserManager/RequireIfLoginRequired/ // RequireAdminIfLoginRequired) resolves a session through - none of them // needed to change for this migration, only what CurrentUser itself does. -func (s *Service) CurrentUser(r *http.Request) (*User, error) { +func (s *Service) CurrentUser(r *http.Request) (*ProxyUser, error) { if !s.enabled() { user := localProfile return &user, nil @@ -432,11 +440,11 @@ func (s *Service) Optional(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, err := s.CurrentUser(r) if err != nil { - writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } if user != nil { - r = r.WithContext(context.WithValue(r.Context(), userContextKey, user)) + r = r.WithContext(context.WithValue(r.Context(), proxyUserContextKey, user)) } next.ServeHTTP(w, r) }) @@ -445,7 +453,7 @@ func (s *Service) Optional(next http.Handler) http.Handler { 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()) + writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) return } next.ServeHTTP(w, r) @@ -465,14 +473,14 @@ func (s *Service) RequireIfLoginRequired(next http.Handler) http.Handler { loginRequired, err := s.LoginRequired(r.Context()) if err != nil { - writeError(w, http.StatusInternalServerError, "authentication status unavailable") + writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable") return } if !loginRequired { next.ServeHTTP(w, r) return } - writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) })) } @@ -480,7 +488,7 @@ 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()) + writeProxyError(w, http.StatusForbidden, ErrForbidden.Error()) return } next.ServeHTTP(w, r) @@ -496,18 +504,18 @@ func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler { if user == nil { loginRequired, err := s.LoginRequired(r.Context()) if err != nil { - writeError(w, http.StatusInternalServerError, "authentication status unavailable") + writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable") return } if !loginRequired { next.ServeHTTP(w, r) return } - writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) return } if !IsAdmin(user) { - writeError(w, http.StatusForbidden, ErrForbidden.Error()) + writeProxyError(w, http.StatusForbidden, ErrForbidden.Error()) return } next.ServeHTTP(w, r) @@ -517,15 +525,15 @@ func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler { 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()) + if !CanManageUsers(user.Role) { + writeProxyError(w, http.StatusForbidden, ErrForbidden.Error()) return } next.ServeHTTP(w, r) })) } -func IsAdmin(user *User) bool { +func IsAdmin(user *ProxyUser) bool { if user == nil { return false } @@ -540,15 +548,15 @@ func IsAdmin(user *User) bool { func (s *Service) Me(w http.ResponseWriter, r *http.Request) { user, err := s.CurrentUser(r) if err != nil { - writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } loginRequired, err := s.LoginRequired(r.Context()) if err != nil { - writeError(w, http.StatusInternalServerError, "authentication status unavailable") + writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable") return } - writeJSON(w, http.StatusOK, map[string]any{"user": user, "authRequired": loginRequired}) + writeProxyJSON(w, http.StatusOK, map[string]any{"user": user, "authRequired": loginRequired}) } // UpdateMe lets the caller edit their own username/email/password. See the @@ -558,16 +566,16 @@ func (s *Service) Me(w http.ResponseWriter, r *http.Request) { // to self-edit today. func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) { if !s.enabled() { - writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) return } current := UserFromContext(r.Context()) if current == nil { - writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) return } - if !sharedauth.CanManageUsers(current.Role) { - writeError(w, http.StatusForbidden, errSelfServiceProfile.Error()) + if !CanManageUsers(current.Role) { + writeProxyError(w, http.StatusForbidden, errSelfServiceProfile.Error()) return } @@ -576,25 +584,25 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) { Username string `json:"username"` Password string `json:"password"` } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") + if err := decodeProxyJSON(r, &input); err != nil { + writeProxyError(w, http.StatusBadRequest, "invalid JSON body") return } - email, err := normalizeEmail(input.Email) + email, err := normalizeProxyEmail(input.Email) if err != nil { - writeError(w, http.StatusBadRequest, err.Error()) + writeProxyError(w, http.StatusBadRequest, err.Error()) return } - username, err := normalizeUsername(input.Username) + username, err := normalizeProxyUsername(input.Username) if err != nil { - writeError(w, http.StatusBadRequest, err.Error()) + writeProxyError(w, http.StatusBadRequest, err.Error()) return } managedInput := authclient.ManagedUserInput{Username: username, Email: email} if input.Password != "" { - if err := validatePassword(input.Password); err != nil { - writeError(w, http.StatusBadRequest, err.Error()) + if err := validateProxyPassword(input.Password); err != nil { + writeProxyError(w, http.StatusBadRequest, err.Error()) return } managedInput.Password = input.Password @@ -608,34 +616,34 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) { updated, err := s.CurrentUser(r) if err != nil || updated == nil { - writeError(w, http.StatusInternalServerError, "profile could not be loaded") + writeProxyError(w, http.StatusInternalServerError, "profile could not be loaded") return } - writeJSON(w, http.StatusOK, map[string]any{"user": updated}) + writeProxyJSON(w, http.StatusOK, map[string]any{"user": updated}) } // AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc // comment's "Setup flow" section. func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) { if !s.enabled() { - writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false}) + writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false}) return } claimed, err := s.isSetupClaimed(r.Context()) if err != nil { - writeError(w, http.StatusInternalServerError, "authentication status unavailable") + writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable") return } if claimed { - writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false}) + writeProxyJSON(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()) + writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } - writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": setupRequired}) + writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": setupRequired}) } func (s *Service) LoginRequired(ctx context.Context) (bool, error) { @@ -645,25 +653,25 @@ func (s *Service) LoginRequired(ctx context.Context) (bool, error) { 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") + writeProxyError(w, http.StatusInternalServerError, "access settings unavailable") return } - writeJSON(w, http.StatusOK, map[string]bool{"loginRequired": loginRequired}) + writeProxyJSON(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") + 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 { - writeError(w, http.StatusInternalServerError, "access setting could not be saved") + writeProxyError(w, http.StatusInternalServerError, "access setting could not be saved") return } - writeJSON(w, http.StatusOK, map[string]bool{"loginRequired": *input.LoginRequired}) + writeProxyJSON(w, http.StatusOK, map[string]bool{"loginRequired": *input.LoginRequired}) } // SetLoginRequired writes the auth_required flag directly, the same one UpdateAccessSettings @@ -678,33 +686,33 @@ func (s *Service) SetLoginRequired(ctx context.Context, required bool) error { func (s *Service) Status(w http.ResponseWriter, r *http.Request) { if !s.enabled() { user := localProfile - writeJSON(w, http.StatusOK, map[string]any{"setupRequired": false, "authenticated": true, "authRequired": true, "user": &user}) + writeProxyJSON(w, http.StatusOK, map[string]any{"setupRequired": false, "authenticated": true, "authRequired": true, "user": &user}) return } claimed, err := s.isSetupClaimed(r.Context()) if err != nil { - writeError(w, http.StatusInternalServerError, "authentication status unavailable") + writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable") return } setupRequired := false if !claimed { setupRequired, err = s.authGuard.SetupStatus(r.Context()) if err != nil { - writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } } user, err := s.CurrentUser(r) if err != nil { - writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } loginRequired, err := s.LoginRequired(r.Context()) if err != nil { - writeError(w, http.StatusInternalServerError, "authentication status unavailable") + writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable") return } - writeJSON(w, http.StatusOK, map[string]any{ + writeProxyJSON(w, http.StatusOK, map[string]any{ "setupRequired": setupRequired, "authenticated": user != nil, "authRequired": loginRequired, "user": user, }) } @@ -714,7 +722,7 @@ func (s *Service) Status(w http.ResponseWriter, r *http.Request) { 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, + "role": string(NormalizeRole(user.Role)), "createdAt": user.CreatedAt, } } @@ -728,7 +736,7 @@ func (s *Service) ManagedUsers(w http.ResponseWriter, r *http.Request) { // 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{}) + writeProxyJSON(w, http.StatusOK, []map[string]any{}) return } users, err := s.authGuard.ListManagedUsers(r.Context(), s.sessionToken(r)) @@ -740,7 +748,7 @@ func (s *Service) ManagedUsers(w http.ResponseWriter, r *http.Request) { for _, user := range users { result = append(result, managedUserPayload(user)) } - writeJSON(w, http.StatusOK, result) + writeProxyJSON(w, http.StatusOK, result) } // ManagedCreateUser proxies admin user creation to AuthGuard's @@ -748,7 +756,7 @@ func (s *Service) ManagedUsers(w http.ResponseWriter, r *http.Request) { // 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()) + writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) return } var input struct { @@ -757,8 +765,8 @@ func (s *Service) ManagedCreateUser(w http.ResponseWriter, r *http.Request) { Password string `json:"password"` Role string `json:"role"` } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") + if err := decodeProxyJSON(r, &input); err != nil { + writeProxyError(w, http.StatusBadRequest, "invalid JSON body") return } managedInput := authclient.ManagedUserInput{Username: input.Username, Email: input.Email, Password: input.Password} @@ -770,7 +778,7 @@ func (s *Service) ManagedCreateUser(w http.ResponseWriter, r *http.Request) { writeAuthGuardError(w, err, "user could not be created") return } - writeJSON(w, http.StatusCreated, managedUserPayload(*created)) + writeProxyJSON(w, http.StatusCreated, managedUserPayload(*created)) } // ManagedUpdateUser proxies admin user update to AuthGuard's @@ -780,11 +788,11 @@ func (s *Service) ManagedCreateUser(w http.ResponseWriter, r *http.Request) { func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseInt(idURLParam(r), 10, 64) if err != nil { - writeError(w, http.StatusBadRequest, "invalid user id") + writeProxyError(w, http.StatusBadRequest, "invalid user id") return } if !s.enabled() { - writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) return } var input struct { @@ -793,8 +801,8 @@ func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) { Password string `json:"password"` Role *string `json:"role"` } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") + if err := decodeProxyJSON(r, &input); err != nil { + writeProxyError(w, http.StatusBadRequest, "invalid JSON body") return } managedInput := authclient.ManagedUserInput{Username: input.Username, Email: input.Email, Password: input.Password, Role: input.Role} @@ -809,11 +817,11 @@ func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) { } for _, user := range users { if user.ID == id { - writeJSON(w, http.StatusOK, managedUserPayload(user)) + writeProxyJSON(w, http.StatusOK, managedUserPayload(user)) return } } - writeError(w, http.StatusNotFound, "user not found") + writeProxyError(w, http.StatusNotFound, "user not found") } // ManagedDeleteUser proxies admin user deletion to AuthGuard's @@ -823,18 +831,18 @@ func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) { func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseInt(idURLParam(r), 10, 64) if err != nil { - writeError(w, http.StatusBadRequest, "invalid user id") + writeProxyError(w, http.StatusBadRequest, "invalid user id") return } if !s.enabled() { - writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + writeProxyError(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}) + writeProxyJSON(w, http.StatusOK, map[string]bool{"ok": true}) } // Signup registers this deployment's first account against AuthGuard's @@ -843,7 +851,7 @@ func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) { func (s *Service) Signup(w http.ResponseWriter, r *http.Request) { if !s.enabled() { user := localProfile - writeJSON(w, http.StatusCreated, map[string]any{"user": &user}) + writeProxyJSON(w, http.StatusCreated, map[string]any{"user": &user}) return } @@ -852,36 +860,36 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) { Username string `json:"username"` Password string `json:"password"` } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") + if err := decodeProxyJSON(r, &input); err != nil { + writeProxyError(w, http.StatusBadRequest, "invalid JSON body") return } - email, err := normalizeEmail(input.Email) + email, err := normalizeProxyEmail(input.Email) if err != nil { - writeError(w, http.StatusBadRequest, err.Error()) + writeProxyError(w, http.StatusBadRequest, err.Error()) return } username := strings.TrimSpace(input.Username) if username == "" { - writeError(w, http.StatusBadRequest, "a username is required") + writeProxyError(w, http.StatusBadRequest, "a username is required") return } - if _, err := normalizeUsername(username); err != nil { - writeError(w, http.StatusBadRequest, err.Error()) + if _, err := normalizeProxyUsername(username); err != nil { + writeProxyError(w, http.StatusBadRequest, err.Error()) return } - if err := validatePassword(input.Password); err != nil { - writeError(w, http.StatusBadRequest, err.Error()) + if err := validateProxyPassword(input.Password); err != nil { + writeProxyError(w, http.StatusBadRequest, err.Error()) return } claimed, err := s.tryClaimSetup(r.Context()) if err != nil { - writeError(w, http.StatusInternalServerError, "internal error") + writeProxyError(w, http.StatusInternalServerError, "internal error") return } if !claimed { - writeError(w, http.StatusConflict, "Setup has already been completed.") + writeProxyError(w, http.StatusConflict, "Setup has already been completed.") return } @@ -892,14 +900,14 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) { // 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") + writeProxyError(w, http.StatusInternalServerError, "internal error") return } if err != nil { - writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } - writeError(w, http.StatusConflict, "Setup has already been completed.") + writeProxyError(w, http.StatusConflict, "Setup has already been completed.") return } @@ -908,7 +916,7 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) { // 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") + writeProxyError(w, http.StatusInternalServerError, "internal error") return } writeAuthGuardError(w, err, "could not create account") @@ -916,13 +924,13 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) { } authclient.ForwardCookies(w, result.Cookies) - writeJSON(w, http.StatusCreated, map[string]any{"user": toUser(result.User)}) + writeProxyJSON(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}) + writeProxyJSON(w, http.StatusOK, map[string]any{"user": &user}) return } @@ -932,8 +940,8 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) { Password string `json:"password"` TOTPToken string `json:"totpToken"` } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") + if err := decodeProxyJSON(r, &input); err != nil { + writeProxyError(w, http.StatusBadRequest, "invalid JSON body") return } identifier := strings.TrimSpace(input.Identifier) @@ -941,7 +949,7 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) { identifier = strings.TrimSpace(input.Email) } if identifier == "" { - writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error()) + writeProxyError(w, http.StatusUnauthorized, ErrInvalidLogin.Error()) return } @@ -950,11 +958,11 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) { 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}) + writeProxyJSON(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()) + writeProxyError(w, http.StatusUnauthorized, ErrInvalidLogin.Error()) return } writeAuthGuardError(w, err, "could not authenticate") @@ -962,17 +970,17 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) { } // A non-APIError here means the call to AuthGuard itself failed // (transport/connectivity); see errAuthGuardUnavailable. - writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } authclient.ForwardCookies(w, result.Cookies) - writeJSON(w, http.StatusOK, map[string]any{"user": toUser(result.User)}) + writeProxyJSON(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}) + writeProxyJSON(w, http.StatusOK, map[string]bool{"ok": true}) return } if token := s.sessionToken(r); token != "" { @@ -980,7 +988,7 @@ func (s *Service) Logout(w http.ResponseWriter, r *http.Request) { if err != nil { var apiErr *authclient.APIError if !errors.As(err, &apiErr) { - writeError(w, http.StatusInternalServerError, "internal error") + writeProxyError(w, http.StatusInternalServerError, "internal error") return } // An already-invalid/expired session is fine to treat as @@ -990,20 +998,20 @@ func (s *Service) Logout(w http.ResponseWriter, r *http.Request) { } } s.clearSessionCookies(w) - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) + writeProxyJSON(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}) + writeProxyJSON(w, http.StatusOK, map[string]any{"enabled": false, "mfaEnabled": false}) return } user := UserFromContext(r.Context()) if user == nil { - writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) return } - writeJSON(w, http.StatusOK, map[string]any{"enabled": user.MFAEnabled, "mfaEnabled": user.MFAEnabled}) + writeProxyJSON(w, http.StatusOK, map[string]any{"enabled": user.MFAEnabled, "mfaEnabled": user.MFAEnabled}) } // TOTPInitiate provisions a pending TOTP secret via AuthGuard's POST @@ -1011,16 +1019,16 @@ func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) { // 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()) + writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) return } user := UserFromContext(r.Context()) if user == nil { - writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) return } if user.MFAEnabled { - writeError(w, http.StatusConflict, "multi-factor authentication is already enabled") + writeProxyError(w, http.StatusConflict, "multi-factor authentication is already enabled") return } result, err := s.authGuard.TOTPEnable(r.Context(), s.sessionToken(r)) @@ -1028,7 +1036,7 @@ func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) { writeAuthGuardError(w, err, "could not create authenticator secret") return } - writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{ + writeProxyJSON(w, http.StatusOK, map[string]any{"data": map[string]any{ "secret": result.Secret, "otpauth": result.OTPAuthURL, "otpauthUrl": result.OTPAuthURL, "enabled": result.Enabled, }}) } @@ -1038,20 +1046,20 @@ func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) { // 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()) + writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) return } user := UserFromContext(r.Context()) if user == nil { - writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + writeProxyError(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") + if err := decodeProxyJSON(r, &input); err != nil { + writeProxyError(w, http.StatusBadRequest, "invalid JSON body") return } token := strings.TrimSpace(input.TOTPToken) @@ -1059,28 +1067,28 @@ func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) { 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.") + writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.") return } - writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": true, "enabled": true, "backupCodes": []string{}}}) + writeProxyJSON(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()) + writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) return } user := UserFromContext(r.Context()) if user == nil { - writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + writeProxyError(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") + if err := decodeProxyJSON(r, &input); err != nil { + writeProxyError(w, http.StatusBadRequest, "invalid JSON body") return } token := strings.TrimSpace(input.TOTPToken) @@ -1088,10 +1096,10 @@ func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) { 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.") + writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.") return } - writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": false, "enabled": false}}) + writeProxyJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": false, "enabled": false}}) } // isSetupClaimed/tryClaimSetup/unclaimSetup back the local one-time setup @@ -1124,7 +1132,11 @@ func (s *Service) unclaimSetup(ctx context.Context) error { // 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. +// 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. type managedAccount struct { ID int64 @@ -1155,22 +1167,22 @@ func managedAccountPayload(user *managedAccount) map[string]any { "id": user.ID, "username": user.Username, "email": user.Email, - "role": normalizeRole(user.Role), + "role": normalizePlatformRole(user.Role), "createdAt": user.CreatedAt, } } -func (s *Service) CreateUser(ctx context.Context, email, username, password, role string) (*User, error) { - email, username, password, err := normalizeCredentials(email, username, password) +func (s *Service) CreateUser(ctx context.Context, email, username, password, role string) (*ProxyUser, error) { + email, username, password, err := normalizeProxyCredentials(email, username, password) if err != nil { return nil, err } - role = normalizeRole(role) + role = normalizePlatformRole(role) hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { return nil, err } - var user User + var user ProxyUser err = s.db.QueryRow(ctx, ` INSERT INTO users (email, username, password_hash, role) VALUES ($1, $2, $3, $4) @@ -1226,7 +1238,7 @@ func (s *Service) DeleteUser(ctx context.Context, id int64) error { 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) + role = normalizePlatformRole(role) } _, err := s.db.Exec(ctx, ` UPDATE users SET email = COALESCE(NULLIF($2, ''), email), username = COALESCE(NULLIF($3, ''), username), @@ -1236,7 +1248,7 @@ func (s *Service) UpdateUser(ctx context.Context, id int64, email, username, rol } func (s *Service) SetPassword(ctx context.Context, id int64, password string) error { - if err := validatePassword(password); err != nil { + if err := validateProxyPassword(password); err != nil { return err } hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) @@ -1256,57 +1268,61 @@ func (s *Service) SetPassword(ctx context.Context, id int64, password string) er // to a generic 500 with fallbackMessage. func writeAuthGuardError(w http.ResponseWriter, err error, fallbackMessage string) { if statusCode, message, ok := authproxy.APIErrorResponse(err); ok { - writeError(w, statusCode, message) + writeProxyError(w, statusCode, message) return } - writeError(w, http.StatusInternalServerError, fallbackMessage) + writeProxyError(w, http.StatusInternalServerError, fallbackMessage) } -func normalizeUsername(value string) (string, error) { +func normalizeProxyUsername(value string) (string, error) { value = strings.TrimSpace(value) if value == "" { return "", nil } - if len([]rune(value)) > maxUsernameLength { + if len([]rune(value)) > proxyMaxUsernameLength { return "", errors.New("username is too long") } return value, nil } -func normalizeEmail(value string) (string, error) { +func normalizeProxyEmail(value string) (string, error) { value = strings.ToLower(strings.TrimSpace(value)) - if !strings.Contains(value, "@") || len(value) > maxEmailLength { + if !strings.Contains(value, "@") || len(value) > proxyMaxEmailLength { return "", errors.New("a valid email is required") } return value, nil } -func validatePassword(password string) error { - if len([]rune(password)) < minPasswordLength || len([]rune(password)) > 1024 { +func validateProxyPassword(password string) error { + if len([]rune(password)) < proxyMinPasswordLength || len([]rune(password)) > 1024 { return errors.New("Password must be at least 8 characters.") } return nil } -// normalizeCredentials validates email/password format (username is +// normalizeProxyCredentials validates email/password format (username is // optional here - Signup separately requires it be non-empty; kept this way // to preserve this package's existing test coverage/contract). -func normalizeCredentials(email, username, password string) (string, string, string, error) { - email, err := normalizeEmail(email) +func normalizeProxyCredentials(email, username, password string) (string, string, string, error) { + email, err := normalizeProxyEmail(email) if err != nil { return "", "", "", err } - username, err = normalizeUsername(username) + username, err = normalizeProxyUsername(username) if err != nil { return "", "", "", err } - if err := validatePassword(password); err != nil { + if err := validateProxyPassword(password); err != nil { return "", "", "", err } return email, username, password, nil } -func normalizeRole(role string) string { +// 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 { switch strings.ToLower(strings.TrimSpace(role)) { case "admin", "superadmin", "moderator": return strings.ToLower(strings.TrimSpace(role)) @@ -1327,20 +1343,20 @@ func idURLParam(r *http.Request) string { return r.PathValue("id") } -func decodeJSON(r *http.Request, target any) error { +func decodeProxyJSON(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) { +func writeProxyJSON(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 writeProxyError(w http.ResponseWriter, status int, message string) { + writeProxyJSON(w, status, map[string]string{"error": message, "message": message}) } -func (u User) String() string { return strconv.FormatInt(u.ID, 10) } +func (u ProxyUser) String() string { return strconv.FormatInt(u.ID, 10) } diff --git a/shared/backend/auth/proxy_test.go b/shared/backend/auth/proxy_test.go new file mode 100644 index 0000000..b7042c7 --- /dev/null +++ b/shared/backend/auth/proxy_test.go @@ -0,0 +1,28 @@ +package auth + +import "testing" + +func TestNormalizeProxyCredentials(t *testing.T) { + email, username, password, err := normalizeProxyCredentials(" User@Example.com ", "user", "correct horse battery staple") + if err != nil { + t.Fatal(err) + } + if email != "user@example.com" || username != "user" || password == "" { + t.Fatalf("normalized credentials = %q, %q, %q", email, username, password) + } +} + +func TestNormalizeProxyCredentialsAllowsAdminEmailOnly(t *testing.T) { + if _, _, _, err := normalizeProxyCredentials("admin@example.com", "", "correct horse battery staple"); err != nil { + t.Fatalf("empty optional username rejected: %v", err) + } +} + +func TestNormalizePlatformRole(t *testing.T) { + if normalizePlatformRole("MODERATOR") != "moderator" { + t.Fatal("moderator role was not normalized") + } + if normalizePlatformRole("unknown") != "user" { + t.Fatal("unknown role was not reduced to user") + } +} diff --git a/shared/backend/mediaauth/auth_test.go b/shared/backend/mediaauth/auth_test.go deleted file mode 100644 index 2c7c273..0000000 --- a/shared/backend/mediaauth/auth_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package mediaauth - -import "testing" - -func TestNormalizeCredentials(t *testing.T) { - email, username, password, err := normalizeCredentials(" User@Example.com ", "user", "correct horse battery staple") - if err != nil { - t.Fatal(err) - } - if email != "user@example.com" || username != "user" || password == "" { - t.Fatalf("normalized credentials = %q, %q, %q", email, username, password) - } -} - -func TestNormalizeCredentialsAllowsAdminEmailOnly(t *testing.T) { - if _, _, _, err := normalizeCredentials("admin@example.com", "", "correct horse battery staple"); err != nil { - t.Fatalf("empty optional username rejected: %v", err) - } -} - -func TestNormalizeRole(t *testing.T) { - if normalizeRole("MODERATOR") != "moderator" { - t.Fatal("moderator role was not normalized") - } - if normalizeRole("unknown") != "user" { - t.Fatal("unknown role was not reduced to user") - } -} diff --git a/shared/backend/mediacore/mediacore.go b/shared/backend/mediacore/mediacore.go index 2bbb8f7..535f800 100644 --- a/shared/backend/mediacore/mediacore.go +++ b/shared/backend/mediacore/mediacore.go @@ -45,15 +45,15 @@ import ( "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgxpool" + sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" "repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient" - "repos.gfranz.ch/Gabriel20xx/shared/backend/mediaauth" "repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket" ) // Config wires a Core to the rest of one service's dependencies. type Config struct { DB *pgxpool.Pool - Auth *mediaauth.Service + Auth *sharedauth.Service Sync *syncsocket.Hub CarrierNode *carriernodeclient.Client // ServiceName is recorded on mutations that track which app produced @@ -65,7 +65,7 @@ type Config struct { // what they need to run. type Core struct { db *pgxpool.Pool - auth *mediaauth.Service + auth *sharedauth.Service sync *syncsocket.Hub carrierNode *carriernodeclient.Client serviceName string @@ -214,7 +214,7 @@ func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "missing mediaKey") return } - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) var likes, saves, views int64 if err := c.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE media_key = $1 AND stat_type = 'like'`, key).Scan(&likes); err != nil { writeError(w, http.StatusInternalServerError, "media state unavailable") @@ -240,7 +240,7 @@ func (c *Core) mediaSave(w http.ResponseWriter, r *http.Request) { } func (c *Core) mediaStatMutation(w http.ResponseWriter, r *http.Request, statType string) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) if user == nil { writeError(w, http.StatusUnauthorized, "not authenticated") return @@ -283,7 +283,7 @@ func (c *Core) mediaStatMutation(w http.ResponseWriter, r *http.Request, statTyp } func (c *Core) mediaView(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) var input struct { MediaKey string `json:"mediaKey"` } @@ -307,7 +307,7 @@ func (c *Core) mediaView(w http.ResponseWriter, r *http.Request) { } func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) var input struct { MediaKey string `json:"mediaKey"` DurationMs int64 `json:"durationMs"` @@ -338,7 +338,7 @@ func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) { } func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) rows, err := c.db.Query(r.Context(), `SELECT media_key, created_at FROM media_stats WHERE user_id = $1 AND stat_type = 'like' ORDER BY created_at DESC`, user.ID) if err != nil { writeError(w, http.StatusInternalServerError, "liked media unavailable") @@ -379,7 +379,7 @@ func (c *Core) mediaTags(w http.ResponseWriter, r *http.Request) { } func (c *Core) addMediaTag(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) var input struct { Tag string `json:"tag"` } @@ -402,7 +402,7 @@ func (c *Core) addMediaTag(w http.ResponseWriter, r *http.Request) { } func (c *Core) voteMediaTag(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) var input struct { Vote int `json:"vote"` } @@ -468,7 +468,7 @@ func (c *Core) tagMedia(w http.ResponseWriter, r *http.Request) { } func (c *Core) playlists(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) rows, err := c.db.Query(r.Context(), `SELECT id, name, created_at FROM playlists WHERE user_id=$1 ORDER BY created_at DESC`, user.ID) if err != nil { writeError(w, http.StatusInternalServerError, "playlists unavailable") @@ -488,7 +488,7 @@ func (c *Core) playlists(w http.ResponseWriter, r *http.Request) { } func (c *Core) playlistSummary(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) if user == nil { writeJSON(w, http.StatusOK, success(map[string]any{"playlists": []any{}}, "No playlists")) return @@ -512,7 +512,7 @@ func (c *Core) playlistSummary(w http.ResponseWriter, r *http.Request) { } func (c *Core) playlist(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil || user == nil { writeError(w, http.StatusNotFound, "playlist not found") @@ -528,7 +528,7 @@ func (c *Core) playlist(w http.ResponseWriter, r *http.Request) { } func (c *Core) createPlaylist(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) var input struct { Name string `json:"name"` } @@ -552,7 +552,7 @@ func (c *Core) createPlaylist(w http.ResponseWriter, r *http.Request) { } func (c *Core) deletePlaylist(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { writeError(w, http.StatusBadRequest, "invalid playlist id") @@ -567,7 +567,7 @@ func (c *Core) deletePlaylist(w http.ResponseWriter, r *http.Request) { } func (c *Core) playlistItems(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil || user == nil { writeError(w, http.StatusNotFound, "playlist not found") @@ -598,7 +598,7 @@ func (c *Core) playlistItems(w http.ResponseWriter, r *http.Request) { } func (c *Core) addPlaylistItem(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { writeError(w, http.StatusBadRequest, "invalid playlist id") @@ -631,7 +631,7 @@ func (c *Core) addPlaylistItem(w http.ResponseWriter, r *http.Request) { } func (c *Core) deletePlaylistItem(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { writeError(w, http.StatusBadRequest, "invalid playlist id") @@ -655,7 +655,7 @@ func (c *Core) deletePlaylistItem(w http.ResponseWriter, r *http.Request) { } func (c *Core) randomPlaylistItem(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) if user == nil { writeError(w, http.StatusNotFound, "playlist not found") return @@ -674,7 +674,7 @@ func (c *Core) randomPlaylistItem(w http.ResponseWriter, r *http.Request) { } func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { writeError(w, http.StatusBadRequest, "invalid playlist id") @@ -699,7 +699,7 @@ func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) { } func (c *Core) profile(w http.ResponseWriter, r *http.Request) { - user := mediaauth.UserFromContext(r.Context()) + user := sharedauth.UserFromContext(r.Context()) if user == nil { writeJSON(w, http.StatusOK, map[string]any{"user": nil}) return