Let non-admin accounts be granted single services, starting with /receipt/
Test and deploy / test (push) Successful in 1m57s
Test and deploy / deploy (push) Successful in 1m42s

Access was admin or nothing, so letting a friend print receipts meant making
them a full admin. Users now carry a list of permissions (User.Permissions,
a JSON column), each a key from the registry in services/permissions.go;
admins pass every check. The only key so far is `receipt`.

GET /auth/validate/:permission answers like /auth/validate-admin (200/403/401,
with the same refresh-token fallback, now shared) plus 404 for an unknown key,
and reads the user row rather than the token, so a grant or revoke applies on
the next request. On 200 it returns the username in X-Auth-User.

nginx gets a permission gate beside the admin gate: a location sets
$auth_permission and auth_requests /internal/auth/validate. /receipt/ moves
onto it, forwarding X-Remote-User to the receipt server. 403 now goes to
/no-access rather than back to the login page. The variable must not be given
a server-level default: the subrequest re-runs the server rewrite phase and
would blank it.

The admin panel's Manage Users tab ticks permissions per user
(setUserPermissions, permissionTypes). The login page is no longer
admin-only in wording or destination: a non-admin lands on /account, which
lists the services they can open; /no-access is the same view with a notice.

/auth/validate-admin and every other admin-gated service are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 22:04:56 +01:00
co-authored by Claude Opus 5.5
parent efd74c1693
commit acf21c69c2
27 changed files with 1101 additions and 119 deletions
+1
View File
@@ -96,6 +96,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
- **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. Revocation is by `User.TokenVersion`: every token carries the version it was minted with, and logout or a password change bumps it, invalidating all of that user's tokens. On the frontend the router guard awaits `auth.ensureLoaded()` (a standalone `me` query), not the home query; `homeData` exposes `settled` (finished either way) as well as `loaded` (succeeded).
- **GraphQL auth is declared in the schema.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. A field is protected by annotating it `@admin` or `@signedIn` in `graph/schema/*.graphql` (implemented in `graph/directives.go`). `graph/directives_test.go` fails if a mutation has neither directive and is not on its short public allow-list (`login`, `logout`, `refreshToken`), so a new mutation cannot ship unguarded by accident; a new *query* is public unless you annotate it. Finer rules (post ownership, hiding private messages) stay in the resolver. See `backend/graph/doc.go`.
- **Adding a GraphQL entity**: model in `models/models.go` (and the AutoMigrate list), schema file with directives, mapping in `gqlgen.yml`, `make generate`, fill in the resolvers; on the frontend a store built with `createCrudStore`. Model `ID uint` binds directly via `graphql.UintID` — there are no hand-written ID resolvers. Full recipe in `backend/README.md`.
- **Per-service permissions**: a non-admin account can be granted individual gated services (today only `receipt`, for `/receipt/`) in the admin panel's Manage Users tab. The keys are the registry `services.PermissionTypes` (`backend/services/permissions.go`), stored in `User.Permissions`; admins hold them all. nginx's *permission gate* (`set $auth_permission <key>; auth_request /internal/auth/validate;`, see `nginx/nginx_routes.conf.template`) asks `GET /auth/validate/<key>`, which reads the user row, so grants apply on the next request. Making another service grantable is a registry entry plus swapping its location from the admin gate to the permission gate. `/auth/validate-admin` and the admin gate are unchanged.
- **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts.
- **Environment variables**: every variable goes in `.env.example`, and a dummy value for it in `.env.dev`. One the Python service or the job tracker reads must also be added to the `python` or `jobs` service's explicit `environment:` list in `docker-compose.yml`, or the container never receives it. `.env` is edited by hand on the host; there is no admin-panel editor.
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
+7 -2
View File
@@ -68,7 +68,7 @@ backend icecast2 gitea sb sb-pub python | |
| certbot | `certbot` | — | — | no |
| cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of nginx, via Cloudflare | no (outbound only) |
| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by nginx `auth_request`; reads the Docker socket) | no |
| receipt printer (`receipt serve`, adamf/receipt_maker) | — (runs on **stppi**, not in this stack) | 8765 on stppi's Tailscale IP (`RECEIPT_WEB_UPSTREAM`) | `/receipt/`, prefix stripped (admin-gated by nginx `auth_request`; nginx adds `X-Receipt-Token`). The only upstream off this host; 503 "offline" when stppi is down | no |
| receipt printer (`receipt serve`, adamf/receipt_maker) | — (runs on **stppi**, not in this stack) | 8765 on stppi's Tailscale IP (`RECEIPT_WEB_UPSTREAM`) | `/receipt/`, prefix stripped (permission-gated on `receipt` by nginx `auth_request`; nginx adds `X-Receipt-Token` and `X-Remote-User`). The only upstream off this host; 503 "offline" when stppi is down | no |
| traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no |
| autoheal (restarts unhealthy nginx) | `autoheal` | — (no network) | none; reads the Docker socket | no |
| garage (S3 object store) | `garage` | 3900 S3, 3902 web, 3903 admin | none directly; `/uploads/` falls back to its web endpoint for files not on the volume | no |
@@ -90,7 +90,7 @@ in one step — never change one without the other.**
- **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with
`resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a
backend down (502s until it appears) instead of refusing to start.
- **Admin gate.** `/sb/`, `/jobs/`, `/tracker/`, `/receipt/`, `/dozzle/`, `/garage/`, `/radio/admin/`, `/uploads/private/` and
- **Admin gate.** `/sb/`, `/jobs/`, `/tracker/`, `/dozzle/`, `/garage/`, `/radio/admin/`, `/uploads/private/` and
Gitea's history views and archives (`…/commit/`, `…/src/commit/`, `…/blame/commit/`, `…/archive/`, `…/compare/`; the
branch views stay public) are
protected by an `auth_request` subrequest to the backend's `/auth/validate-admin`; a failure
@@ -98,6 +98,11 @@ in one step — never change one without the other.**
job and activity trackers also check the session themselves. Their carve-outs, which a session
cookie never reaches, stay public at nginx and are guarded by bearer tokens in the apps:
`/jobs/api/capture` and `/jobs/job-capture.user.js`, `/tracker/api/v1/` and `/tracker/tracker.user.js`.
- **Permission gate.** `/receipt/` asks `/auth/validate/receipt` instead, which also lets in a
non-admin account granted `receipt` in the admin panel's Manage Users tab. Not signed in
redirects to the login; signed in without the grant redirects to `/no-access`. To let a
friend print: create their user (admin panel → User), then tick "Receipt printer" for them
under Manage Users. Revoking is the same tick, and applies on their next request.
- **Public notes privacy boundary.** `/notes/` is public, and the only thing
keeping `private/` (and `templates/`, `.git`, `.obsidian`) off it is a pair of
nginx deny blocks. SilverBullet's `SB_SPACE_IGNORE` only hides paths from its
+10
View File
@@ -64,6 +64,16 @@ graph/ GraphQL layer
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
and will transparently refresh, so returning admins are recognised without a
visible re-login.
- `GET /auth/validate/:permission` is the same for one named permission
(200 / 403 / 401, and 404 for a key that does not exist). It backs nginx's
*permission gate*, which lets a non-admin account into one service — the
receipt printer at `/receipt/` — without making it an admin. Grantable keys
are the registry `services.PermissionTypes` (`services/permissions.go`);
a user's grants are `User.Permissions`, set from the admin panel's Manage
Users tab (`setUserPermissions`). Admins pass every permission check. The
check reads the user row, not the token, so a grant or revoke applies on
the next request. On 200 it returns the username in `X-Auth-User`, which
nginx forwards to the gated service as `X-Remote-User`.
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing
is revoked server-side, and a token that has already been issued stays valid
until it expires. The same is true of demoting an admin: it takes effect on
+4
View File
@@ -34,6 +34,10 @@ models:
resolver: false
deletedAt:
resolver: false
# Not a database model: the fixed registry in services/permissions.go.
PermissionType:
model:
- adam-french.co.uk/backend/services.PermissionType
Post:
model:
- adam-french.co.uk/backend/models.Post
+5 -4
View File
@@ -187,10 +187,11 @@ func TestSignedInMutationsArePinned(t *testing.T) {
// `spotifyNeedsReauth` is false for non-admins.
func TestGuardedQueriesArePinned(t *testing.T) {
want := map[string]string{
"users": "admin",
"user": "admin",
"places": "signedIn",
"layouts": "admin",
"users": "admin",
"user": "admin",
"places": "signedIn",
"layouts": "admin",
"permissionTypes": "signedIn",
}
got := map[string]string{}
for _, field := range schemaUnderTest().Query.Fields {
+454 -33
View File
@@ -15,6 +15,7 @@ import (
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/introspection"
gqlparser "github.com/vektah/gqlparser/v2"
@@ -132,34 +133,35 @@ type ComplexityRoot struct {
}
Mutation struct {
ApplyLayout func(childComplexity int, id int, page string, replace bool) int
ClearBackground func(childComplexity int, page string) int
CreateActivity func(childComplexity int, input model.CreateActivityInput) int
CreateBookmark func(childComplexity int, input model.CreateBookmarkInput) int
CreateBox func(childComplexity int, input model.CreateBoxInput) int
CreateFavorite func(childComplexity int, input model.CreateFavoriteInput) int
CreateLayout func(childComplexity int, input model.CreateLayoutInput) int
CreatePage func(childComplexity int, input model.CreatePageInput) int
CreatePlace func(childComplexity int, input model.CreatePlaceInput) int
CreatePost func(childComplexity int, input model.CreatePostInput) int
CreateUser func(childComplexity int, input model.CreateUserInput) int
DeleteBookmark func(childComplexity int, id int) int
DeleteBox func(childComplexity int, id int) int
DeleteLayout func(childComplexity int, id int) int
DeletePage func(childComplexity int, id int) int
DeletePlace func(childComplexity int, id int) int
DeletePost func(childComplexity int, id int) int
DeleteUser func(childComplexity int, id int) int
Login func(childComplexity int, input model.LoginInput) int
Logout func(childComplexity int) int
RefreshToken func(childComplexity int) int
SetBackground func(childComplexity int, page string, input model.BackgroundInput) int
SetUserAdmin func(childComplexity int, id int, admin bool) int
UpdateBox func(childComplexity int, id int, input model.UpdateBoxInput) int
UpdateLayout func(childComplexity int, id int, input model.UpdateLayoutInput) int
UpdatePage func(childComplexity int, id int, input model.UpdatePageInput) int
UpdatePlace func(childComplexity int, id int, input model.UpdatePlaceInput) int
UpdatePost func(childComplexity int, id int, input model.UpdatePostInput) int
ApplyLayout func(childComplexity int, id int, page string, replace bool) int
ClearBackground func(childComplexity int, page string) int
CreateActivity func(childComplexity int, input model.CreateActivityInput) int
CreateBookmark func(childComplexity int, input model.CreateBookmarkInput) int
CreateBox func(childComplexity int, input model.CreateBoxInput) int
CreateFavorite func(childComplexity int, input model.CreateFavoriteInput) int
CreateLayout func(childComplexity int, input model.CreateLayoutInput) int
CreatePage func(childComplexity int, input model.CreatePageInput) int
CreatePlace func(childComplexity int, input model.CreatePlaceInput) int
CreatePost func(childComplexity int, input model.CreatePostInput) int
CreateUser func(childComplexity int, input model.CreateUserInput) int
DeleteBookmark func(childComplexity int, id int) int
DeleteBox func(childComplexity int, id int) int
DeleteLayout func(childComplexity int, id int) int
DeletePage func(childComplexity int, id int) int
DeletePlace func(childComplexity int, id int) int
DeletePost func(childComplexity int, id int) int
DeleteUser func(childComplexity int, id int) int
Login func(childComplexity int, input model.LoginInput) int
Logout func(childComplexity int) int
RefreshToken func(childComplexity int) int
SetBackground func(childComplexity int, page string, input model.BackgroundInput) int
SetUserAdmin func(childComplexity int, id int, admin bool) int
SetUserPermissions func(childComplexity int, id int, permissions []string) int
UpdateBox func(childComplexity int, id int, input model.UpdateBoxInput) int
UpdateLayout func(childComplexity int, id int, input model.UpdateLayoutInput) int
UpdatePage func(childComplexity int, id int, input model.UpdatePageInput) int
UpdatePlace func(childComplexity int, id int, input model.UpdatePlaceInput) int
UpdatePost func(childComplexity int, id int, input model.UpdatePostInput) int
}
Page struct {
@@ -171,6 +173,12 @@ type ComplexityRoot struct {
UpdatedAt func(childComplexity int) int
}
PermissionType struct {
Key func(childComplexity int) int
Label func(childComplexity int) int
Path func(childComplexity int) int
}
Place struct {
Category func(childComplexity int) int
Cost func(childComplexity int) int
@@ -206,6 +214,7 @@ type ComplexityRoot struct {
Messages func(childComplexity int) int
Page func(childComplexity int, slug string) int
Pages func(childComplexity int) int
PermissionTypes func(childComplexity int) int
Places func(childComplexity int) int
Post func(childComplexity int, id int) int
Posts func(childComplexity int) int
@@ -271,11 +280,12 @@ type ComplexityRoot struct {
}
User struct {
Admin func(childComplexity int) int
CreatedAt func(childComplexity int) int
ID func(childComplexity int) int
UpdatedAt func(childComplexity int) int
Username func(childComplexity int) int
Admin func(childComplexity int) int
CreatedAt func(childComplexity int) int
ID func(childComplexity int) int
Permissions func(childComplexity int) int
UpdatedAt func(childComplexity int) int
Username func(childComplexity int) int
}
}
@@ -319,6 +329,7 @@ type MutationResolver interface {
CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error)
DeleteUser(ctx context.Context, id int) (*models.User, error)
SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error)
SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error)
}
type QueryResolver interface {
Activities(ctx context.Context) ([]*models.Activity, error)
@@ -342,6 +353,7 @@ type QueryResolver interface {
SteamStatus(ctx context.Context) (*model.SteamStatus, error)
Users(ctx context.Context) ([]*models.User, error)
User(ctx context.Context, id int) (*models.User, error)
PermissionTypes(ctx context.Context) ([]*services.PermissionType, error)
}
type RowingResolver interface {
Time(ctx context.Context, obj *models.Rowing) (int, error)
@@ -978,6 +990,17 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
}
return e.ComplexityRoot.Mutation.SetUserAdmin(childComplexity, args["id"].(int), args["admin"].(bool)), true
case "Mutation.setUserPermissions":
if e.ComplexityRoot.Mutation.SetUserPermissions == nil {
break
}
args, err := ec.field_Mutation_setUserPermissions_args(ctx, rawArgs)
if err != nil {
return 0, false
}
return e.ComplexityRoot.Mutation.SetUserPermissions(childComplexity, args["id"].(int), args["permissions"].([]string)), true
case "Mutation.updateBox":
if e.ComplexityRoot.Mutation.UpdateBox == nil {
break
@@ -1071,6 +1094,25 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
return e.ComplexityRoot.Page.UpdatedAt(childComplexity), true
case "PermissionType.key":
if e.ComplexityRoot.PermissionType.Key == nil {
break
}
return e.ComplexityRoot.PermissionType.Key(childComplexity), true
case "PermissionType.label":
if e.ComplexityRoot.PermissionType.Label == nil {
break
}
return e.ComplexityRoot.PermissionType.Label(childComplexity), true
case "PermissionType.path":
if e.ComplexityRoot.PermissionType.Path == nil {
break
}
return e.ComplexityRoot.PermissionType.Path(childComplexity), true
case "Place.category":
if e.ComplexityRoot.Place.Category == nil {
break
@@ -1257,6 +1299,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
}
return e.ComplexityRoot.Query.Pages(childComplexity), true
case "Query.permissionTypes":
if e.ComplexityRoot.Query.PermissionTypes == nil {
break
}
return e.ComplexityRoot.Query.PermissionTypes(childComplexity), true
case "Query.places":
if e.ComplexityRoot.Query.Places == nil {
break
@@ -1505,6 +1553,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
}
return e.ComplexityRoot.User.ID(childComplexity), true
case "User.permissions":
if e.ComplexityRoot.User.Permissions == nil {
break
}
return e.ComplexityRoot.User.Permissions(childComplexity), true
case "User.updatedAt":
if e.ComplexityRoot.User.UpdatedAt == nil {
break
@@ -1844,6 +1898,18 @@ func (ec *executionContext) childFields_Page(ctx context.Context, field graphql.
return nil, fmt.Errorf("no field named %q was found under type Page", field.Name)
}
func (ec *executionContext) childFields_PermissionType(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
switch field.Name {
case "key":
return ec.fieldContext_PermissionType_key(ctx, field)
case "label":
return ec.fieldContext_PermissionType_label(ctx, field)
case "path":
return ec.fieldContext_PermissionType_path(ctx, field)
}
return nil, fmt.Errorf("no field named %q was found under type PermissionType", field.Name)
}
func (ec *executionContext) childFields_Place(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
switch field.Name {
case "id":
@@ -2006,6 +2072,8 @@ func (ec *executionContext) childFields_User(ctx context.Context, field graphql.
return ec.fieldContext_User_username(ctx, field)
case "admin":
return ec.fieldContext_User_admin(ctx, field)
case "permissions":
return ec.fieldContext_User_permissions(ctx, field)
}
return nil, fmt.Errorf("no field named %q was found under type User", field.Name)
}
@@ -2452,6 +2520,28 @@ func (ec *executionContext) field_Mutation_setUserAdmin_args(ctx context.Context
return args, nil
}
func (ec *executionContext) field_Mutation_setUserPermissions_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) {
var err error
args := map[string]any{}
arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id",
func(ctx context.Context, v any) (int, error) {
return ec.unmarshalNID2int(ctx, v)
})
if err != nil {
return nil, err
}
args["id"] = arg0
arg1, err := graphql.ProcessArgField(ctx, rawArgs, "permissions",
func(ctx context.Context, v any) ([]string, error) {
return ec.unmarshalNString2ᚕstringᚄ(ctx, v)
})
if err != nil {
return nil, err
}
args["permissions"] = arg1
return args, nil
}
func (ec *executionContext) field_Mutation_updateBox_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) {
var err error
args := map[string]any{}
@@ -5619,6 +5709,63 @@ func (ec *executionContext) fieldContext_Mutation_setUserAdmin(ctx context.Conte
return fc, nil
}
func (ec *executionContext) _Mutation_setUserPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
ec.OperationContext,
field,
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return ec.fieldContext_Mutation_setUserPermissions(ctx, field)
},
func(ctx context.Context) (any, error) {
fc := graphql.GetFieldContext(ctx)
return ec.Resolvers.Mutation().SetUserPermissions(ctx, fc.Args["id"].(int), fc.Args["permissions"].([]string))
},
func(ctx context.Context, next graphql.Resolver) graphql.Resolver {
directive0 := next
directive1 := func(ctx context.Context) (any, error) {
if ec.Directives.Admin == nil {
var zeroVal *models.User
return zeroVal, errors.New("directive admin is not implemented")
}
return ec.Directives.Admin(ctx, nil, directive0)
}
next = directive1
return next
},
func(ctx context.Context, selections ast.SelectionSet, v *models.User) graphql.Marshaler {
return ec.marshalNUser2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐUser(ctx, selections, v)
},
true,
true,
)
}
func (ec *executionContext) fieldContext_Mutation_setUserPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
fc = &graphql.FieldContext{
Object: "Mutation",
Field: field,
IsMethod: true,
IsResolver: true,
Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return ec.childFields_User(ctx, field)
},
}
defer func() {
if r := recover(); r != nil {
err = ec.Recover(ctx, r)
ec.Error(ctx, err)
}
}()
ctx = graphql.WithFieldContext(ctx, fc)
if fc.Args, err = ec.field_Mutation_setUserPermissions_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {
ec.Error(ctx, err)
return fc, err
}
return fc, nil
}
func (ec *executionContext) _Page_id(ctx context.Context, field graphql.CollectedField, obj *models.Page) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
@@ -5757,6 +5904,75 @@ func (ec *executionContext) fieldContext_Page_adminOnly(_ context.Context, field
return graphql.NewScalarFieldContext("Page", field, false, false, errors.New("field of type Boolean does not have child fields"))
}
func (ec *executionContext) _PermissionType_key(ctx context.Context, field graphql.CollectedField, obj *services.PermissionType) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
ec.OperationContext,
field,
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return ec.fieldContext_PermissionType_key(ctx, field)
},
func(ctx context.Context) (any, error) {
return obj.Key, nil
},
nil,
func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler {
return ec.marshalNString2string(ctx, selections, v)
},
true,
true,
)
}
func (ec *executionContext) fieldContext_PermissionType_key(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
return graphql.NewScalarFieldContext("PermissionType", field, false, false, errors.New("field of type String does not have child fields"))
}
func (ec *executionContext) _PermissionType_label(ctx context.Context, field graphql.CollectedField, obj *services.PermissionType) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
ec.OperationContext,
field,
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return ec.fieldContext_PermissionType_label(ctx, field)
},
func(ctx context.Context) (any, error) {
return obj.Label, nil
},
nil,
func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler {
return ec.marshalNString2string(ctx, selections, v)
},
true,
true,
)
}
func (ec *executionContext) fieldContext_PermissionType_label(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
return graphql.NewScalarFieldContext("PermissionType", field, false, false, errors.New("field of type String does not have child fields"))
}
func (ec *executionContext) _PermissionType_path(ctx context.Context, field graphql.CollectedField, obj *services.PermissionType) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
ec.OperationContext,
field,
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return ec.fieldContext_PermissionType_path(ctx, field)
},
func(ctx context.Context) (any, error) {
return obj.Path, nil
},
nil,
func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler {
return ec.marshalNString2string(ctx, selections, v)
},
true,
true,
)
}
func (ec *executionContext) fieldContext_PermissionType_path(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
return graphql.NewScalarFieldContext("PermissionType", field, false, false, errors.New("field of type String does not have child fields"))
}
func (ec *executionContext) _Place_id(ctx context.Context, field graphql.CollectedField, obj *models.Place) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
@@ -6932,6 +7148,51 @@ func (ec *executionContext) fieldContext_Query_user(ctx context.Context, field g
return fc, nil
}
func (ec *executionContext) _Query_permissionTypes(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
ec.OperationContext,
field,
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return ec.fieldContext_Query_permissionTypes(ctx, field)
},
func(ctx context.Context) (any, error) {
return ec.Resolvers.Query().PermissionTypes(ctx)
},
func(ctx context.Context, next graphql.Resolver) graphql.Resolver {
directive0 := next
directive1 := func(ctx context.Context) (any, error) {
if ec.Directives.SignedIn == nil {
var zeroVal []*services.PermissionType
return zeroVal, errors.New("directive signedIn is not implemented")
}
return ec.Directives.SignedIn(ctx, nil, directive0)
}
next = directive1
return next
},
func(ctx context.Context, selections ast.SelectionSet, v []*services.PermissionType) graphql.Marshaler {
return ec.marshalNPermissionType2ᚕᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋservicesᚐPermissionTypeᚄ(ctx, selections, v)
},
true,
true,
)
}
func (ec *executionContext) fieldContext_Query_permissionTypes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
fc = &graphql.FieldContext{
Object: "Query",
Field: field,
IsMethod: true,
IsResolver: true,
Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return ec.childFields_PermissionType(ctx, field)
},
}
return fc, nil
}
func (ec *executionContext) _Query___type(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
@@ -7752,6 +8013,29 @@ func (ec *executionContext) fieldContext_User_admin(_ context.Context, field gra
return graphql.NewScalarFieldContext("User", field, false, false, errors.New("field of type Boolean does not have child fields"))
}
func (ec *executionContext) _User_permissions(ctx context.Context, field graphql.CollectedField, obj *models.User) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
ec.OperationContext,
field,
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
return ec.fieldContext_User_permissions(ctx, field)
},
func(ctx context.Context) (any, error) {
return obj.Permissions, nil
},
nil,
func(ctx context.Context, selections ast.SelectionSet, v []string) graphql.Marshaler {
return ec.marshalNString2ᚕstringᚄ(ctx, selections, v)
},
true,
true,
)
}
func (ec *executionContext) fieldContext_User_permissions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
return graphql.NewScalarFieldContext("User", field, false, false, errors.New("field of type String does not have child fields"))
}
func (ec *executionContext) ___Directive_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) {
return graphql.ResolveField(
ctx,
@@ -10582,6 +10866,13 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet)
if out.Values[i] == graphql.Null {
out.Invalids++
}
case "setUserPermissions":
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
return ec._Mutation_setUserPermissions(ctx, field)
})
if out.Values[i] == graphql.Null {
out.Invalids++
}
default:
panic("unknown field " + strconv.Quote(field.Name))
}
@@ -10666,6 +10957,54 @@ func (ec *executionContext) _Page(ctx context.Context, sel ast.SelectionSet, obj
return out
}
var permissionTypeImplementors = []string{"PermissionType"}
func (ec *executionContext) _PermissionType(ctx context.Context, sel ast.SelectionSet, obj *services.PermissionType) graphql.Marshaler {
fields := graphql.CollectFields(ec.OperationContext, sel, permissionTypeImplementors)
out := graphql.NewFieldSet(fields)
deferredFieldSet := graphql.NewFieldSet(nil)
deferLabelToView := make(map[string]*graphql.FieldSetView)
for i, field := range fields {
switch field.Name {
case "__typename":
out.Values[i] = graphql.MarshalString("PermissionType")
case "key":
out.Values[i] = ec._PermissionType_key(ctx, field, obj)
if out.Values[i] == graphql.Null {
out.Invalids++
}
case "label":
out.Values[i] = ec._PermissionType_label(ctx, field, obj)
if out.Values[i] == graphql.Null {
out.Invalids++
}
case "path":
out.Values[i] = ec._PermissionType_path(ctx, field, obj)
if out.Values[i] == graphql.Null {
out.Invalids++
}
default:
panic("unknown field " + strconv.Quote(field.Name))
}
}
out.Dispatch(ctx)
if out.Invalids > 0 {
return graphql.Null
}
atomic.AddInt32(&ec.Deferred, int32(min(len(deferLabelToView), math.MaxInt32)))
ec.ProcessDeferredGroup(graphql.DeferredGroup{
Defers: deferLabelToView,
Path: graphql.GetPath(ctx),
FieldSet: deferredFieldSet,
Context: ctx,
})
return out
}
var placeImplementors = []string{"Place"}
func (ec *executionContext) _Place(ctx context.Context, sel ast.SelectionSet, obj *models.Place) graphql.Marshaler {
@@ -11298,6 +11637,28 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr
func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) })
}
out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) })
case "permissionTypes":
field := field
innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) {
defer func() {
if r := recover(); r != nil {
ec.Error(ctx, ec.Recover(ctx, r))
}
}()
res = ec._Query_permissionTypes(ctx, field)
if res == graphql.Null {
atomic.AddUint32(&fs.Invalids, 1)
}
return res
}
rrm := func(ctx context.Context) graphql.Marshaler {
return ec.OperationContext.RootResolverMiddleware(ctx,
func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) })
}
out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) })
case "__type":
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
@@ -11859,6 +12220,11 @@ func (ec *executionContext) _User(ctx context.Context, sel ast.SelectionSet, obj
if out.Values[i] == graphql.Null {
out.Invalids++
}
case "permissions":
out.Values[i] = ec._User_permissions(ctx, field, obj)
if out.Values[i] == graphql.Null {
out.Invalids++
}
default:
panic("unknown field " + strconv.Quote(field.Name))
}
@@ -12609,6 +12975,32 @@ func (ec *executionContext) marshalNPage2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋ
return ec._Page(ctx, sel, v)
}
func (ec *executionContext) marshalNPermissionType2ᚕᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋservicesᚐPermissionTypeᚄ(ctx context.Context, sel ast.SelectionSet, v []*services.PermissionType) graphql.Marshaler {
ret := graphql.MarshalSliceConcurrently(ctx, len(v), 0, false, func(ctx context.Context, i int) graphql.Marshaler {
fc := graphql.GetFieldContext(ctx)
fc.Result = &v[i]
return ec.marshalNPermissionType2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋservicesᚐPermissionType(ctx, sel, v[i])
})
for _, e := range ret {
if e == graphql.Null {
return graphql.Null
}
}
return ret
}
func (ec *executionContext) marshalNPermissionType2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋservicesᚐPermissionType(ctx context.Context, sel ast.SelectionSet, v *services.PermissionType) graphql.Marshaler {
if v == nil {
if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {
graphql.AddErrorf(ctx, "the requested element is null which the schema does not allow")
}
return graphql.Null
}
return ec._PermissionType(ctx, sel, v)
}
func (ec *executionContext) marshalNPlace2ᚕᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐPlaceᚄ(ctx context.Context, sel ast.SelectionSet, v []*models.Place) graphql.Marshaler {
ret := graphql.MarshalSliceConcurrently(ctx, len(v), 0, false, func(ctx context.Context, i int) graphql.Marshaler {
fc := graphql.GetFieldContext(ctx)
@@ -12811,6 +13203,35 @@ func (ec *executionContext) marshalNString2string(ctx context.Context, sel ast.S
return res
}
func (ec *executionContext) unmarshalNString2ᚕstringᚄ(ctx context.Context, v any) ([]string, error) {
vSlice := graphql.CoerceList(v)
var err error
res := make([]string, len(vSlice))
for i := range vSlice {
ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i))
res[i], err = ec.unmarshalNString2string(ctx, vSlice[i])
if err != nil {
return nil, err
}
}
return res, nil
}
func (ec *executionContext) marshalNString2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler {
ret := make(graphql.Array, len(v))
for i := range v {
ret[i] = ec.marshalNString2string(ctx, sel, v[i])
}
for _, e := range ret {
if e == graphql.Null {
return graphql.Null
}
}
return ret
}
func (ec *executionContext) unmarshalNTime2timeᚐTime(ctx context.Context, v any) (time.Time, error) {
res, err := graphql.UnmarshalTime(v)
return res, graphql.ErrorOnPath(ctx, err)
+16
View File
@@ -4,6 +4,17 @@ type User {
updatedAt: Time!
username: String!
admin: Boolean!
# Keys of the gated services this user may use (see PermissionType). Admins
# pass every permission check whatever this holds.
permissions: [String!]!
}
# One grantable service, from services.PermissionTypes: `key` is what is
# stored and what nginx gates on, `label` and `path` are for display.
type PermissionType {
key: String!
label: String!
path: String!
}
input CreateUserInput {
@@ -14,10 +25,15 @@ input CreateUserInput {
extend type Query {
users: [User!]! @admin
user(id: ID!): User @admin
# @signedIn rather than @admin: /account lists a non-admin's own services
# from it. The list itself is not a secret.
permissionTypes: [PermissionType!]! @signedIn
}
extend type Mutation {
createUser(input: CreateUserInput!): User! @admin
deleteUser(id: ID!): User! @admin
setUserAdmin(id: ID!, admin: Boolean!): User! @admin
# Replaces the user's whole permission list; unknown keys are rejected.
setUserPermissions(id: ID!, permissions: [String!]!): User! @admin
}
+43
View File
@@ -8,9 +8,11 @@ package graph
import (
"context"
"fmt"
"slices"
"adam-french.co.uk/backend/graph/model"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"golang.org/x/crypto/bcrypt"
)
@@ -72,6 +74,41 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
return &user, nil
}
// SetUserPermissions is the resolver for the setUserPermissions field.
func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error) {
// The whole list is replaced, so the admin panel sends every ticked box
// each time. An unknown key is refused rather than dropped, so a stale
// front end cannot silently save less than it showed. The stored list is
// rebuilt in registry order, which also drops duplicates.
want := map[string]bool{}
for _, key := range permissions {
if !services.ValidPermission(key) {
return nil, fmt.Errorf("unknown permission %q", key)
}
want[key] = true
}
granted := []string{}
for _, p := range services.PermissionTypes {
if want[p.Key] {
granted = append(granted, p.Key)
}
}
var user models.User
if err := r.Store.DB.First(&user, id).Error; err != nil {
return nil, fmt.Errorf("user not found")
}
// No token bump needed: the permission gate reads this column on every
// request, so the change applies to the user's next one.
user.Permissions = granted
if err := r.Store.DB.Save(&user).Error; err != nil {
return nil, err
}
return &user, nil
}
// Users is the resolver for the users field.
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
var users []models.User
@@ -89,3 +126,9 @@ func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error)
}
return &user, nil
}
// PermissionTypes is the resolver for the permissionTypes field.
func (r *queryResolver) PermissionTypes(ctx context.Context) ([]*services.PermissionType, error) {
// A copy, so nothing downstream can write through to the registry.
return ptrs(slices.Clone(services.PermissionTypes)), nil
}
+72 -36
View File
@@ -93,51 +93,86 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
}
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
// decide whether to show admin UI. It answers with a bare status code and no
// body: 200 admin, 403 authenticated but not admin, 401 not authenticated.
// decide whether to show admin UI, nginx's admin gate calls as an
// auth_request, and the jobs container calls with the visitor's cookies. It
// answers with a bare status code and no body: 200 admin, 403 authenticated
// but not admin, 401 not authenticated.
//
// Unlike AdminMiddleware it falls back to the refresh token, and will mint a
// new cookie pair as a side effect, so a returning admin is recognised
// without a visible re-login.
func (store *Store) ValidateAdmin(ctx *gin.Context) {
accessToken, err := ctx.Cookie("access_token")
if err != nil {
// No access token — try refreshing
if !store.tryRefreshAndValidateAdmin(ctx) {
ctx.Status(http.StatusUnauthorized)
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool {
// On the access-token path admin is read from the token, as
// everywhere else; on the refresh path there is no admin claim, and
// the row is what makes that path pick up a revoked admin flag.
if claims == nil {
return user.Admin
}
return
}
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
if err != nil {
// Expired, invalid or revoked access token — try refreshing
if !store.tryRefreshAndValidateAdmin(ctx) {
ctx.Status(http.StatusUnauthorized)
}
return
}
admin, ok := (*claims)["admin"].(bool)
if !ok || !admin {
ctx.Status(http.StatusForbidden)
return
}
ctx.Status(http.StatusOK)
admin, ok := (*claims)["admin"].(bool)
return ok && admin
})
}
// tryRefreshAndValidateAdmin re-authenticates from the refresh token.
// ValidatePermission backs GET /auth/validate/:permission, nginx's permission
// gate (see services/permissions.go). Same bare-status contract and refresh
// fallback as ValidateAdmin — 200 allowed, 403 signed in without the
// permission, 401 not signed in — plus 404 for a key that is not in
// services.PermissionTypes, so a typo in an nginx location fails closed and
// visibly rather than as a 403 that looks like a missing grant.
//
// The bool does not mean "is an admin" — it means "this function already
// wrote the response". It returns true both for a successful admin refresh
// (200, new cookies set) and for a valid non-admin (403), and false only when
// it could not decide, leaving the caller to send 401. Getting this backwards
// would send two status codes for one request.
// The decision reads the user row, not the token, for admins as well: a
// grant, a revoke or a demotion applies on the very next request.
func (store *Store) ValidatePermission(ctx *gin.Context) {
key := ctx.Param("permission")
if !services.ValidPermission(key) {
ctx.Status(http.StatusNotFound)
return
}
store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
return services.HasPermission(user, key)
})
}
// validateSession is the body shared by the two validate endpoints: identify
// the caller from the access token, or failing that the refresh token, and
// answer 200 / 403 / 401 according to allow.
//
// Admin status is re-read from the database here, which is what makes the
// refresh path pick up a revoked admin flag.
func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
// allow receives the access token's claims, or nil when the caller was
// identified from the refresh token (which carries no authorisation claims).
//
// On 200 the username goes back in X-Auth-User, which nginx can lift with
// auth_request_set and hand to the service behind the gate, so that service
// knows who is using it without having accounts of its own.
func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) {
accessToken, err := ctx.Cookie("access_token")
if err == nil {
user, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
if err == nil {
if !allow(user, claims) {
ctx.Status(http.StatusForbidden)
return
}
ctx.Header("X-Auth-User", user.Username)
ctx.Status(http.StatusOK)
return
}
}
// No access token, or an expired, invalid or revoked one — try refreshing.
if !store.tryRefreshAndValidate(ctx, allow) {
ctx.Status(http.StatusUnauthorized)
}
}
// tryRefreshAndValidate re-authenticates from the refresh token.
//
// The bool does not mean "allowed" — it means "this function already wrote
// the response". It returns true both for a successful refresh (200, new
// cookies set) and for a valid but unauthorised user (403, no new cookies),
// and false only when it could not decide, leaving the caller to send 401.
// Getting this backwards would send two status codes for one request.
func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) bool {
refreshToken, err := ctx.Cookie("refresh_token")
if err != nil {
return false
@@ -150,7 +185,7 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
return false
}
if !user.Admin {
if !allow(user, nil) {
ctx.Status(http.StatusForbidden)
return true
}
@@ -162,6 +197,7 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
store.setAuthCookies(ctx, tokens)
ctx.Header("X-Auth-User", user.Username)
ctx.Status(http.StatusOK)
return true
}
+23 -2
View File
@@ -23,8 +23,9 @@ import (
// handler, so only the extension allow-list it gates on is covered, as a
// table contract below. (The site's general uploads — validation, naming,
// storage — are services.Uploads, tested in services/uploads_test.go.)
// - Store.isAdminRequest and the refresh fallback in ValidateAdmin: both
// reach the database on the refresh path.
// - Store.isAdminRequest, and the validate endpoints past their first
// check: they authenticate against the database. The allow/deny rule the
// permission gate applies is services.HasPermission, tested there.
//
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
// three shared caches, the admin claim check on the upload trust boundary, and
@@ -251,6 +252,26 @@ func TestRequestIsAdmin(t *testing.T) {
}
}
// --- Permission gate ------------------------------------------------------
// An unknown key must be refused before any session lookup (Store has no DB
// or Auth here, so reaching one would panic): it is how a typo in an nginx
// location shows up as a 404 rather than as a missing grant.
func TestValidatePermissionUnknownKey(t *testing.T) {
gin.SetMode(gin.TestMode)
s := &Store{}
for _, key := range []string{"no-such-service", "admin", ""} {
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Params = gin.Params{{Key: "permission", Value: key}}
ctx.Request = httptest.NewRequest("GET", "/auth/validate/"+key, nil)
s.ValidatePermission(ctx)
if ctx.Writer.Status() != 404 {
t.Errorf("key %q: status %d, want 404", key, ctx.Writer.Status())
}
}
}
// The radio allow-list is the radio upload's trust boundary. Testing it as
// data catches the realistic failure: someone adding a non-audio or malformed
// extension.
+1
View File
@@ -167,6 +167,7 @@ func main() {
r.GET("/auth/check", store.CheckToken)
r.POST("/auth/logout", store.Logout)
r.GET("/auth/validate-admin", store.ValidateAdmin)
r.GET("/auth/validate/:permission", store.ValidatePermission)
// SPOTIFY
// The callback must be open — Spotify redirects a logged-out browser to
+8
View File
@@ -39,6 +39,14 @@ type User struct {
// Admin gates almost every mutation. It is copied into the access token,
// so a change here only takes effect on the user's next token refresh.
Admin bool `json:"admin"`
// Permissions names the gated services this non-admin user may use, one
// key each from services.PermissionTypes (admins pass every check
// regardless). Unlike Admin it is never copied into a token: the gate
// reads it from the row, which services.Auth loads on every request
// anyway, so a grant or revoke takes effect on the user's next request.
// Stored as a JSON array in one text column; a row from before the
// column existed reads as NULL, i.e. no permissions.
Permissions []string `gorm:"serializer:json" json:"permissions"`
// TokenVersion is the session generation counter. Every issued JWT
// carries the value current at the time it was minted, and
// services.Auth rejects a token whose value no longer matches, so
+1 -1
View File
@@ -155,7 +155,7 @@ func tokenVersionOf(v uint) uint {
// verifies the signature and expiry, reads the id claim, loads the row, and
// checks the token version. Every caller that used to hand-roll this sequence
// (handlers.Store.CheckToken, handlers.Store.RefreshToken,
// handlers.Store.tryRefreshAndValidateAdmin and the GraphQL refreshToken
// handlers.Store.tryRefreshAndValidate and the GraphQL refreshToken
// resolver) now goes through here, so the checks cannot drift apart.
//
// The returned error is always one of the sentinels above, wrapped or not, so
+49
View File
@@ -0,0 +1,49 @@
package services
import (
"slices"
"adam-french.co.uk/backend/models"
)
// Per-service permissions: how a non-admin account is let into one gated
// service (the receipt printer, say) without being made an admin.
//
// A permission is a key from PermissionTypes stored in models.User.Permissions.
// nginx gates a service on one key by asking GET /auth/validate/<key>
// (handlers.Store.ValidatePermission); admins pass every such check, so
// moving a service from the admin gate to a permission gate never locks an
// admin out. Services that are not listed here stay admin-only.
//
// Adding a grantable service is one entry below plus swapping that location's
// nginx gate from /internal/auth/admin-validate to the permission gate (see
// "Permission gate" in nginx/nginx_routes.conf.template).
// PermissionType describes one grantable service. Key is what is stored and
// what nginx names; Label and Path are for the admin panel's checkboxes and
// the signed-in user's /account list of links.
type PermissionType struct {
Key string
Label string
Path string
}
// PermissionTypes is the full set of grantable permissions, in display order.
// Removing an entry leaves the key in users' rows, where it is inert: the
// validate endpoint 404s an unknown key, so nothing can be gated on it.
var PermissionTypes = []PermissionType{
{Key: "receipt", Label: "Receipt printer", Path: "/receipt/"},
}
// ValidPermission reports whether key names a permission in PermissionTypes.
func ValidPermission(key string) bool {
return slices.ContainsFunc(PermissionTypes, func(p PermissionType) bool {
return p.Key == key
})
}
// HasPermission reports whether user may use the service gated on key. It
// reads the row, not a token, so Admin here is the current database value.
func HasPermission(user *models.User, key string) bool {
return user.Admin || slices.Contains(user.Permissions, key)
}
+54
View File
@@ -0,0 +1,54 @@
package services
import (
"testing"
"adam-french.co.uk/backend/models"
)
func TestValidPermission(t *testing.T) {
for _, p := range PermissionTypes {
if !ValidPermission(p.Key) {
t.Errorf("listed key %q reported invalid", p.Key)
}
}
for _, key := range []string{"", "admin", "Receipt", "receipt "} {
if ValidPermission(key) {
t.Errorf("unlisted key %q reported valid", key)
}
}
}
// Keys must be URL-path safe: nginx splices them into /auth/validate/<key>.
func TestPermissionKeysArePathSafe(t *testing.T) {
seen := map[string]bool{}
for _, p := range PermissionTypes {
if seen[p.Key] {
t.Errorf("duplicate key %q", p.Key)
}
seen[p.Key] = true
for _, r := range p.Key {
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') {
t.Errorf("key %q has %q; use lowercase letters, digits and '-'", p.Key, r)
}
}
}
}
func TestHasPermission(t *testing.T) {
cases := []struct {
name string
user models.User
want bool
}{
{"admin passes without a grant", models.User{Admin: true}, true},
{"granted user passes", models.User{Permissions: []string{"receipt"}}, true},
{"other grant does not count", models.User{Permissions: []string{"other"}}, false},
{"no grants (NULL column) fails", models.User{}, false},
}
for _, c := range cases {
if got := HasPermission(&c.user, "receipt"); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
+6 -1
View File
@@ -29,6 +29,11 @@ var logQuietDrop = map[string]bool{
"/auth/check": true, // front-end session check
}
// logQuietDropPrefix is the permission gate's auth_request subrequest
// (/auth/validate/<key>), dropped on 2xx for the same reason as
// /auth/validate-admin above: it repeats on every request to a gated page.
const logQuietDropPrefix = "/auth/validate/"
// TrafficLogFormatter renders gin's log line. Signed to gin's LogFormatter
// signature so it plugs into gin.LoggerWithFormatter.
func TrafficLogFormatter(params gin.LogFormatterParams) string {
@@ -63,7 +68,7 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
// All-quiet: drop heartbeat endpoints that succeeded. A 4xx/5xx on them
// is still interesting (an expired session raging against refresh, a
// broken admin gate) and is kept.
if logQuietDrop[path] && params.StatusCode < 400 {
if (logQuietDrop[path] || startsWith(path, logQuietDropPrefix)) && params.StatusCode < 400 {
return ""
}
+9
View File
@@ -25,6 +25,15 @@ func TestTrafficFormatterDropsQuietHeartbeats(t *testing.T) {
}
}
func TestTrafficFormatterDropsPermissionGate(t *testing.T) {
if out := TrafficLogFormatter(fmtParams("GET", "/auth/validate/receipt", 200, "172.28.0.6", time.Millisecond)); out != "" {
t.Fatalf("permission-gate 200 should be dropped, got %q", out)
}
if out := TrafficLogFormatter(fmtParams("GET", "/auth/validate/receipt", 403, "172.28.0.6", time.Millisecond)); out == "" {
t.Fatal("a refused permission check must stay visible")
}
}
func TestTrafficFormatterKeepsHeartbeatFailures(t *testing.T) {
out := TrafficLogFormatter(fmtParams("GET", "/auth/validate-admin", 401, "172.28.0.6", time.Millisecond))
if out == "" {
+54 -9
View File
@@ -546,19 +546,25 @@
# ---- Receipt printer (/receipt/) ----
# The adamf/receipt_maker repo's `receipt serve`, running on stppi
# (not in this stack: that machine reaches the printer on the home LAN). A page
# for printing a note or an uploaded image, plus its API. Gated like
# /tracker/ on the admin session; the prefix IS stripped. The server
# trusts nothing without X-Receipt-Token, which only this proxy adds
# (proxy_set_header replaces any copy the client sent). The value is
# quoted so an unset token still renders a valid config. When stppi
# is off or unreachable the connect fails fast and @receipt_offline answers.
# for printing a note or an uploaded image, plus its API. Behind the
# permission gate on `receipt`, so an account granted it in the admin
# panel can print without being an admin; the prefix IS stripped. The
# server trusts nothing without X-Receipt-Token, which only this proxy
# adds (proxy_set_header replaces any copy the client sent), and is
# told who is printing in X-Remote-User, likewise only set here. The
# token is quoted so an unset one still renders a valid config. When
# stppi is off or unreachable the connect fails fast and
# @receipt_offline answers.
location = /receipt {
return 301 /receipt/;
}
location ^~ /receipt/ {
auth_request /internal/auth/admin-validate;
error_page 401 403 = @auth_denied;
set $auth_permission receipt;
auth_request /internal/auth/validate;
auth_request_set $auth_user $upstream_http_x_auth_user;
error_page 401 = @auth_denied;
error_page 403 = @auth_forbidden;
error_page 502 504 = @receipt_offline;
limit_req zone=api burst=10 nodelay;
# The server caps uploads at 16 MB; this leaves room for the
@@ -571,6 +577,7 @@
# dead printer socket gives up after escpos's 60 s timeout.
proxy_read_timeout 90s;
proxy_set_header X-Receipt-Token "${RECEIPT_WEB_TOKEN}";
proxy_set_header X-Remote-User $auth_user;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
@@ -596,7 +603,7 @@
return 301 /jobs/job-capture.user.js;
}
# ---- Admin gate (/sb/, /jobs/, /tracker/, /receipt/, /dozzle/, /garage/, /radio/admin/, /uploads/private/) ----
# ---- Admin gate (/sb/, /jobs/, /tracker/, /dozzle/, /garage/, /radio/admin/, /uploads/private/) ----
# (/uploads/private/ is declared in the including template, not here;
# it points at the two locations below by name.)
# `auth_request` makes nginx fire a subrequest here before serving the
@@ -634,3 +641,41 @@
location @auth_denied {
return 302 /admin/login?redirect=$request_uri;
}
# ---- Permission gate (/receipt/) ----
# The same auth_request mechanism as the admin gate above, but asking
# GET /auth/validate/<key> whether the session holds one named
# permission (services/permissions.go; admins hold them all). A gated
# location sets $auth_permission and points auth_request here:
#
# set $auth_permission <key>;
# auth_request /internal/auth/validate;
# error_page 401 = @auth_denied;
# error_page 403 = @auth_forbidden;
#
# The variable reaches the subrequest because nginx subrequests share
# the parent request's variables, and `set` runs in the rewrite phase,
# before auth_request's access phase. It must NOT also be given a
# default at server level: a subrequest re-runs the server-level
# rewrite phase, so that `set` would blank the shared value before
# this location reads it. (A location that forgets to set it asks for
# /auth/validate/, which matches no route: denied.) 401 (not signed in) goes to the
# login page as before; 403 (signed in, not granted) goes to a page
# that says so, since sending a signed-in user to log in again only
# shows them "Already signed in". On success the backend returns the
# username in X-Auth-User, which a location can forward with
# auth_request_set (see /receipt/). The body/limit settings are the
# admin-validate location's, for the same reasons.
location = /internal/auth/validate {
internal;
client_max_body_size 0;
rewrite ^ /auth/validate/$auth_permission break;
proxy_pass $upstream_backend;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header Cookie $http_cookie;
}
location @auth_forbidden {
return 302 /no-access?path=$request_uri;
}
+2 -1
View File
@@ -65,7 +65,8 @@ Two layout shells, defined in `src/router/index.js`:
| --- | --- | --- |
| `/` | DefaultLayout | Landing page (statically imported — it's the first paint): a box canvas, page key `index`; the old fixed page is its starter layout, `views/landing/landingLayout.js` |
| `/stp` | DefaultLayout | The personal home page: an ordinary canvas page (the `Page` with slug `stp`) served by the catch-all, see "The /stp canvas" below |
| `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin` |
| `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin`. The login page is everyone's, admin or not |
| `/account`, `/no-access` | DefaultLayout | `views/account/Account.vue`, guarded by `meta.requiresSignIn`: the gated services a non-admin has been granted. `/no-access` is where nginx's permission gate sends a signed-in visitor without the grant |
| `/automata`, `/hotels` | DefaultLayout | |
| `/shrines`, `/shrines/*` | DefaultLayout | All canvas pages via the catch-all: `/shrines` is an index whose links are Link boxes placed by hand |
| `/cv` | CVLayout | Light print theme. Its Jobs button goes to `/jobs/`, the separate job tracker app (`adamf/job-tracker`); nginx redirects the old `/cv/jobs` and `/cv/leads` there |
+21 -4
View File
@@ -1,5 +1,5 @@
/**
* Route table and the single admin route guard.
* Route table and the single sign-in/admin route guard.
*
* Structure: two layout shells. `/` mounts DefaultLayout (navbar + footer, dark
* theme) and holds most routes; `/cv` mounts CVLayout (light print theme).
@@ -44,6 +44,21 @@ const router = createRouter({
component: () => import("@/views/admin/Admin.vue"),
meta: { requiresAdmin: true },
},
// A signed-in user's own page: the gated services they have
// been granted. /no-access is the same page with a notice,
// where nginx's permission gate sends a refused visitor.
{
path: "account",
name: "account",
component: () => import("@/views/account/Account.vue"),
meta: { requiresSignIn: true },
},
{
path: "no-access",
name: "no-access",
component: () => import("@/views/account/Account.vue"),
meta: { requiresSignIn: true },
},
{
path: "automata",
name: "mobile-automata",
@@ -96,7 +111,8 @@ const router = createRouter({
],
});
// Guard for routes marked `meta: { requiresAdmin: true }`.
// Guard for routes marked `meta: { requiresAdmin: true }` or
// `meta: { requiresSignIn: true }` (any account, admin or not).
//
// The admin flag arrives asynchronously, so navigating straight to /admin on a
// cold load would otherwise read an empty user and bounce a legitimate admin to
@@ -109,10 +125,11 @@ const router = createRouter({
// as "not signed in" — and `user` is re-read on every navigation, so a login or
// logout during the session is honoured.
router.beforeEach(async (to) => {
if (!to.meta.requiresAdmin) return;
if (!to.meta.requiresAdmin && !to.meta.requiresSignIn) return;
const auth = useAuthStore();
await auth.ensureLoaded();
if (!auth.user.admin)
const allowed = to.meta.requiresAdmin ? auth.user.admin : auth.loggedIn;
if (!allowed)
return { path: "/admin/login", query: { redirect: to.fullPath } };
});
+41 -5
View File
@@ -23,6 +23,11 @@ import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { gql } from "@/graphql";
// The user fields every query here selects, so `user` has the same shape
// whichever one filled it. `permissions` is the list of gated services
// (/receipt/ and so on) a non-admin may open; see views/Account.vue.
export const USER_FIELDS = "id username admin permissions";
export const useAuthStore = defineStore("auth", () => {
const user = ref({});
const loggedIn = computed(() => !!user.value.username);
@@ -71,7 +76,7 @@ export const useAuthStore = defineStore("auth", () => {
if (resolved.value) return Promise.resolve();
if (!pending) {
const requestedAt = epoch;
pending = gql(`query Me { me { id username admin } }`)
pending = gql(`query Me { me { ${USER_FIELDS} } }`)
.then((data) => adoptSession(data.me, requestedAt))
.catch((err) => console.error("me query failed:", err))
.finally(() => {
@@ -98,7 +103,7 @@ export const useAuthStore = defineStore("auth", () => {
async function logIn(username, password) {
try {
const data = await gql(
`mutation Login($input: LoginInput!) { login(input: $input) { user { id username admin } } }`,
`mutation Login($input: LoginInput!) { login(input: $input) { user { ${USER_FIELDS} } } }`,
{ input: { username, password } },
);
user.value = data.login.user;
@@ -113,7 +118,7 @@ export const useAuthStore = defineStore("auth", () => {
async function createUser(username, password) {
try {
const data = await gql(
`mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { id username admin } }`,
`mutation CreateUser($input: CreateUserInput!) { createUser(input: $input) { ${USER_FIELDS} } }`,
{ input: { username, password } },
);
return data.createUser;
@@ -128,7 +133,7 @@ export const useAuthStore = defineStore("auth", () => {
async function refreshToken() {
try {
const data = await gql(
`mutation { refreshToken { user { id username admin } } }`,
`mutation { refreshToken { user { ${USER_FIELDS} } } }`,
);
user.value = data.refreshToken.user;
markSessionChanged();
@@ -141,7 +146,7 @@ export const useAuthStore = defineStore("auth", () => {
async function setUserAdmin(userId, admin) {
try {
const data = await gql(
`mutation SetUserAdmin($id: ID!, $admin: Boolean!) { setUserAdmin(id: $id, admin: $admin) { id username admin } }`,
`mutation SetUserAdmin($id: ID!, $admin: Boolean!) { setUserAdmin(id: $id, admin: $admin) { ${USER_FIELDS} } }`,
{ id: userId, admin },
);
return data.setUserAdmin;
@@ -151,6 +156,34 @@ export const useAuthStore = defineStore("auth", () => {
}
}
/** Admin-only: replace a user's permission list. Returns the updated user;
* re-throws. */
async function setUserPermissions(userId, permissions) {
try {
const data = await gql(
`mutation SetUserPermissions($id: ID!, $permissions: [String!]!) { setUserPermissions(id: $id, permissions: $permissions) { ${USER_FIELDS} } }`,
{ id: userId, permissions },
);
return data.setUserPermissions;
} catch (err) {
console.error(err);
throw err;
}
}
/** Signed-in only: every grantable service, as [{ key, label, path }].
* Re-throws. */
async function fetchPermissionTypes() {
const data = await gql(`query { permissionTypes { key label path } }`);
return data.permissionTypes;
}
/** Whether the signed-in user may open the service gated on `key`. Admins
* may open them all, as on the server. */
function can(key) {
return !!user.value.admin || (user.value.permissions ?? []).includes(key);
}
return {
user,
@@ -165,5 +198,8 @@ export const useAuthStore = defineStore("auth", () => {
logOut,
createUser,
setUserAdmin,
setUserPermissions,
fetchPermissionTypes,
can,
};
});
+2 -2
View File
@@ -25,7 +25,7 @@ import { defineStore } from "pinia";
import { ref } from "vue";
import { gql } from "@/graphql";
import axios from "axios";
import { useAuthStore } from "@/stores/auth";
import { useAuthStore, USER_FIELDS } from "@/stores/auth";
export const useHomeDataStore = defineStore("homeData", () => {
const loaded = ref(false);
@@ -66,7 +66,7 @@ export const useHomeDataStore = defineStore("homeData", () => {
bookmarks { id category name link }
giteaFeed { avatarUrl repoUrl repoName opType commitMessage createdAt }
steamStatus { online recentGames { appId name playtime2Weeks playtimeForever headerImageUrl } }
me { id username admin }
me { ${USER_FIELDS} }
}
`),
fetchRadioStatus(),
+125
View File
@@ -0,0 +1,125 @@
<script setup>
/**
* Routes `/account` and `/no-access` (both `meta.requiresSignIn`): the landing
* page for a signed-in account that is not an admin, listing the gated
* services it has been granted (backend/services/permissions.go) as links.
*
* `/no-access` is where nginx's permission gate sends a signed-in visitor who
* lacks the permission (`@auth_forbidden`, with the refused address in
* `?path=`). It is this same page with a notice on top, since "what can I
* open instead" is the useful answer to "you can't open that".
*
* The links are plain <a href>, not RouterLinks: every service lives in
* another container behind nginx, so it needs a real page load.
*/
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useAuthStore } from "@/stores/auth";
import Button from "@/components/input/Button.vue";
const auth = useAuthStore();
const route = useRoute();
const router = useRouter();
const permissionTypes = ref([]);
const loaded = ref(false);
const error = ref("");
const services = computed(() =>
permissionTypes.value.filter((p) => auth.can(p.key)),
);
// Only shown on /no-access, and only as text, so an odd value is harmless.
const refused = computed(() =>
route.name === "no-access" && typeof route.query.path === "string"
? route.query.path
: "",
);
onMounted(async () => {
try {
permissionTypes.value = await auth.fetchPermissionTypes();
} catch (err) {
console.error(err);
error.value = err.message || "Couldn't load your services";
} finally {
loaded.value = true;
}
});
// The guard only runs on navigation, so logging out in place would leave the
// page up for a signed-out visitor; leave it instead.
async function handleLogout() {
await auth.logOut();
router.push("/admin/login");
}
</script>
<template>
<main class="account-page">
<div class="account-card bdr-1">
<p v-if="refused" class="account-refused" role="alert">
You don't have access to <code>{{ refused }}</code>.
</p>
<h1>Your services</h1>
<small>Signed in as <code>{{ auth.user.username }}</code>.</small>
<p v-if="error" class="text-tertiary" role="alert">{{ error }}</p>
<p v-else-if="!loaded" class="text-muted">Loading…</p>
<ul v-else-if="services.length" class="account-services">
<li v-for="s in services" :key="s.key">
<a :href="s.path">{{ s.label }}</a>
</li>
</ul>
<p v-else class="text-muted">Nothing has been shared with you yet.</p>
<div class="account-actions">
<Button v-if="auth.user.admin" @click="router.push('/admin')">
Open Admin
</Button>
<Button @click="handleLogout">Log Out</Button>
</div>
</div>
</main>
</template>
<style scoped>
.account-page {
display: flex;
align-items: center;
justify-content: center;
min-height: 70vh;
padding: 16px;
}
.account-card {
width: 100%;
max-width: 380px;
background-color: var(--color-surface);
padding: 18px 20px 12px;
display: flex;
flex-direction: column;
gap: 8px;
}
.account-refused {
color: var(--color-tertiary);
border: 1px dashed var(--color-tertiary);
padding: 4px 8px;
}
.account-services {
display: flex;
flex-direction: column;
gap: 4px;
padding-left: 1.2rem;
list-style: square;
}
.account-actions {
display: flex;
gap: 6px;
margin-top: 4px;
}
</style>
+1 -1
View File
@@ -109,7 +109,7 @@ async function handleLogout() {
</a>
<!-- The receipt printer's page is served from stppi, which reaches
the printer on the home LAN; nginx proxies /receipt/ there over
Tailscale behind the admin check. -->
Tailscale behind the `receipt` permission gate. -->
<a
class="admin-nav-link no-underline"
href="/receipt/"
+18 -8
View File
@@ -1,10 +1,13 @@
<script setup>
/**
* Route `/admin/login`. On success redirects to `?redirect=` or to /admin.
* Route `/admin/login`, the one login page for everyone: admins and accounts
* granted a gated service (the receipt printer, say). On success redirects to
* `?redirect=`, or else to /admin for an admin and /account for anyone else
* (a non-admin would only bounce off /admin's guard back to here).
*
* The `?redirect=` is set by two different gates: the SPA router guard
* (`meta.requiresAdmin`) and nginx's `auth_request` gate in front of the
* proxied containers (/notes/, /sb/). The latter means the
* proxied containers (/notes/, /sb/, /receipt/). The latter means the
* destination is frequently NOT a Vue route, so see goTo() below.
*
* auth.logIn() never throws — it swallows the error — so success is detected by
@@ -31,8 +34,8 @@ const errorMsg = ref("");
// Send the browser to `dest`, choosing SPA navigation vs. a real page load.
//
// nginx bounces /notes/ and /sb/ here when the admin cookie is
// missing; those paths belong to other containers, so router.push() would just
// nginx bounces /notes/, /sb/, /receipt/ and the like here when the session
// is missing; those paths belong to other containers, so router.push() would just
// match the catch-all 404 route and never leave the SPA. Resolving the path
// first tells us which it is: the catch-all matches everything, so landing on
// the route named "404" means no real Vue route exists and the browser needs a
@@ -42,7 +45,7 @@ const errorMsg = ref("");
// site-relative path — a leading "//" or a scheme would be an open redirect.
function goTo(dest) {
if (typeof dest !== "string" || !dest.startsWith("/") || dest.startsWith("//")) {
router.push("/admin");
router.push(home());
return;
}
if (router.resolve(dest).name !== "404") {
@@ -52,6 +55,11 @@ function goTo(dest) {
}
}
// Where a signed-in user lands when nothing asked for anywhere in particular.
function home() {
return auth.user.admin ? "/admin" : "/account";
}
async function handleLogin() {
if (submitting.value) return;
submitting.value = true;
@@ -61,7 +69,7 @@ async function handleLogin() {
// `loggedIn` rather than by catching.
await auth.logIn(username.value, password.value);
if (auth.loggedIn) {
goTo(route.query.redirect || "/admin");
goTo(route.query.redirect || home());
} else {
errorMsg.value = "Invalid username or password";
}
@@ -81,7 +89,9 @@ function handleLogout() {
<h1>Already signed in</h1>
<p>You're logged in as <code>{{ auth.user.username }}</code>.</p>
<div class="login-actions">
<Button @click="router.push('/admin')">Open Admin</Button>
<Button @click="router.push(home())">
{{ auth.user.admin ? "Open Admin" : "Your Services" }}
</Button>
<Button @click="handleLogout">Log Out</Button>
</div>
</div>
@@ -91,7 +101,7 @@ function handleLogout() {
<form v-else class="login-card bdr-1" @submit.prevent="handleLogin">
<h1>Login</h1>
<small class="login-hint">
Admin access is required beyond this point.
Sign in to continue.
</small>
<label class="login-field">
+73 -9
View File
@@ -1,25 +1,36 @@
<script setup>
/**
* Admin panel: list users and toggle their admin flag. Mutates the local `user`
* object in place from the mutation's response, so the row updates without a
* refetch. A failed load or toggle is shown above the table rather than only
* logged, and a row's button is disabled while its toggle is in flight.
* Admin panel: list users, toggle their admin flag, and grant non-admins the
* gated services in `permissionTypes` (the receipt printer and so on; see
* backend/services/permissions.go). Mutates the local `user` object in place
* from each mutation's response, so the row updates without a refetch. A
* failed load or change is shown above the table rather than only logged, and
* a row's controls are disabled while a change to it is in flight.
*
* Admins pass every permission check on the server, so their checkboxes are
* replaced with "all" rather than shown with grants that would mean nothing.
* A grant or revoke applies on the user's next request (the gate reads the
* database, not their token), so there is nothing to tell them to do.
*/
import Button from "@/components/input/Button.vue";
import { ref, onMounted } from "vue";
import { useAuthStore } from "@/stores/auth";
import { useAuthStore, USER_FIELDS } from "@/stores/auth";
import { gql } from "@/graphql";
const auth = useAuthStore();
const users = ref([]);
const permissionTypes = ref([]);
const loaded = ref(false);
const error = ref("");
const pending = ref(null);
async function fetchUsers() {
try {
const data = await gql(`query { users { id username admin } }`);
const data = await gql(
`query { users { ${USER_FIELDS} } permissionTypes { key label path } }`,
);
users.value = data.users;
permissionTypes.value = data.permissionTypes;
} catch (err) {
console.error(err);
error.value = err.message || "Couldn't load the users";
@@ -28,12 +39,13 @@ async function fetchUsers() {
}
}
async function toggleAdmin(user) {
// Shared by both kinds of change: one in flight per row, the row replaced
// from the server's answer, failures shown above the table.
async function change(user, mutate) {
error.value = "";
pending.value = user.id;
try {
const data = await auth.setUserAdmin(user.id, !user.admin);
user.admin = data.admin;
Object.assign(user, await mutate());
} catch (err) {
console.error(err);
error.value = err.message || `Couldn't change ${user.username}`;
@@ -42,6 +54,23 @@ async function toggleAdmin(user) {
}
}
function toggleAdmin(user) {
return change(user, () => auth.setUserAdmin(user.id, !user.admin));
}
// The mutation replaces the whole list, so send the row's list with this one
// key flipped. Afterwards the box is set from the row: on a failure the row
// is unchanged, so Vue sees nothing to patch and would leave the box showing
// the click that did not take.
async function togglePermission(user, key, event) {
const current = user.permissions ?? [];
const next = current.includes(key)
? current.filter((k) => k !== key)
: [...current, key];
await change(user, () => auth.setUserPermissions(user.id, next));
event.target.checked = (user.permissions ?? []).includes(key);
}
onMounted(fetchUsers);
</script>
@@ -54,6 +83,25 @@ onMounted(fetchUsers);
<tr v-for="user in users" :key="user.id">
<td class="py-1">{{ user.username }}</td>
<td class="py-1">{{ user.admin ? "admin" : "user" }}</td>
<td class="py-1">
<span v-if="user.admin" class="text-muted">all services</span>
<div v-else class="grants">
<label
v-for="p in permissionTypes"
:key="p.key"
class="grant"
:title="p.path"
>
<input
type="checkbox"
:checked="(user.permissions ?? []).includes(p.key)"
:disabled="pending === user.id"
@change="togglePermission(user, p.key, $event)"
/>
{{ p.label }}
</label>
</div>
</td>
<td class="py-1 text-right">
<span v-if="user.id === auth.user.id" class="text-muted">you</span>
<Button
@@ -69,3 +117,19 @@ onMounted(fetchUsers);
<p v-else-if="!error" class="text-muted">No users.</p>
</div>
</template>
<style scoped>
.grants {
display: flex;
flex-wrap: wrap;
gap: 0.2rem 0.8rem;
}
.grant {
display: inline-flex;
align-items: center;
gap: 0.4rem;
}
.grant input {
width: auto;
}
</style>
@@ -112,7 +112,7 @@ const rows = [
{ y: 76, path: "/admin/login", name: "admin-login", file: "views/admin/Login.vue",
note: "not guarded: calls auth.ensureLoaded() itself for its \"Already signed in\" card" },
{ y: 132, path: "/admin", name: "admin", file: "views/admin/Admin.vue", admin: true,
note: "meta: { requiresAdmin: true }, the only flag the beforeEach guard acts on" },
note: "meta: { requiresAdmin: true }; the beforeEach guard's other flag, requiresSignIn, is on /account" },
{ y: 188, path: "/automata", name: "mobile-automata", file: "views/automata/MobileAutomata.vue",
note: "Turing machine / mobile automaton drawn to a <canvas>" },
{ y: 244, path: "/hotels", name: "cheap-hotels", file: "views/hotels/CheapHotels.vue",