fastify-xauth-better
auditLog.log(event, data)
Writes a structured audit event to the AuthAuditLog Prisma model.
auditLog.log(event, data)
Writes a structured audit event to the AuthAuditLog table. Event name must be one of the 14 allowed event strings. IP address and user agent are automatically extracted from the request when provided.
Signature
instance.auditLog.log(
event: string,
data?: {
userId?: string
targetId?: string
metadata?: Record<string, unknown>
request?: FastifyRequest
}
): Promise<AuthAuditLog>
Params
| Name | Type | Required | Description |
|---|---|---|---|
event | string | Yes | One of the 14 allowed audit event names (see table below) |
data.userId | string | No | ID of the user performing the action |
data.targetId | string | No | ID of the affected resource or user |
data.metadata | object | No | Arbitrary JSON — stored as Json in Prisma |
data.request | FastifyRequest | No | Fastify request — used to capture IP and user-agent automatically |
Allowed events
| Category | Event |
|---|---|
| Login | auth.login.success, auth.login.failed, auth.logout |
| Password | auth.password.changed, auth.password.reset.requested, auth.password.reset.completed |
| 2FA | auth.2fa.enabled, auth.2fa.disabled |
| Session | auth.session.revoked |
| Account | auth.account.linked, auth.account.banned |
| Organization | auth.org.joined, auth.org.left, auth.org.role.changed |
Returns
Promise<AuthAuditLog> — the created Prisma record.
Throws
Error: Invalid audit event: {event}— the event string is not in the allowed list
Examples
Log a successful login
const userAuth = fastify.xauthbetter.get("user");
fastify.post("/api/login-webhook", async (request) => {
const { userId } = request.body;
await userAuth.auditLog.log("auth.login.success", {
userId,
metadata: { method: "oauth", provider: "google" },
request,
});
return { ok: true };
});
Log an org role change with target user
await userAuth.auditLog.log("auth.org.role.changed", {
userId: request.user.id, // who made the change
targetId: memberId, // who was changed
metadata: {
orgId: request.organization.id,
previousRole: "member",
newRole: "admin",
},
request,
});
See also
- pruneAuditLogs(options) — delete old audit log records
- getSession(request) — resolve user ID without requiring middleware
AI Context
package: "@xenterprises/fastify-xauth-better"
method: fastify.xauthbetter.get(name).auditLog.log(event, data)
use-when: Write a structured audit event to the AuthAuditLog table
events: sign_in, sign_out, sign_up, password_reset, email_verification, org_created, org_updated, org_deleted, member_added, member_removed, role_changed, 2fa_enabled, 2fa_disabled, impersonation_started
