Add per-user project-access restriction; generalize mediaauth into a unified auth proxy
shared/backend/auth: adds SchemaOptions.ProjectScoping and Store methods
(SetUserProjects/UserProjects/UserProjectsByUser/IsProjectAllowed,
SetKnownProjects/KnownProjects) backing AuthGuard's new per-user
project-access restriction.
shared/backend/authclient: Client can now identify its calling project to
AuthServer via WithProjectKey (sent as X-Project-Key on every request), so
AuthServer can enforce the restriction above per project.
shared/backend/mediaauth: generalized from a media-family-only package
into the one shared auth-proxy engine every AuthGuard-integrated project
should use. New accepts a projectKey; the login-required/setup-claim
storage it needs is now expressed as a small Store interface
(NewWithStore lets any project's own storage satisfy it, not just the
media family's shared `settings` table, which pgSettingsStore still backs
for existing callers). ManagedUpdateUser/ManagedDeleteUser now resolve
their {id} path param via chi.URLParam OR the stdlib 1.22+ ServeMux's
PathValue, so non-chi consumers work unchanged.
packages/web-ui: UserManagement gains an optional `projects` prop (a
per-account project-access picker), used only by AuthGuard's own admin UI.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6ac2fcefeb
commit
663d498a03
7 files changed
+476
-51
No files matched your search
@@ -7,6 +7,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
@@ -46,6 +47,11 @@ type SchemaOptions struct {
|
||||
SingleUser bool
|
||||
// APITokens creates the optional per-user API token table.
|
||||
APITokens bool
|
||||
// ProjectScoping creates auth_known_projects/auth_user_projects, backing per-user
|
||||
// project-access restriction (see Store.SetUserProjects/IsProjectAllowed). Only AuthGuard
|
||||
// itself needs this - every other project only ever calls AuthGuard's own API, never these
|
||||
// tables directly.
|
||||
ProjectScoping bool
|
||||
}
|
||||
|
||||
// DefaultSchemaOptions returns the single-account schema used by most small
|
||||
@@ -113,6 +119,24 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
|
||||
return fmt.Errorf("remove single-user auth constraint: %w", err)
|
||||
}
|
||||
|
||||
if options.ProjectScoping {
|
||||
if _, err := pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS auth_known_projects (
|
||||
project TEXT PRIMARY KEY,
|
||||
label TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS auth_user_projects (
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
project TEXT NOT NULL,
|
||||
PRIMARY KEY (user_id, project)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS auth_user_projects_project_idx ON auth_user_projects (project);
|
||||
`); err != nil {
|
||||
return fmt.Errorf("ensure project-scoping schema: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if options.APITokens {
|
||||
if _, err := pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS auth_api_tokens (
|
||||
@@ -433,6 +457,174 @@ func (s *Store) DeleteExpiredSessions(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// KnownProject is one project ProjectConfigurator has registered, pushed to AuthGuard so its
|
||||
// admin UI can offer real, live project keys instead of free-form text - see SetKnownProjects.
|
||||
type KnownProject struct {
|
||||
Key string
|
||||
Label string
|
||||
}
|
||||
|
||||
// SetKnownProjects replaces the full set of known projects (pushed by ProjectConfigurator's
|
||||
// PUT /api/projects/internal whenever its registered-project list changes). A project no longer
|
||||
// registered is dropped, so the admin UI never offers a stale key; existing auth_user_projects
|
||||
// rows for a removed project are left alone (harmless - IsProjectAllowed only ever compares
|
||||
// against a user's own rows, never against auth_known_projects).
|
||||
func (s *Store) SetKnownProjects(ctx context.Context, projects []KnownProject) error {
|
||||
if err := s.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("set known projects: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM auth_known_projects`); err != nil {
|
||||
return fmt.Errorf("set known projects: %w", err)
|
||||
}
|
||||
for _, project := range projects {
|
||||
key := strings.ToLower(strings.TrimSpace(project.Key))
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO auth_known_projects (project, label, updated_at) VALUES ($1, $2, now())
|
||||
ON CONFLICT (project) DO UPDATE SET label = EXCLUDED.label, updated_at = now()
|
||||
`, key, strings.TrimSpace(project.Label)); err != nil {
|
||||
return fmt.Errorf("set known projects: %w", err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("set known projects: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// KnownProjects returns every registered project, ordered by key.
|
||||
func (s *Store) KnownProjects(ctx context.Context) ([]KnownProject, error) {
|
||||
if err := s.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `SELECT project, label FROM auth_known_projects ORDER BY project`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list known projects: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
projects := make([]KnownProject, 0)
|
||||
for rows.Next() {
|
||||
var project KnownProject
|
||||
if err := rows.Scan(&project.Key, &project.Label); err != nil {
|
||||
return nil, fmt.Errorf("scan known project: %w", err)
|
||||
}
|
||||
projects = append(projects, project)
|
||||
}
|
||||
return projects, rows.Err()
|
||||
}
|
||||
|
||||
// SetUserProjects replaces the full set of projects userID is restricted to. An empty projects
|
||||
// list means unrestricted (see IsProjectAllowed) - the default for every account until an
|
||||
// administrator explicitly scopes it, so this feature is opt-in and never breaks an existing
|
||||
// deployment's accounts on upgrade.
|
||||
func (s *Store) SetUserProjects(ctx context.Context, userID int64, projects []string) error {
|
||||
if err := s.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("set user projects: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM auth_user_projects WHERE user_id = $1`, userID); err != nil {
|
||||
return fmt.Errorf("set user projects: %w", err)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, project := range projects {
|
||||
key := strings.ToLower(strings.TrimSpace(project))
|
||||
if key == "" || seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO auth_user_projects (user_id, project) VALUES ($1, $2)`, userID, key); err != nil {
|
||||
return fmt.Errorf("set user projects: %w", err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("set user projects: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UserProjects returns the projects userID is restricted to, or an empty slice when unrestricted.
|
||||
func (s *Store) UserProjects(ctx context.Context, userID int64) ([]string, error) {
|
||||
if err := s.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `SELECT project FROM auth_user_projects WHERE user_id = $1 ORDER BY project`, userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list user projects: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
projects := make([]string, 0)
|
||||
for rows.Next() {
|
||||
var project string
|
||||
if err := rows.Scan(&project); err != nil {
|
||||
return nil, fmt.Errorf("scan user project: %w", err)
|
||||
}
|
||||
projects = append(projects, project)
|
||||
}
|
||||
return projects, rows.Err()
|
||||
}
|
||||
|
||||
// UserProjectsByUser bulk-loads every user's project restrictions in one query, for the admin
|
||||
// user list screen (avoids one query per row).
|
||||
func (s *Store) UserProjectsByUser(ctx context.Context) (map[int64][]string, error) {
|
||||
if err := s.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `SELECT user_id, project FROM auth_user_projects ORDER BY user_id, project`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list user projects: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
result := map[int64][]string{}
|
||||
for rows.Next() {
|
||||
var userID int64
|
||||
var project string
|
||||
if err := rows.Scan(&userID, &project); err != nil {
|
||||
return nil, fmt.Errorf("scan user project: %w", err)
|
||||
}
|
||||
result[userID] = append(result[userID], project)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
// IsProjectAllowed reports whether userID may authenticate against project: true when the
|
||||
// account has no project restrictions at all (the default for every account), or when project is
|
||||
// one of its assigned projects. An empty project (a caller that sent no project-key header - a
|
||||
// service not yet migrated to identify itself, or a browser request straight to AuthGuard's own
|
||||
// web UI, which is not itself a "project" another service authenticates against) is always
|
||||
// allowed; restriction only ever applies once a caller actually identifies itself.
|
||||
func (s *Store) IsProjectAllowed(ctx context.Context, userID int64, project string) (bool, error) {
|
||||
project = strings.ToLower(strings.TrimSpace(project))
|
||||
if project == "" {
|
||||
return true, nil
|
||||
}
|
||||
if err := s.validate(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
var total int
|
||||
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM auth_user_projects WHERE user_id = $1`, userID).Scan(&total); err != nil {
|
||||
return false, fmt.Errorf("count user projects: %w", err)
|
||||
}
|
||||
if total == 0 {
|
||||
return true, nil
|
||||
}
|
||||
var allowed bool
|
||||
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM auth_user_projects WHERE user_id = $1 AND project = $2)`, userID, project).Scan(&allowed); err != nil {
|
||||
return false, fmt.Errorf("check user project: %w", err)
|
||||
}
|
||||
return allowed, nil
|
||||
}
|
||||
|
||||
var ErrUserExists = errors.New("auth user already exists")
|
||||
|
||||
func (s *Store) validate() error {
|
||||
|
||||
@@ -63,8 +63,20 @@ type Client struct {
|
||||
// when Middleware has no Authorization header to use. Defaults to
|
||||
// "auth_session", matching AuthServer's SessionCookieName.
|
||||
cookieName string
|
||||
// projectKey identifies the calling project to AuthServer (sent as the
|
||||
// ProjectKeyHeader on every request) so per-user project-access
|
||||
// restrictions can be enforced. Empty means "don't identify" - the
|
||||
// caller is treated as unrestricted; see AuthServer's project-scoping
|
||||
// feature and WithProjectKey.
|
||||
projectKey string
|
||||
}
|
||||
|
||||
// ProjectKeyHeader is the header Client attaches to every request identifying
|
||||
// which project is calling, so AuthServer can enforce per-user project-access
|
||||
// restriction (see WithProjectKey). AuthServer treats a missing/empty header
|
||||
// the same as "this caller has no project identity": never restricted.
|
||||
const ProjectKeyHeader = "X-Project-Key"
|
||||
|
||||
// Option configures optional Client behavior.
|
||||
type Option func(*Client)
|
||||
|
||||
@@ -81,6 +93,16 @@ func WithCookieName(name string) Option {
|
||||
return func(c *Client) { c.cookieName = name }
|
||||
}
|
||||
|
||||
// WithProjectKey identifies this Client's project to AuthServer (see
|
||||
// ProjectKeyHeader), enabling per-user project-access restriction. key is
|
||||
// normally a project's own lowercase identifier, matching the same key
|
||||
// ProjectConfigurator's Projects workspace registers it under (e.g.
|
||||
// "carriernode", "gamestream", "omnilogger") - see AuthServer's project-scope
|
||||
// admin UI, which assigns users access using these same keys.
|
||||
func WithProjectKey(key string) Option {
|
||||
return func(c *Client) { c.projectKey = strings.ToLower(strings.TrimSpace(key)) }
|
||||
}
|
||||
|
||||
// New creates a Client for the AuthServer instance at baseURL. baseURL may
|
||||
// be given without a scheme (e.g. "auth.example.com" or "192.168.1.50:8080")
|
||||
// - the scheme is then inferred from the host: a loopback, RFC1918/RFC4193
|
||||
@@ -124,6 +146,15 @@ func (c *Client) getBaseURL() string {
|
||||
return c.baseURL
|
||||
}
|
||||
|
||||
// setProjectKeyHeader attaches ProjectKeyHeader when this Client was built
|
||||
// with WithProjectKey; a no-op otherwise, so an unconfigured Client behaves
|
||||
// exactly as it did before project scoping existed.
|
||||
func (c *Client) setProjectKeyHeader(req *http.Request) {
|
||||
if c.projectKey != "" {
|
||||
req.Header.Set(ProjectKeyHeader, c.projectKey)
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeBaseURL(baseURL string) string {
|
||||
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
||||
if trimmed == "" {
|
||||
@@ -186,6 +217,7 @@ func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
|
||||
return nil, fmt.Errorf("authclient: build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
c.setProjectKeyHeader(req)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
@@ -418,6 +450,7 @@ func (c *Client) call(ctx context.Context, method, path, token string, body, out
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
c.setProjectKeyHeader(req)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
|
||||
+153
-50
@@ -5,6 +5,29 @@
|
||||
// MediaViewer, ContentScanner, CraftStudio) use one copy instead of
|
||||
// duplicating it.
|
||||
//
|
||||
// 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).
|
||||
//
|
||||
// AuthGuard migration
|
||||
// ====================
|
||||
// This service used to be a fully self-contained auth implementation:
|
||||
@@ -190,8 +213,33 @@ const (
|
||||
// underlying admin endpoints have nothing to manage.
|
||||
var localProfile = User{ID: 0, Username: "local", Email: "", Role: string(sharedauth.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
|
||||
// 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
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
// 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.
|
||||
db *pgxpool.Pool
|
||||
store Store
|
||||
cookieName string
|
||||
secureCookies bool
|
||||
// authGuard is nil when AUTHGUARD_URL is unset; see the top-of-file doc
|
||||
@@ -199,18 +247,96 @@ type Service struct {
|
||||
authGuard *authclient.Client
|
||||
}
|
||||
|
||||
// New constructs a Service. cookieName/secureCookies are retained only for
|
||||
// clearing the pre-migration session cookie on logout (see the package doc
|
||||
// comment's "Session cookie / token model" section) - the live session
|
||||
// cookie this service actually reads/sets is always AuthGuard's own
|
||||
// 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
|
||||
// authclient.DefaultCookieName. authGuardURL is AUTHGUARD_URL; empty means
|
||||
// auth-disabled mode.
|
||||
func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL string) *Service {
|
||||
// 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 {
|
||||
var client *authclient.Client
|
||||
if strings.TrimSpace(authGuardURL) != "" {
|
||||
client = authclient.New(authGuardURL)
|
||||
client = authclient.New(authGuardURL, authclient.WithProjectKey(projectKey))
|
||||
}
|
||||
return &Service{db: db, cookieName: cookieName, secureCookies: secureCookies, authGuard: client}
|
||||
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
|
||||
}
|
||||
|
||||
// enabled reports whether AUTHGUARD_URL was configured. See the top-of-file
|
||||
@@ -497,21 +623,7 @@ func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (s *Service) LoginRequired(ctx context.Context) (bool, error) {
|
||||
var value string
|
||||
err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key = $1`, loginRequiredSettingKey).Scan(&value)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
|
||||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||
case "false", "0", "no", "off":
|
||||
return false, nil
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
return s.store.LoginRequired(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -544,12 +656,7 @@ func (s *Service) UpdateAccessSettings(w http.ResponseWriter, r *http.Request) {
|
||||
// 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 {
|
||||
_, 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
|
||||
return s.store.SetLoginRequired(ctx, required)
|
||||
}
|
||||
|
||||
func (s *Service) Status(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -655,7 +762,7 @@ func (s *Service) ManagedCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
// enforces authorization (including the "the superadmin account is
|
||||
// protected" rule) itself.
|
||||
func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
id, err := strconv.ParseInt(idURLParam(r), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid user id")
|
||||
return
|
||||
@@ -698,7 +805,7 @@ func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) {
|
||||
// enforces authorization (including "this user cannot be deleted" rules)
|
||||
// itself.
|
||||
func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
id, err := strconv.ParseInt(idURLParam(r), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid user id")
|
||||
return
|
||||
@@ -976,31 +1083,15 @@ func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) {
|
||||
// the pre-existing `settings` key/value table (same mechanism as
|
||||
// LoginRequired's `auth_required` key) rather than a new table.
|
||||
func (s *Service) isSetupClaimed(ctx context.Context) (bool, error) {
|
||||
var value string
|
||||
err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key = $1`, setupClaimedSettingKey).Scan(&value)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return value == "true", nil
|
||||
return s.store.IsSetupClaimed(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) tryClaimSetup(ctx context.Context) (bool, error) {
|
||||
tag, err := s.db.Exec(ctx, `
|
||||
INSERT INTO settings (key, value, updated_at) VALUES ($1, 'true', NOW())
|
||||
ON CONFLICT (key) DO NOTHING
|
||||
`, setupClaimedSettingKey)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return tag.RowsAffected() > 0, nil
|
||||
return s.store.TryClaimSetup(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) unclaimSetup(ctx context.Context) error {
|
||||
_, err := s.db.Exec(ctx, `DELETE FROM settings WHERE key = $1`, setupClaimedSettingKey)
|
||||
return err
|
||||
return s.store.UnclaimSetup(ctx)
|
||||
}
|
||||
|
||||
// --- Moderatable platform users (unrelated to admin login identity) --------
|
||||
@@ -1208,6 +1299,18 @@ func normalizeRole(role string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, target any) error {
|
||||
defer r.Body.Close()
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024))
|
||||
|
||||
Reference in new issue
Block a user