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:
@@ -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