chore: move orgRole back to session

This commit is contained in:
Rotimi Best
2026-05-20 15:58:43 +01:00
parent 4e52a618e5
commit cbf1218186
8 changed files with 197 additions and 51 deletions
+19 -2
View File
@@ -6,9 +6,11 @@ import { sendChangeEmailConfirmation, sendVerificationEmail } from './auth/email
import { betterAuth } from 'better-auth/minimal';
import { createProfileHook } from './auth/hooks/create-profile';
import { customSession } from 'better-auth/plugins/custom-session';
import { db } from '@db/drizzle';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { config as emailAndPassword } from './auth/email-password';
import { getUserOrgRolesMap } from './queries/organization/organization';
import { loginLink } from './auth/plugins/login-link';
import { oAuthProxy } from 'better-auth/plugins/oauth-proxy';
import { resolveTrustedBrowserOrigin } from './utils';
@@ -76,7 +78,8 @@ export const auth: ReturnType<typeof betterAuth> = betterAuth({
user: {
create: {
after: async (user, ctx) => {
console.log('[auth] databaseHooks.user.create.after: running', { userId: user.id, ctx });
console.log('[auth] databaseHooks.user.create.after: running', { userId: user.id });
const request =
(ctx as { context?: { request?: Request }; request?: Request } | undefined)?.context?.request ??
(ctx as { request?: Request } | undefined)?.request;
@@ -119,6 +122,20 @@ export const auth: ReturnType<typeof betterAuth> = betterAuth({
productionURL: CONSTANTS.BASE_URL
}),
loginLink(),
tokenExchange()
tokenExchange(),
// Attaches the user's org memberships ({ [orgId]: roleId }) to the session
// so org-scoped middlewares can authorize without a per-request DB query.
// Refreshes when the session cookie cache expires (see session.cookieCache.maxAge).
customSession(async ({ user, session }) => {
let orgRoles: Record<string, number> = {};
try {
if (user?.id) {
orgRoles = await getUserOrgRolesMap(user.id);
}
} catch (error) {
console.error('customSession: failed to load orgRoles', error);
}
return { user, session, orgRoles };
})
]
});