- Runbooks: notes per server/integration, shown next to matching alerts - Backup coverage page across Proxmox and PBS, with a digest section - Hardware inventory with warranty, power and running cost - Authentik group to role mapping with preview and safeguards - /metrics (bearer token) and signed outgoing event webhooks - Docs: README, DATABASE, NOTIFICATIONS, ROLES and new API.md Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
108 lines
4.5 KiB
TypeScript
108 lines
4.5 KiB
TypeScript
import { Router } from "express";
|
|
import { eq, ne, and } from "drizzle-orm";
|
|
import { z } from "zod";
|
|
import { db } from "../db/client.js";
|
|
import { users, userRoles } from "../db/schema.js";
|
|
import { requireAuth, requireRole } from "../auth/middleware.js";
|
|
import { recordAudit } from "../services/audit.js";
|
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
|
import { getSettings } from "../services/settingsStore.js";
|
|
import { roleFromGroups } from "../auth/groups.js";
|
|
|
|
export const usersRouter = Router();
|
|
|
|
usersRouter.use(requireAuth, requireRole("admin"));
|
|
|
|
/** What is stored for a person's groups, as a list. Anything that isn't one is none rather than an error. */
|
|
export function parseGroups(stored: string | null): string[] | null {
|
|
if (!stored) return null;
|
|
try {
|
|
const v = JSON.parse(stored);
|
|
return Array.isArray(v) ? v.filter((g): g is string => typeof g === "string") : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
usersRouter.get("/", asyncHandler(async (_req, res) => {
|
|
const rows = await db.select().from(users).orderBy(users.createdAt);
|
|
const { signIn } = await getSettings();
|
|
res.json({
|
|
users: rows.map((u) => ({ id: u.id, oidcSub: u.oidcSub, email: u.email, name: u.name, role: u.role, createdAt: u.createdAt, lastLoginAt: u.lastLoginAt, groups: parseGroups(u.groups) })),
|
|
// When roles follow groups, a role set by hand would be undone at the next sign-in, so the page says so instead of offering it.
|
|
rolesFollowGroups: signIn.roleFromGroups,
|
|
});
|
|
}));
|
|
|
|
const updateRoleSchema = z.object({
|
|
role: z.enum(userRoles),
|
|
});
|
|
|
|
usersRouter.patch("/:id/role", asyncHandler(async (req, res) => {
|
|
const { signIn } = await getSettings();
|
|
if (signIn.roleFromGroups) {
|
|
return res.status(409).json({ error: "managed_by_groups", message: "Roles are set from sign-in groups (Settings → Sign-in), so a role set here would be undone at the next sign-in. Change the person's group in the identity provider, or switch the group rules off." });
|
|
}
|
|
const id = Number(req.params.id);
|
|
const parsed = updateRoleSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
|
|
}
|
|
|
|
const [target] = await db.select().from(users).where(eq(users.id, id)).limit(1);
|
|
if (!target) {
|
|
return res.status(404).json({ error: "not_found" });
|
|
}
|
|
|
|
if (target.role === "admin" && parsed.data.role !== "admin") {
|
|
const otherAdmins = await db
|
|
.select({ id: users.id })
|
|
.from(users)
|
|
.where(and(eq(users.role, "admin"), ne(users.id, id)))
|
|
.limit(1);
|
|
if (otherAdmins.length === 0) {
|
|
return res.status(400).json({ error: "last_admin", message: "Cannot remove the only admin." });
|
|
}
|
|
}
|
|
|
|
const [updated] = await db
|
|
.update(users)
|
|
.set({ role: parsed.data.role })
|
|
.where(eq(users.id, id))
|
|
.returning();
|
|
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "user",
|
|
action: "update_role",
|
|
targetType: "user",
|
|
targetId: id,
|
|
detail: { from: target.role, to: parsed.data.role, targetLabel: target.name ?? target.email },
|
|
});
|
|
|
|
res.json({ user: updated });
|
|
}));
|
|
|
|
const previewSchema = z.object({
|
|
groupsClaim: z.string().optional(),
|
|
adminGroups: z.array(z.string().trim().min(1).max(100)).max(20).default([]),
|
|
operatorGroups: z.array(z.string().trim().min(1).max(100)).max(20).default([]),
|
|
otherwise: z.enum(["viewer", "keep"]).default("viewer"),
|
|
});
|
|
|
|
// What each person would be, if these group rules were switched on now and they signed in again with the groups they had last time.
|
|
// Nothing is saved or changed: it is for checking the names before relying on them.
|
|
usersRouter.post("/preview-group-roles", asyncHandler(async (req, res) => {
|
|
const parsed = previewSchema.safeParse(req.body);
|
|
if (!parsed.success) return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
|
|
const rows = await db.select().from(users).orderBy(users.name);
|
|
const rules = { roleFromGroups: true, groupsClaim: parsed.data.groupsClaim ?? "groups", adminGroups: parsed.data.adminGroups, operatorGroups: parsed.data.operatorGroups, otherwise: parsed.data.otherwise };
|
|
const people = rows.map((u) => {
|
|
const groups = parseGroups(u.groups);
|
|
return { id: u.id, name: u.name ?? u.email ?? u.oidcSub, role: u.role, groups, wouldBe: groups === null ? null : roleFromGroups(rules, groups, u.role) };
|
|
});
|
|
// Said plainly, because it is the one way to lock yourself out: nobody left with admin.
|
|
const adminsAfter = people.filter((p) => (p.wouldBe ?? p.role) === "admin").length;
|
|
res.json({ people, adminsAfter });
|
|
}));
|