32 lines
1019 B
TypeScript
32 lines
1019 B
TypeScript
import type { Context, Next } from "@wrnexus/core";
|
|
import { getDb, type Db } from "@wrnexus/db";
|
|
import { getAuthzCatalog } from "./client.ts";
|
|
import { dbPermissionStore, ensureAuthzTables } from "./db.ts";
|
|
import { setDefaultAuthzRoleStore } from "./defaults.ts";
|
|
import { authzMiddleware } from "./middleware.ts";
|
|
|
|
const initialized = new WeakMap<Db, Promise<void>>();
|
|
|
|
function initialize(db: Db): Promise<void> {
|
|
let pending = initialized.get(db);
|
|
if (!pending) {
|
|
pending = ensureAuthzTables(db);
|
|
initialized.set(db, pending);
|
|
pending.catch(() => initialized.delete(db));
|
|
}
|
|
return pending;
|
|
}
|
|
|
|
/** Package-installed authorization middleware with lazy database resolution. */
|
|
export default async function frameworkAuthz(ctx: Context, next: Next): Promise<Response> {
|
|
const db = getDb();
|
|
await initialize(db);
|
|
const store = dbPermissionStore(db);
|
|
setDefaultAuthzRoleStore(store);
|
|
return authzMiddleware({
|
|
catalog: getAuthzCatalog(),
|
|
store,
|
|
strict: true,
|
|
})(ctx, next);
|
|
}
|