refactor(backend): rename mediacore package to media
This commit is contained in:
1 parent
e8cb7c6c68
commit
75c08beec6
34 files changed
+837
-656
No files matched your search
@@ -0,0 +1,35 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// MountAccountRoutes mounts the signed-in account routes onto r: the TOTP enrollment and
|
||||
// verification routes, which require a session, and GET /profile, which reports the session's
|
||||
// user or null. A project that signs users in through AuthGuard mounts these alongside its own
|
||||
// routes.
|
||||
func (s *Service) MountAccountRoutes(r chi.Router) {
|
||||
r.With(s.Require).Get("/security/totp/status", s.TOTPStatus)
|
||||
r.With(s.Require).Get("/security/totp/initiate", s.TOTPInitiate)
|
||||
r.With(s.Require).Post("/security/totp/verify", s.TOTPVerify)
|
||||
r.With(s.Require).Post("/security/totp/disable", s.TOTPDisable)
|
||||
r.With(s.Optional).Get("/profile", profile)
|
||||
}
|
||||
|
||||
func profile(w http.ResponseWriter, r *http.Request) {
|
||||
user := UserFromContext(r.Context())
|
||||
if user == nil {
|
||||
writeAccountJSON(w, http.StatusOK, map[string]any{"user": nil})
|
||||
return
|
||||
}
|
||||
writeAccountJSON(w, http.StatusOK, map[string]any{"user": user})
|
||||
}
|
||||
|
||||
func writeAccountJSON(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)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func TestProfileReportsTheSessionUser(t *testing.T) {
|
||||
guard := newRoleAuthGuard(t)
|
||||
auth := NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
|
||||
router := chi.NewRouter()
|
||||
auth.MountAccountRoutes(router)
|
||||
|
||||
anonymous := httptest.NewRecorder()
|
||||
router.ServeHTTP(anonymous, httptest.NewRequest(http.MethodGet, "/profile", nil))
|
||||
if anonymous.Code != http.StatusOK || strings.TrimSpace(anonymous.Body.String()) != `{"user":null}` {
|
||||
t.Fatalf("anonymous profile = %d %s, want a null user", anonymous.Code, anonymous.Body.String())
|
||||
}
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/profile", nil)
|
||||
request.AddCookie(&http.Cookie{Name: "auth_session", Value: "viewer-token"})
|
||||
known := httptest.NewRecorder()
|
||||
router.ServeHTTP(known, request)
|
||||
var body struct{ User map[string]any }
|
||||
if err := json.Unmarshal(known.Body.Bytes(), &body); err != nil || body.User["username"] != "tester" || body.User["role"] != "user" {
|
||||
t.Fatalf("profile = %s, %v", known.Body.String(), err)
|
||||
}
|
||||
}
|
||||
|
||||
type loginRequiredStore struct{}
|
||||
|
||||
func (loginRequiredStore) LoginRequired(context.Context) (bool, error) { return true, nil }
|
||||
func (loginRequiredStore) SetLoginRequired(context.Context, bool) error { return nil }
|
||||
func (loginRequiredStore) IsSetupClaimed(context.Context) (bool, error) { return true, nil }
|
||||
func (loginRequiredStore) TryClaimSetup(context.Context) (bool, error) { return false, nil }
|
||||
func (loginRequiredStore) UnclaimSetup(context.Context) error { return nil }
|
||||
|
||||
// loginOffStore is loginRequiredStore with login switched off for the whole application.
|
||||
type loginOffStore struct{ loginRequiredStore }
|
||||
|
||||
func (loginOffStore) LoginRequired(context.Context) (bool, error) { return false, nil }
|
||||
|
||||
func newRoleAuthGuard(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
roles := map[string]string{"viewer-token": "user", "moderator-token": "moderator", "admin-token": "admin"}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
role, ok := roles[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
|
||||
if !ok || r.URL.Path != "/api/me" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"user":{"id":1,"username":"tester","role":%q}}`, role)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
// platformUsersSchema holds the test's own `users` table, so it never meets the fuller table that
|
||||
// mediacore's migration creates in the same database.
|
||||
// the media package's migration creates in the same database.
|
||||
const platformUsersSchema = "platform_users_test"
|
||||
|
||||
// withSearchPath returns databaseURL with its search_path set to schema.
|
||||
@@ -29,7 +29,7 @@ func withSearchPath(t *testing.T, databaseURL, schema string) string {
|
||||
|
||||
// TestPlatformUserSQL runs the moderatable platform-user methods (CreateUser, ListUsers,
|
||||
// UpdateUser, SetPassword, DeleteUser) against a real database. The `users` table normally comes
|
||||
// from mediacore's migration, which this package cannot import, so the test creates the columns it
|
||||
// from the media package's migration, which this package cannot import, so the test creates the columns it
|
||||
// needs in a schema of its own. It is skipped unless SHARED_TEST_DATABASE_URL points at a scratch
|
||||
// database, for example:
|
||||
//
|
||||
|
||||
+15
-20
@@ -1,10 +1,7 @@
|
||||
// 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. Originally its own "mediaauth" package; merged into this
|
||||
// package (2026-09-13) since it is no longer media-specific - see "Unified
|
||||
// This file holds the /auth/... and /api/auth/... handlers, proxied to AuthGuard. Promoted from
|
||||
// each service's own internal/auth into this shared library so every project that signs users in
|
||||
// through AuthGuard uses one copy instead of duplicating it. It was merged here from a separate
|
||||
// package (2026-09-13) since it is not specific to any one project - 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,
|
||||
@@ -13,9 +10,8 @@
|
||||
//
|
||||
// Unified auth proxy
|
||||
// ==================
|
||||
// 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
|
||||
// This file used to be its own package, built around New and wired directly to the 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
|
||||
@@ -23,7 +19,7 @@
|
||||
// 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
|
||||
// original constructor) is unchanged and is really just
|
||||
// NewWithStore plus pgSettingsStore, the default ProxyStore implementation
|
||||
// backed by the shared `settings` table.
|
||||
//
|
||||
@@ -44,7 +40,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). This
|
||||
// via the `authclient` package (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
|
||||
@@ -257,7 +253,7 @@ var adminProfile = ProxyUser{ID: 0, Username: "Admin", Email: "", Role: string(R
|
||||
// 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
|
||||
// implementation New builds automatically over the 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.
|
||||
@@ -272,7 +268,7 @@ type ProxyStore interface {
|
||||
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
|
||||
// a concept specific to the platform-users table, 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.
|
||||
@@ -351,7 +347,7 @@ func WithTrustedProxies(networks []*net.IPNet) ServiceOption {
|
||||
return func(o *serviceOptions) { o.trustedProxies = networks }
|
||||
}
|
||||
|
||||
// New constructs a Service backed by the media family's shared `settings`
|
||||
// New constructs a Service backed by the 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
|
||||
@@ -373,7 +369,7 @@ func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL,
|
||||
|
||||
// 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 own storage rather than the 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).
|
||||
@@ -410,9 +406,8 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
// pgSettingsStore is the default ProxyStore New builds over the shared
|
||||
// `settings` key/value table (see settings.Value/settings.Save) - unchanged behavior from before this package accepted a
|
||||
// pluggable ProxyStore.
|
||||
type pgSettingsStore struct {
|
||||
db *pgxpool.Pool
|
||||
@@ -1629,7 +1624,7 @@ func normalizePlatformRole(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
|
||||
// URLParam for 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 {
|
||||
|
||||
Reference in new issue
Block a user