Files
classroomio/packages/db/src/auth.ts
T

152 lines
4.8 KiB
TypeScript
Raw Normal View History

import * as CONSTANTS from './constants';
2025-11-01 15:49:29 +01:00
import * as schema from '@db/schema';
import { admin, anonymous } from 'better-auth/plugins';
import { sendChangeEmailConfirmation, sendVerificationEmail } from './auth/email-verification';
2025-11-01 15:49:29 +01:00
import { betterAuth } from 'better-auth/minimal';
import { createProfileHook } from './auth/hooks/create-profile';
2026-05-20 15:58:43 +01:00
import { customSession } from 'better-auth/plugins/custom-session';
2025-11-01 15:49:29 +01:00
import { db } from '@db/drizzle';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { config as emailAndPassword } from './auth/email-password';
2026-05-20 15:58:43 +01:00
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';
2026-03-09 11:18:22 +01:00
import { sso } from '@better-auth/sso';
import { syncUserWithProfile } from './auth/hooks/sync-user';
2026-03-09 11:18:22 +01:00
import { tokenExchange } from './auth/plugins/token-exchange';
2026-04-27 11:40:38 +01:00
import { trackLoginHook } from './auth/hooks/track-login';
2025-11-01 15:49:29 +01:00
2026-05-20 16:33:11 +01:00
/**
* Cloud (multi-tenant) only. Routes OAuth/SSO callbacks to the canonical
* production URL while completing the flow on whichever tenant host the
* user signed in from (<org>.myclassroomio.com or a BYOD domain).
2026-05-20 16:33:11 +01:00
*
* Self-hosted instances run with one apex (api.<domain> + app.<domain>)
* and use AUTH_COOKIE_DOMAIN for cross-subdomain cookies, so the proxy
* isn't needed there.
*/
function buildOAuthProxyPlugin() {
if (process.env.PUBLIC_IS_SELFHOSTED === 'true') {
return [];
}
return [oAuthProxy({ productionURL: CONSTANTS.BASE_URL })];
}
export const auth: ReturnType<typeof betterAuth> = betterAuth({
baseURL: CONSTANTS.BASE_URL,
2025-11-01 15:49:29 +01:00
database: drizzleAdapter(db, {
provider: 'pg',
schema
// debugLogs: true
2025-11-01 15:49:29 +01:00
}),
emailAndPassword: emailAndPassword,
user: {
changeEmail: {
enabled: true,
sendChangeEmailConfirmation
}
},
emailVerification: {
enabled: true,
sendVerificationEmail
2025-11-01 15:49:29 +01:00
},
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
accessType: 'offline',
prompt: 'select_account consent'
}
},
trustedOrigins: (request) => {
const origins = [...CONSTANTS.TRUSTED_ORIGINS];
const originHeader = request?.headers.get('origin');
const resolved = resolveTrustedBrowserOrigin(originHeader, CONSTANTS.TRUSTED_ORIGINS);
if (resolved && !origins.includes(resolved)) {
origins.push(resolved);
}
return origins;
},
advanced: {
cookiePrefix: 'classroomio',
2026-05-20 16:33:11 +01:00
// Cloud (multi-tenant): host-only cookies on each tenant/BYOD domain.
// Self-hosted: cross-subdomain cookies under AUTH_COOKIE_DOMAIN so the
// session set on `api.<apex>` is also sent to `app.<apex>`.
crossSubDomainCookies: process.env.AUTH_COOKIE_DOMAIN?.trim()
? { enabled: true, domain: process.env.AUTH_COOKIE_DOMAIN.trim() }
: { enabled: false },
database: {
generateId: false
}
},
account: {
storeAccountCookie: true
},
session: {
expiresIn: 60 * 60 * 24 * 30, // 30 days
updateAge: 60 * 60 * 24, // 1 day (every 1 day the session expiration is updated)
cookieCache: {
enabled: true,
maxAge: 60 * 60 // 1 hour
}
},
databaseHooks: {
user: {
create: {
after: async (user) => {
2026-05-20 15:58:43 +01:00
console.log('[auth] databaseHooks.user.create.after: running', { userId: user.id });
await createProfileHook(user);
}
},
update: {
after: async (user) => {
console.log('[auth] databaseHooks.user.update.after: running', { userId: user.id });
await syncUserWithProfile(user);
}
}
2026-04-27 11:40:38 +01:00
},
session: {
create: {
after: async (session) => {
await trackLoginHook(session);
}
},
update: {
after: async (session) => {
await trackLoginHook(session);
}
}
2025-11-01 15:49:29 +01:00
}
},
2026-03-09 11:18:22 +01:00
plugins: [
admin(),
anonymous(),
sso({
// OIDC providers are registered dynamically per organization
// via the admin API (auth.api.registerSSOProvider)
}),
2026-05-20 16:33:11 +01:00
...buildOAuthProxyPlugin(),
loginLink(),
2026-05-20 15:58:43 +01:00
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 };
})
2026-03-09 11:18:22 +01:00
]
2025-11-01 15:49:29 +01:00
});