Add read-only admin impersonation
Admins (with 2FA) can view the site as a non-admin user for up to 30 minutes, with a required reason and a "Viewing as" banner. It is strictly read-only: a guard mounted before every route refuses any write made with an impersonation token, protect/optionalAuth check the session is live, and GET handlers skip the price-refresh writes. Start, end, reason and every page/API call (including blocked attempts) are audited; optional email to the user. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CP62L9JxHomA36aYP1ekCe
This commit is contained in:
@@ -30,6 +30,8 @@ const ACTIONS = [
|
||||
"scan_lock_force_released",
|
||||
"offline_sync",
|
||||
"ticket_transferred",
|
||||
"impersonation_started",
|
||||
"impersonation_ended",
|
||||
] as const;
|
||||
|
||||
const ACTION_LABELS: Record<string, string> = {
|
||||
@@ -54,6 +56,8 @@ const ACTION_LABELS: Record<string, string> = {
|
||||
scan_lock_force_released: "Offline lock force-released",
|
||||
offline_sync: "Offline scans synced",
|
||||
ticket_transferred: "Ticket transferred",
|
||||
impersonation_started: "Impersonation started",
|
||||
impersonation_ended: "Impersonation ended",
|
||||
};
|
||||
|
||||
interface AuditLogEntry {
|
||||
@@ -81,6 +85,49 @@ function formatMetadata(metadata: Record<string, unknown> | null): string {
|
||||
}
|
||||
}
|
||||
|
||||
type ImpSession = {
|
||||
id: string; reason: string; startedAt: string; expiresAt: string; endedAt: string | null; endedReason: string | null;
|
||||
admin: { name: string; email: string }; target: { name: string; email: string };
|
||||
requests: { method: string; path: string; blocked: boolean; createdAt: string }[];
|
||||
};
|
||||
|
||||
/** "View as" sessions, each with the trail of pages and API calls made during it. */
|
||||
function ImpersonationSessions({ token }: { token: string }) {
|
||||
const [sessions, setSessions] = useState<ImpSession[]>([]);
|
||||
const [open, setOpen] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
apiFetch<ImpSession[]>("/api/admin/impersonation-sessions?limit=20", { authToken: token }).then(setSessions).catch(() => setSessions([]));
|
||||
}, [token]);
|
||||
if (sessions.length === 0) return null;
|
||||
return (
|
||||
<div className="border rounded-xl bg-white shadow-sm p-4 mb-4">
|
||||
<div className="font-semibold mb-2">Impersonation sessions</div>
|
||||
<ul className="divide-y text-sm">
|
||||
{sessions.map(s => (
|
||||
<li key={s.id} className="py-2">
|
||||
<button className="w-full text-left flex flex-wrap items-baseline justify-between gap-2" onClick={() => setOpen(open === s.id ? null : s.id)}>
|
||||
<span><strong>{s.admin.name}</strong> viewed as <strong>{s.target.name}</strong> — “{s.reason}”</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{new Date(s.startedAt).toLocaleString()} · {s.endedAt ? `${s.endedReason || "ended"} ${new Date(s.endedAt).toLocaleTimeString()}` : new Date(s.expiresAt) > new Date() ? "active" : "expired"} · {s.requests.length} request(s){s.requests.some(r => r.blocked) ? ` · ${s.requests.filter(r => r.blocked).length} blocked` : ""}
|
||||
</span>
|
||||
</button>
|
||||
{open === s.id && (
|
||||
<ul className="mt-2 text-xs font-mono bg-gray-50 rounded p-2 max-h-64 overflow-auto space-y-0.5">
|
||||
{s.requests.map((r, i) => (
|
||||
<li key={i} className={r.blocked ? "text-red-700" : "text-gray-700"}>
|
||||
{new Date(r.createdAt).toLocaleTimeString()} {r.method} {r.path}{r.blocked ? " (blocked — read-only)" : ""}
|
||||
</li>
|
||||
))}
|
||||
{s.requests.length === 0 && <li className="text-gray-500">No requests recorded.</li>}
|
||||
</ul>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminAuditLogPage() {
|
||||
const { user, loading, token } = useAuth();
|
||||
const router = useRouter();
|
||||
@@ -148,6 +195,7 @@ export default function AdminAuditLogPage() {
|
||||
You need admin access to view the audit log.
|
||||
</div>
|
||||
)}
|
||||
{isAdmin && token && <ImpersonationSessions token={token} />}
|
||||
|
||||
{error && <div className="mb-3 p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
|
||||
|
||||
|
||||
@@ -137,6 +137,7 @@ function SiteSettingsPageInner() {
|
||||
const [legalWebsiteUrl, setLegalWebsiteUrl] = useState("");
|
||||
const [legalEffectiveDate, setLegalEffectiveDate] = useState("");
|
||||
const [consentRetentionDays, setConsentRetentionDays] = useState("30");
|
||||
const [notifyOnImpersonation, setNotifyOnImpersonation] = useState(false);
|
||||
|
||||
// ── Load all settings once ────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
@@ -173,6 +174,7 @@ function SiteSettingsPageInner() {
|
||||
setLegalWebsiteUrl(s.legal_website_url || "");
|
||||
setLegalEffectiveDate(s.legal_effective_date || "");
|
||||
setConsentRetentionDays(s.consent_medical_retention_days || "30");
|
||||
setNotifyOnImpersonation(s.notify_user_on_impersonation === "true");
|
||||
})
|
||||
.catch((e: any) => setResult({ ok: false, message: e?.message || "Failed to load settings" }))
|
||||
.finally(() => setLoadingInitial(false));
|
||||
@@ -322,6 +324,7 @@ function SiteSettingsPageInner() {
|
||||
legal_website_url: legalWebsiteUrl.trim(),
|
||||
legal_effective_date: legalEffectiveDate.trim(),
|
||||
consent_medical_retention_days: String(Math.max(0, parseInt(consentRetentionDays, 10) || 0)),
|
||||
notify_user_on_impersonation: notifyOnImpersonation ? "true" : "false",
|
||||
});
|
||||
|
||||
const handleTestSmtp = async () => {
|
||||
@@ -670,6 +673,14 @@ function SiteSettingsPageInner() {
|
||||
<p className="text-xs text-gray-500 mt-1">Collected on parental consent forms. The consent record itself (who agreed, and when) is kept.</p>
|
||||
</div>
|
||||
|
||||
<div className="border-t pt-4">
|
||||
<p className="text-sm font-medium text-gray-700 mb-3">Support access</p>
|
||||
<label className="flex items-start gap-2 text-sm cursor-pointer">
|
||||
<input type="checkbox" className="mt-0.5" checked={notifyOnImpersonation} onChange={e => setNotifyOnImpersonation(e.target.checked)} />
|
||||
<span>Email a user when an admin views their account with "Impersonate" (read-only support access), including the reason given</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<SaveBar saving={saving} onSave={saveLegal} result={result} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useAuth } from "@/hooks/useAuth";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { beginImpersonation } from "@/lib/impersonation";
|
||||
import { Users as UsersIcon } from "lucide-react";
|
||||
import { RoleBadge, type Role as RoleBadgeRole } from "@/components/shared/RoleBadge";
|
||||
|
||||
@@ -187,6 +188,23 @@ export default function AdminUsersPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const [impTarget, setImpTarget] = useState<{ id: string; name: string } | null>(null);
|
||||
const [impReason, setImpReason] = useState("");
|
||||
const [impBusy, setImpBusy] = useState(false);
|
||||
const [impError, setImpError] = useState<string | null>(null);
|
||||
const startImpersonation = async () => {
|
||||
if (!impTarget || !token) return;
|
||||
setImpBusy(true);
|
||||
setImpError(null);
|
||||
try {
|
||||
const res = await apiFetch<any>(`/api/admin/impersonate/${encodeURIComponent(impTarget.id)}`, { method: "POST", authToken: token, body: { reason: impReason } });
|
||||
beginImpersonation(res);
|
||||
} catch (e: any) {
|
||||
setImpError(e?.message || "Couldn't start impersonation");
|
||||
setImpBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const resetTwoFactor = async (id: string, name: string, role: string) => {
|
||||
// Admins and supervisors can't go without 2FA: a reset just makes them set it up
|
||||
// again (on a channel that works) at their next login.
|
||||
@@ -222,6 +240,24 @@ export default function AdminUsersPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const impersonateModal = impTarget && (
|
||||
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50" onClick={() => !impBusy && setImpTarget(null)}>
|
||||
<div className="bg-white rounded-xl shadow-lg max-w-md w-full mx-4 p-5 space-y-3" onClick={e => e.stopPropagation()}>
|
||||
<h3 className="text-lg font-semibold">View as {impTarget.name}</h3>
|
||||
<p className="text-sm text-gray-600">You'll see the site exactly as they do, for up to 30 minutes. It's strictly read-only: nothing can be registered, paid, changed or sent. The session, your reason and every page you open are recorded in the audit log.</p>
|
||||
<div>
|
||||
<label className="block text-xs text-gray-600 mb-1">Reason (required)</label>
|
||||
<textarea className="w-full border rounded-lg px-3 py-2 text-sm" rows={2} value={impReason} onChange={e => setImpReason(e.target.value)} placeholder="e.g. Says their ticket isn't showing in My Events" maxLength={500} autoFocus />
|
||||
</div>
|
||||
{impError && <div className="p-2 rounded bg-red-50 text-red-800 text-sm">{impError}</div>}
|
||||
<div className="flex justify-end gap-2">
|
||||
<button className="px-3 py-1.5 text-sm rounded bg-gray-100 hover:bg-gray-200" onClick={() => setImpTarget(null)} disabled={impBusy}>Cancel</button>
|
||||
<button className="px-3 py-1.5 text-sm rounded bg-violet-600 text-white hover:bg-violet-700 disabled:opacity-50" onClick={startImpersonation} disabled={impBusy || impReason.trim().length < 5}>{impBusy ? "Starting…" : "Start viewing"}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto w-full p-6">
|
||||
<div className="flex items-center justify-between mb-4 flex-wrap gap-3">
|
||||
@@ -367,6 +403,9 @@ export default function AdminUsersPage() {
|
||||
<td className="p-2">
|
||||
<div className="flex gap-1 flex-wrap">
|
||||
<button className="px-2 py-1 text-xs rounded bg-gray-100 hover:bg-gray-200" onClick={() => startEdit(u)}>Edit</button>
|
||||
{user?.role === "admin" && u.role !== "admin" && u.isActive && (
|
||||
<button className="px-2 py-1 text-xs rounded bg-violet-600 text-white hover:bg-violet-700" onClick={() => { setImpTarget({ id: u.id, name: u.name }); setImpReason(""); setImpError(null); }} title="See the site exactly as this user sees it (read-only, 30 minutes, audited)">Impersonate</button>
|
||||
)}
|
||||
<button className="px-2 py-1 text-xs rounded bg-amber-500 text-white hover:bg-amber-600" onClick={() => revokeUserSessions(u.id, u.name)} title="Force this user to sign in again on every device where they're currently logged in">Sign out everywhere</button>
|
||||
{u.twoFactorEnabled && (
|
||||
<button className="px-2 py-1 text-xs rounded bg-amber-500 text-white hover:bg-amber-600" onClick={() => resetTwoFactor(u.id, u.name, u.role)} title={u.role === "admin" || u.role === "supervisor" ? "Reset two-factor authentication — they set it up again at their next login" : "Turn off two-factor authentication for a user who can no longer receive their codes"}>Reset 2FA</button>
|
||||
@@ -498,6 +537,7 @@ export default function AdminUsersPage() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{impersonateModal}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { BannerBar } from "@/components/shared/BannerBar";
|
||||
import { SetupGuard } from "@/components/shared/SetupGuard";
|
||||
import HelpFab from "@/components/shared/HelpFab";
|
||||
import { CookieConsent } from "@/components/shared/CookieConsent";
|
||||
import { ImpersonationBanner } from "@/components/shared/ImpersonationBanner";
|
||||
import { API_BASE, resolveToApiOrigin } from "@/lib/api";
|
||||
import { buildThemeCssVars } from "@/lib/colorScale";
|
||||
import { appUrl } from "@/lib/siteConfig";
|
||||
@@ -94,6 +95,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
<AuthProvider>
|
||||
<ToastProvider>
|
||||
<SetupGuard />
|
||||
<ImpersonationBanner />
|
||||
<BannerBar />
|
||||
{children}
|
||||
<HelpFab />
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Eye } from "lucide-react";
|
||||
import { currentImpersonation, endImpersonation, logImpersonatedPage, type Impersonation } from "@/lib/impersonation";
|
||||
|
||||
/** Bright bar on every page while an admin is viewing the site as someone else. */
|
||||
export function ImpersonationBanner() {
|
||||
const pathname = usePathname();
|
||||
const [imp, setImp] = useState<Impersonation | null>(null);
|
||||
const [left, setLeft] = useState("");
|
||||
const [ending, setEnding] = useState(false);
|
||||
|
||||
useEffect(() => { setImp(currentImpersonation()); }, []);
|
||||
|
||||
// Every page viewed goes into the session's audit trail.
|
||||
useEffect(() => {
|
||||
if (imp && pathname) logImpersonatedPage(pathname + (typeof window !== "undefined" ? window.location.search : ""));
|
||||
}, [imp, pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!imp) return;
|
||||
const tick = () => {
|
||||
const ms = new Date(imp.expiresAt).getTime() - Date.now();
|
||||
if (ms <= 0) { endImpersonation(); return; }
|
||||
const m = Math.floor(ms / 60000), s = Math.floor((ms % 60000) / 1000);
|
||||
setLeft(`${m}:${String(s).padStart(2, "0")}`);
|
||||
};
|
||||
tick();
|
||||
const t = setInterval(tick, 1000);
|
||||
return () => clearInterval(t);
|
||||
}, [imp]);
|
||||
|
||||
if (!imp) return null;
|
||||
return (
|
||||
<div className="sticky top-0 z-[60] bg-amber-400 text-amber-950 px-4 py-2 text-sm flex flex-wrap items-center justify-center gap-x-3 gap-y-1 shadow" role="status">
|
||||
<Eye className="w-4 h-4 shrink-0" />
|
||||
<span><strong>Viewing as {imp.name}</strong> ({imp.email}) — read-only, nothing can be changed.</span>
|
||||
<span className="tabular-nums">{left} left</span>
|
||||
<button
|
||||
onClick={() => { setEnding(true); endImpersonation(); }}
|
||||
disabled={ending}
|
||||
className="px-2.5 py-1 rounded bg-amber-950 text-amber-50 text-xs font-medium hover:bg-black disabled:opacity-60"
|
||||
>
|
||||
{ending ? "Ending…" : "End impersonation"}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from "react";
|
||||
import { Users, UserPlus, ShieldAlert } from "lucide-react";
|
||||
import { Users, UserPlus, ShieldAlert, Eye } from "lucide-react";
|
||||
import { GuideItem } from "@/components/shared/GuideItem";
|
||||
import type { HelpContent } from "./types";
|
||||
|
||||
@@ -30,6 +30,9 @@ export const dashboardAdminUsersHelpContent: HelpContent = {
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-4">
|
||||
<GuideItem icon={Eye} title="Impersonate" tone="violet">
|
||||
See the site exactly as a user does, to help with a problem ("my ticket isn't showing"). Give a reason. A bright banner shows while you're viewing, for up to 30 minutes. It's strictly read-only: nothing can be registered, paid, changed or sent. The reason and every page you open are recorded in the audit log. You need two-factor authentication on, and admins can't be impersonated. Optionally, users get an email when this happens (Site Settings → Legal → Support access).
|
||||
</GuideItem>
|
||||
<GuideItem icon={Users} title="Sign out everywhere" tone="amber">
|
||||
Revokes all of that user's active sessions — useful if a device was lost or access needs to be cut immediately.
|
||||
</GuideItem>
|
||||
|
||||
@@ -36,6 +36,7 @@ export function setConsent(v: "accepted" | "declined") {
|
||||
export function analyticsSessionId(): string | undefined {
|
||||
if (getConsent() !== "accepted") return undefined;
|
||||
try {
|
||||
if (localStorage.getItem("hope_events_impersonation")) return undefined;
|
||||
let id = localStorage.getItem(SESSION_KEY);
|
||||
if (!id) {
|
||||
id = crypto.randomUUID();
|
||||
|
||||
@@ -119,6 +119,11 @@ export async function apiFetch<T = any>(path: string, options: ApiOptions = {}):
|
||||
} catch { /* not JSON — use raw text */ }
|
||||
// An admin/supervisor session from before 2FA was required for their role:
|
||||
// end it and send them to log in, where they enrol.
|
||||
// The admin's "view as" session ended or expired: put their own session back.
|
||||
if (res.status === 401 && data?.code === "IMPERSONATION_ENDED" && typeof window !== "undefined") {
|
||||
const { restoreAdmin } = await import("@/lib/impersonation");
|
||||
restoreAdmin();
|
||||
}
|
||||
if (res.status === 401 && data?.code === "TWO_FACTOR_REQUIRED" && typeof window !== "undefined") {
|
||||
localStorage.removeItem("hope_events_token");
|
||||
localStorage.removeItem("hope_events_user_cache");
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Admin "view as user". The admin's own token (and cached profile) are put aside while
|
||||
* the impersonation token is the active one, and restored when it ends. Everything is
|
||||
* read-only on the server (any write is refused), so this is only about which token the
|
||||
* browser sends.
|
||||
*/
|
||||
import { API_BASE } from "@/lib/api";
|
||||
|
||||
const TOKEN_KEY = "hope_events_token";
|
||||
const USER_CACHE_KEY = "hope_events_user_cache";
|
||||
const ADMIN_TOKEN_KEY = "hope_events_admin_token";
|
||||
const ADMIN_CACHE_KEY = "hope_events_admin_user_cache";
|
||||
const IMP_KEY = "hope_events_impersonation";
|
||||
|
||||
export type Impersonation = { sessionId: string; expiresAt: string; name: string; email: string };
|
||||
|
||||
export function currentImpersonation(): Impersonation | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(IMP_KEY);
|
||||
return raw ? JSON.parse(raw) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const isImpersonating = () => !!currentImpersonation();
|
||||
|
||||
/** Switches this browser to the impersonation token and opens the user's dashboard. */
|
||||
export function beginImpersonation(res: { token: string; session: { id: string; expiresAt: string; target: { name: string; email: string } } }) {
|
||||
try {
|
||||
localStorage.setItem(ADMIN_TOKEN_KEY, localStorage.getItem(TOKEN_KEY) || "");
|
||||
localStorage.setItem(ADMIN_CACHE_KEY, localStorage.getItem(USER_CACHE_KEY) || "");
|
||||
localStorage.setItem(TOKEN_KEY, res.token);
|
||||
localStorage.removeItem(USER_CACHE_KEY);
|
||||
localStorage.setItem(IMP_KEY, JSON.stringify({ sessionId: res.session.id, expiresAt: res.session.expiresAt, name: res.session.target.name, email: res.session.target.email }));
|
||||
} catch { /* storage unavailable */ }
|
||||
window.location.href = "/dashboard/user";
|
||||
}
|
||||
|
||||
/** Puts the admin's own session back (no server call). */
|
||||
export function restoreAdmin(redirect = true) {
|
||||
try {
|
||||
const adminToken = localStorage.getItem(ADMIN_TOKEN_KEY);
|
||||
const adminCache = localStorage.getItem(ADMIN_CACHE_KEY);
|
||||
if (adminToken) localStorage.setItem(TOKEN_KEY, adminToken); else localStorage.removeItem(TOKEN_KEY);
|
||||
if (adminCache) localStorage.setItem(USER_CACHE_KEY, adminCache); else localStorage.removeItem(USER_CACHE_KEY);
|
||||
localStorage.removeItem(ADMIN_TOKEN_KEY);
|
||||
localStorage.removeItem(ADMIN_CACHE_KEY);
|
||||
localStorage.removeItem(IMP_KEY);
|
||||
} catch { /* storage unavailable */ }
|
||||
if (redirect) window.location.href = "/dashboard/admin/users";
|
||||
}
|
||||
|
||||
/** Ends the session on the server (audited), then restores the admin. */
|
||||
export async function endImpersonation() {
|
||||
try {
|
||||
const token = localStorage.getItem(TOKEN_KEY);
|
||||
if (token) await fetch(`${API_BASE}/api/admin/impersonate/end`, { method: "POST", headers: { Authorization: `Bearer ${token}` } });
|
||||
} catch { /* the session expires by itself anyway */ }
|
||||
restoreAdmin();
|
||||
}
|
||||
|
||||
/** Records a page view in the session's audit trail. */
|
||||
export function logImpersonatedPage(path: string) {
|
||||
try {
|
||||
const token = localStorage.getItem(TOKEN_KEY);
|
||||
if (!token) return;
|
||||
fetch(`${API_BASE}/api/admin/impersonate/log`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, body: JSON.stringify({ path }), keepalive: true }).catch(() => {});
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
Reference in New Issue
Block a user