Record usernames for manual provisioning requests
This commit is contained in:
@@ -2,6 +2,7 @@ import { error, json, redirect, type Handle } from '@sveltejs/kit';
|
||||
import { readSession, readSessionHash, recordAudit, setupRequired } from './index.js';
|
||||
import { authBody, authError, requireSameOrigin, requireUserTransport, sessionCookie } from './http.js';
|
||||
import { roleAllows, routePermission, type RoutePermission } from './access.js';
|
||||
import { withRequestUsername } from './request-context.js';
|
||||
|
||||
function publicAsset(routeId: string | null, path: string, method: string) {
|
||||
return routeId === null && ['GET','HEAD'].includes(method) &&
|
||||
@@ -94,7 +95,7 @@ export const authenticationHandle: Handle = async ({ event, resolve }) => {
|
||||
if (routeId==='/login'&&setup) redirect(303,'/setup');
|
||||
}
|
||||
|
||||
let response = await resolve(event);
|
||||
let response = await withRequestUsername(session?.user.username ?? null, () => resolve(event));
|
||||
if (session && !['GET','HEAD','OPTIONS'].includes(method) && response.status < 400) {
|
||||
recordAudit(session.user.id,'request',routeId,{method,status:response.status,path:event.url.pathname});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
|
||||
const requester = new AsyncLocalStorage<{ username: string | null; active: boolean }>();
|
||||
|
||||
/** Use only the authenticated session, and stop attribution when the request finishes. */
|
||||
export async function withRequestUsername<T>(username: string | null, work: () => T | Promise<T>): Promise<T> {
|
||||
const context = { username, active: true };
|
||||
return requester.run(context, async () => {
|
||||
try { return await work(); }
|
||||
finally { context.active = false; }
|
||||
});
|
||||
}
|
||||
|
||||
export function currentRequestUsername(): string | null {
|
||||
const context = requester.getStore();
|
||||
return context?.active ? context.username : null;
|
||||
}
|
||||
Reference in New Issue
Block a user