Become a Pro / website · becomeapro.ai / src / lib / biolock / session-plugin.ts
| 1 | import type { BetterAuthPlugin } from "better-auth"; |
| 2 | import { APIError, createAuthEndpoint } from "better-auth/api"; |
| 3 | import { setSessionCookie } from "better-auth/cookies"; |
| 4 | import * as z from "zod"; |
| 5 | |
| 6 | // Server-only: called after a BioLock check has passed, to create the account (first device) and the session. |
| 7 | export const biolockSessions = () => ({ |
| 8 | id: "biolock", |
| 9 | endpoints: { |
| 10 | biolockStartSession: createAuthEndpoint("/biolock/start-session", { |
| 11 | method: "POST", |
| 12 | body: z.object({ userId: z.string().max(100).optional(), newName: z.string().min(1).max(80).optional() }), |
| 13 | metadata: { SERVER_ONLY: true }, |
| 14 | }, async (ctx) => { |
| 15 | const adapter = ctx.context.internalAdapter; |
| 16 | let user = ctx.body.userId ? await adapter.findUserById(ctx.body.userId) : null; |
| 17 | if (!user && ctx.body.newName) { |
| 18 | const id = crypto.randomUUID(); |
| 19 | user = await adapter.createUser({ |
| 20 | name: ctx.body.newName, |
| 21 | // Accounts have no email. This placeholder only fills the required column and is never contacted. |
| 22 | email: `member-${id}@members.becomeapro.ai`, |
| 23 | emailVerified: false, |
| 24 | }, { method: "email-password" } as Parameters<typeof adapter.createUser>[1]); |
| 25 | } |
| 26 | if (!user) throw new APIError("UNAUTHORIZED", { message: "Account not found." }); |
| 27 | const session = await adapter.createSession(user.id); |
| 28 | if (!session) throw new APIError("UNAUTHORIZED", { message: "Could not start a session." }); |
| 29 | await setSessionCookie(ctx, { session, user }); |
| 30 | return ctx.json({ userId: user.id }); |
| 31 | }), |
| 32 | }, |
| 33 | }) satisfies BetterAuthPlugin; |