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"; import { avatarUrlFor } from "../services/avatars.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, profilePictures } = 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), avatarUrl: avatarUrlFor(u, profilePictures) })), // 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 }); }));