Sync shared snapshot from 663d498
Docker / Docker Build & Push (push) Successful in 3m0s

This commit is contained in:
Gabriel20xx committed 2026-09-13 12:18:24 +02:00
1 parent 1d99f0272d
commit b1412a9016
7 files changed
+476 -51

No files matched your search

+192
View File
@@ -7,6 +7,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"strings"
"time" "time"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
@@ -46,6 +47,11 @@ type SchemaOptions struct {
SingleUser bool SingleUser bool
// APITokens creates the optional per-user API token table. // APITokens creates the optional per-user API token table.
APITokens bool 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 // 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) 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 options.APITokens {
if _, err := pool.Exec(ctx, ` if _, err := pool.Exec(ctx, `
CREATE TABLE IF NOT EXISTS auth_api_tokens ( CREATE TABLE IF NOT EXISTS auth_api_tokens (
@@ -433,6 +457,174 @@ func (s *Store) DeleteExpiredSessions(ctx context.Context) error {
return nil 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") var ErrUserExists = errors.New("auth user already exists")
func (s *Store) validate() error { func (s *Store) validate() error {
+33
View File
@@ -63,8 +63,20 @@ type Client struct {
// when Middleware has no Authorization header to use. Defaults to // when Middleware has no Authorization header to use. Defaults to
// "auth_session", matching AuthServer's SessionCookieName. // "auth_session", matching AuthServer's SessionCookieName.
cookieName string 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. // Option configures optional Client behavior.
type Option func(*Client) type Option func(*Client)
@@ -81,6 +93,16 @@ func WithCookieName(name string) Option {
return func(c *Client) { c.cookieName = name } 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 // 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") // 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 // - the scheme is then inferred from the host: a loopback, RFC1918/RFC4193
@@ -124,6 +146,15 @@ func (c *Client) getBaseURL() string {
return c.baseURL 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 { func normalizeBaseURL(baseURL string) string {
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/") trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if trimmed == "" { 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) return nil, fmt.Errorf("authclient: build request: %w", err)
} }
req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Authorization", "Bearer "+token)
c.setProjectKeyHeader(req)
resp, err := c.httpClient.Do(req) resp, err := c.httpClient.Do(req)
if err != nil { if err != nil {
@@ -418,6 +450,7 @@ func (c *Client) call(ctx context.Context, method, path, token string, body, out
if token != "" { if token != "" {
req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Authorization", "Bearer "+token)
} }
c.setProjectKeyHeader(req)
resp, err := c.httpClient.Do(req) resp, err := c.httpClient.Do(req)
if err != nil { if err != nil {
+153 -50
View File
@@ -5,6 +5,29 @@
// MediaViewer, ContentScanner, CraftStudio) use one copy instead of // MediaViewer, ContentScanner, CraftStudio) use one copy instead of
// duplicating it. // 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 // AuthGuard migration
// ==================== // ====================
// This service used to be a fully self-contained auth implementation: // This service used to be a fully self-contained auth implementation:
@@ -190,8 +213,33 @@ const (
// underlying admin endpoints have nothing to manage. // underlying admin endpoints have nothing to manage.
var localProfile = User{ID: 0, Username: "local", Email: "", Role: string(sharedauth.RoleSuperAdmin), CanManageUsers: true} 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 { 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 db *pgxpool.Pool
store Store
cookieName string cookieName string
secureCookies bool secureCookies bool
// authGuard is nil when AUTHGUARD_URL is unset; see the top-of-file doc // authGuard is nil when AUTHGUARD_URL is unset; see the top-of-file doc
@@ -199,18 +247,96 @@ type Service struct {
authGuard *authclient.Client authGuard *authclient.Client
} }
// New constructs a Service. cookieName/secureCookies are retained only for // New constructs a Service backed by the media family's shared `settings`
// clearing the pre-migration session cookie on logout (see the package doc // table (pgSettingsStore) for the login-required toggle and setup-claim
// comment's "Session cookie / token model" section) - the live session // flag, and by db directly for the unrelated "moderatable platform users"
// cookie this service actually reads/sets is always AuthGuard's own // 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 // authclient.DefaultCookieName. authGuardURL is AUTHGUARD_URL; empty means
// auth-disabled mode. // auth-disabled mode. projectKey identifies this project to AuthGuard for
func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL string) *Service { // 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 var client *authclient.Client
if strings.TrimSpace(authGuardURL) != "" { 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 // 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) { func (s *Service) LoginRequired(ctx context.Context) (bool, error) {
var value string return s.store.LoginRequired(ctx)
err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key = $1`, loginRequiredSettingKey).Scan(&value)
if errors.Is(err, pgx.ErrNoRows) {
return true, nil
}
if err != nil {
return true, err
}
switch strings.ToLower(strings.TrimSpace(value)) {
case "false", "0", "no", "off":
return false, nil
default:
return true, nil
}
} }
func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) { 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 // central "Require Login" toggle (ConfigWorkspace.svelte's loginControls) apply here without an
// admin session of its own. // admin session of its own.
func (s *Service) SetLoginRequired(ctx context.Context, required bool) error { func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
_, err := s.db.Exec(ctx, ` return s.store.SetLoginRequired(ctx, required)
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 *Service) Status(w http.ResponseWriter, r *http.Request) { 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 // enforces authorization (including the "the superadmin account is
// protected" rule) itself. // protected" rule) itself.
func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) { 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 { if err != nil {
writeError(w, http.StatusBadRequest, "invalid user id") writeError(w, http.StatusBadRequest, "invalid user id")
return return
@@ -698,7 +805,7 @@ func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) {
// enforces authorization (including "this user cannot be deleted" rules) // enforces authorization (including "this user cannot be deleted" rules)
// itself. // itself.
func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) { 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 { if err != nil {
writeError(w, http.StatusBadRequest, "invalid user id") writeError(w, http.StatusBadRequest, "invalid user id")
return 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 // the pre-existing `settings` key/value table (same mechanism as
// LoginRequired's `auth_required` key) rather than a new table. // LoginRequired's `auth_required` key) rather than a new table.
func (s *Service) isSetupClaimed(ctx context.Context) (bool, error) { func (s *Service) isSetupClaimed(ctx context.Context) (bool, error) {
var value string return s.store.IsSetupClaimed(ctx)
err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key = $1`, setupClaimedSettingKey).Scan(&value)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, err
}
return value == "true", nil
} }
func (s *Service) tryClaimSetup(ctx context.Context) (bool, error) { func (s *Service) tryClaimSetup(ctx context.Context) (bool, error) {
tag, err := s.db.Exec(ctx, ` return s.store.TryClaimSetup(ctx)
INSERT INTO settings (key, value, updated_at) VALUES ($1, 'true', NOW())
ON CONFLICT (key) DO NOTHING
`, setupClaimedSettingKey)
if err != nil {
return false, err
}
return tag.RowsAffected() > 0, nil
} }
func (s *Service) unclaimSetup(ctx context.Context) error { func (s *Service) unclaimSetup(ctx context.Context) error {
_, err := s.db.Exec(ctx, `DELETE FROM settings WHERE key = $1`, setupClaimedSettingKey) return s.store.UnclaimSetup(ctx)
return err
} }
// --- Moderatable platform users (unrelated to admin login identity) -------- // --- 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 { func decodeJSON(r *http.Request, target any) error {
defer r.Body.Close() defer r.Body.Close()
decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024)) decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024))
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import type { import type {
KnownProject,
ManagedUser, ManagedUser,
UserCreateInput, UserCreateInput,
UserCreateRequest, UserCreateRequest,
@@ -19,7 +20,8 @@
onCreate, onCreate,
onDelete, onDelete,
onList, onList,
onUpdate onUpdate,
projects
}: { }: {
currentRole?: UserRole; currentRole?: UserRole;
currentUserId?: UserId; currentUserId?: UserId;
@@ -27,6 +29,15 @@
onDelete?: UserDeleteRequest; onDelete?: UserDeleteRequest;
onList?: UserListRequest; onList?: UserListRequest;
onUpdate?: UserUpdateRequest; onUpdate?: UserUpdateRequest;
/**
* Every project an account can be restricted to logging into
* (AuthGuard's project-scope feature). Only AuthGuard's own admin UI
* passes this - every other project's UserManagement usage (proxying to
* AuthGuard's admin/users endpoints without knowing about registered
* projects) omits it, and the whole project-access section of this
* component simply doesn't render.
*/
projects?: KnownProject[];
} = $props(); } = $props();
let users = $state<ManagedUser[]>([]); let users = $state<ManagedUser[]>([]);
@@ -102,10 +113,25 @@
function startEditing(user: ManagedUser): void { function startEditing(user: ManagedUser): void {
editingId = user.id; editingId = user.id;
editUser = { username: user.username, email: user.email, role: roleForForm(user.role) }; editUser = { username: user.username, email: user.email, role: roleForForm(user.role) };
if (projects && projects.length > 0) editUser.projects = [...(user.projects ?? [])];
error = ''; error = '';
notice = ''; notice = '';
} }
function toggleEditProject(key: string, checked: boolean): void {
const current = editUser.projects ?? [];
editUser.projects = checked ? [...current, key] : current.filter((project) => project !== key);
}
function projectLabel(key: string): string {
return projects?.find((project) => project.key === key)?.label ?? key;
}
function projectSummary(user: ManagedUser): string {
if (!user.projects || user.projects.length === 0) return 'All projects';
return user.projects.map(projectLabel).join(', ');
}
function stopEditing(): void { function stopEditing(): void {
editingId = null; editingId = null;
editUser = {}; editUser = {};
@@ -195,6 +221,21 @@
{#if canAssignAdmin}<option value="admin">Admin</option>{/if} {#if canAssignAdmin}<option value="admin">Admin</option>{/if}
{#if user.role === 'superadmin'}<option value="superadmin">Superadmin</option>{/if} {#if user.role === 'superadmin'}<option value="superadmin">Superadmin</option>{/if}
</select> </select>
{#if projects && projects.length > 0}
<fieldset class="sc-user-projects">
<legend>Projects (none checked = all projects)</legend>
{#each projects as project (project.key)}
<label class="sc-user-project-option">
<input
type="checkbox"
checked={(editUser.projects ?? []).includes(project.key)}
onchange={(event) => toggleEditProject(project.key, event.currentTarget.checked)}
/>
{project.label}
</label>
{/each}
</fieldset>
{/if}
<div class="sc-user-actions"><Button disabled={saving} size="sm" type="submit">Save</Button><Button disabled={saving} size="sm" type="button" variant="secondary" onclick={stopEditing}>Cancel</Button></div> <div class="sc-user-actions"><Button disabled={saving} size="sm" type="submit">Save</Button><Button disabled={saving} size="sm" type="button" variant="secondary" onclick={stopEditing}>Cancel</Button></div>
</form> </form>
{:else} {:else}
@@ -202,6 +243,9 @@
<div><strong>{user.username}</strong><span>{user.email}</span></div> <div><strong>{user.username}</strong><span>{user.email}</span></div>
<span class="sc-user-role">{user.role}</span> <span class="sc-user-role">{user.role}</span>
<span class="sc-muted sc-user-last-login" title="Last login">{formatLastLogin(user.lastLoginAt)}</span> <span class="sc-muted sc-user-last-login" title="Last login">{formatLastLogin(user.lastLoginAt)}</span>
{#if projects && projects.length > 0}
<span class="sc-muted sc-user-projects-summary" title="Project access">{projectSummary(user)}</span>
{/if}
<div class="sc-user-actions"> <div class="sc-user-actions">
<Button disabled={saving} size="sm" type="button" variant="secondary" onclick={() => startEditing(user)}>Edit</Button> <Button disabled={saving} size="sm" type="button" variant="secondary" onclick={() => startEditing(user)}>Edit</Button>
<Button disabled={saving || String(user.id) === String(currentUserId) || user.role === 'superadmin'} size="sm" type="button" variant="danger" onclick={() => void deleteUser(user)}>Remove</Button> <Button disabled={saving || String(user.id) === String(currentUserId) || user.role === 'superadmin'} size="sm" type="button" variant="danger" onclick={() => void deleteUser(user)}>Remove</Button>
+1
View File
@@ -28,6 +28,7 @@ export type {
AuthResetRequest, AuthResetRequest,
AuthSetupInput, AuthSetupInput,
ContentSnippet, ContentSnippet,
KnownProject,
NavItem, NavItem,
ProfileUpdateInput, ProfileUpdateInput,
ManagedUser, ManagedUser,
+33
View File
@@ -818,6 +818,39 @@
gap: 0.4rem; gap: 0.4rem;
} }
.sc-user-projects-summary {
max-width: 12rem;
overflow: hidden;
font-size: 0.8rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.sc-user-projects {
display: flex;
flex: 1 1 100%;
flex-wrap: wrap;
gap: 0.5rem 1rem;
margin: 0;
padding: 0.5rem 0.7rem;
border: 1px solid var(--sc-border);
border-radius: 0.5rem;
}
.sc-user-projects legend {
flex-basis: 100%;
margin-bottom: 0.3rem;
color: var(--sc-muted-fg);
font-size: 0.8rem;
}
.sc-user-project-option {
display: flex;
align-items: center;
gap: 0.35rem;
font-size: 0.85rem;
}
.sc-user-edit-row { .sc-user-edit-row {
align-items: stretch; align-items: stretch;
flex-wrap: wrap; flex-wrap: wrap;
+19
View File
@@ -58,6 +58,19 @@ export interface ManagedUser {
updatedAt?: string; updatedAt?: string;
/** Null/undefined means the account has never completed a login. */ /** Null/undefined means the account has never completed a login. */
lastLoginAt?: string | null; lastLoginAt?: string | null;
/**
* Project keys this account is restricted to logging into (AuthGuard's
* project-scope feature); an empty array (never undefined, when the
* backend supports this feature at all) means unrestricted. Undefined on
* a backend that doesn't report it at all.
*/
projects?: string[];
}
/** One project an administrator may restrict a user's login access to - see UserManagement's `projects` prop. */
export interface KnownProject {
key: string;
label: string;
} }
/** /**
@@ -79,6 +92,12 @@ export interface UserUpdateInput {
email?: string; email?: string;
password?: string; password?: string;
role?: UserRole; role?: UserRole;
/**
* Replaces the account's full project-access list when present (an empty
* array clears any restriction); omitted (undefined) leaves it untouched.
* Only ever set when UserManagement was given a `projects` prop.
*/
projects?: string[];
} }
export type UserListRequest = () => ManagedUser[] | Promise<ManagedUser[]>; export type UserListRequest = () => ManagedUser[] | Promise<ManagedUser[]>;