createImpersonationManager
createImpersonationManager(
d1,options?):object
Defined in: packages/auth/src/impersonation.ts:118
Creates an impersonation manager backed by a Cloudflare D1 database.
Manages an audit trail of impersonation sessions, allowing admins to temporarily act as another user for debugging and support. Each session is logged with start and end timestamps.
Graceful fallback when the table is missing
Section titled “Graceful fallback when the table is missing”If the impersonation_logs table does not exist yet (e.g. the consumer
upgraded @cfast/auth from 0.2.x to 0.3.x without running the new
migration), getActiveImpersonation() returns null instead of
throwing. This keeps authenticated requests working — they simply
behave as if no admin is impersonating anyone — and logs a one-time
warning pointing the operator at the migration they need to run. See
cfast issue #172.
impersonate() and stopImpersonating() still propagate the underlying
error because silently swallowing a write would pretend an admin is
impersonating someone when the audit row was never recorded.
Parameters
Section titled “Parameters”D1Database
The Cloudflare D1 database binding.
options?
Section titled “options?”ImpersonationManagerOptions
Optional configuration for table and column names.
Returns
Section titled “Returns”object
An object with impersonate, stopImpersonating, and getActiveImpersonation methods.
getActiveImpersonation()
Section titled “getActiveImpersonation()”getActiveImpersonation(
adminUserId):Promise<{targetUserId:string; } |null>
Parameters
Section titled “Parameters”adminUserId
Section titled “adminUserId”string
Returns
Section titled “Returns”Promise<{ targetUserId: string; } | null>
impersonate()
Section titled “impersonate()”impersonate(
adminUserId,targetUserId):Promise<void>
Parameters
Section titled “Parameters”adminUserId
Section titled “adminUserId”string
targetUserId
Section titled “targetUserId”string
Returns
Section titled “Returns”Promise<void>
stopImpersonating()
Section titled “stopImpersonating()”stopImpersonating(
adminUserId):Promise<void>
Parameters
Section titled “Parameters”adminUserId
Section titled “adminUserId”string
Returns
Section titled “Returns”Promise<void>
Example
Section titled “Example”import { createImpersonationManager } from "@cfast/auth";
const impersonation = createImpersonationManager(env.DB);
// Start impersonating a userawait impersonation.impersonate(adminUserId, targetUserId);
// Check if admin is currently impersonating someoneconst active = await impersonation.getActiveImpersonation(adminUserId);// active?.targetUserId
// Stop impersonatingawait impersonation.stopImpersonating(adminUserId);