import { betterAuth } from "better-auth"; import { customSession, genericOAuth } from "better-auth/plugins"; function firstString(...values: unknown[]) { return values.find( (value): value is string => typeof value === "string" && value.length > 0, ); } function netIdFromEmail(email: unknown) { const value = firstString(email); if (!value?.toLowerCase().endsWith("@byu.edu")) return undefined; const [netId] = value.split("@"); return netId && netId !== "undefined" ? netId : undefined; } function netIdFromProfile(profile: Record) { return ( firstString( profile.net_id, profile.netId, profile.netid, profile.preferred_username, profile.username, ) ?? netIdFromEmail(profile.email) ); } function withNetId>(user: T) { const netId = firstString(user.netId) ?? netIdFromEmail(user.email); return netId ? { ...user, netId } : user; } const additionalUserFields = { // Generic OAuth only persists mapped profile fields that are accepted as input. firstName: { type: "string", input: true, }, lastName: { type: "string", input: true, }, expiresAt: { type: "number", input: false, }, byuId: { type: "string", input: true, }, netId: { type: "string", input: true, }, } as const; export const auth = betterAuth({ plugins: [ genericOAuth({ config: [ { providerId: "byu-pkce", clientId: process.env.BETTER_AUTH_CLIENT_ID ?? "", discoveryUrl: "https://api.byu.edu/.well-known/openid-configuration", pkce: true, overrideUserInfo: true, mapProfileToUser: (profile) => { const netId = netIdFromProfile(profile); return { name: firstString(profile.display_name, profile.name), firstName: firstString( profile.preferred_first_name, profile.given_name, ), lastName: firstString(profile.surname, profile.family_name), netId, byuId: firstString(profile.byu_id, profile.byuId), email: firstString(profile.email) ?? (netId ? `${netId}@byu.edu` : undefined), }; }, }, ], }), customSession( async ({ user, session }) => ({ session, user: withNetId(user), }), { user: { additionalFields: additionalUserFields } }, ), ], user: { additionalFields: additionalUserFields, }, session: { expiresIn: 60 * 60, updateAge: 60 * 60, cookieCache: { enabled: true, maxAge: 60 * 60, version: "net-id-v1", refreshCache: { updateAge: 60, }, }, }, });