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
+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",