diff --git a/app/lib/auth.ts b/app/lib/auth.ts index 049295a2..93f2333c 100644 --- a/app/lib/auth.ts +++ b/app/lib/auth.ts @@ -14,36 +14,57 @@ import { ensureOnlyOneUser } from "./auth-middlewares/only-one-user"; export type AuthMiddlewareContext = MiddlewareContext>; -export const auth = betterAuth({ - secret: await cryptoUtils.deriveSecret("better-auth"), - hooks: { - before: createAuthMiddleware(async (ctx) => { - await ensureOnlyOneUser(ctx); - await convertLegacyUserOnFirstLogin(ctx); +let _auth: ReturnType | null = null; + +const createAuth = async () => { + if (_auth) return _auth; + + _auth = betterAuth({ + secret: await cryptoUtils.deriveSecret("better-auth"), + hooks: { + before: createAuthMiddleware(async (ctx) => { + await ensureOnlyOneUser(ctx); + await convertLegacyUserOnFirstLogin(ctx); + }), + }, + database: drizzleAdapter(db, { + provider: "sqlite", }), - }, - database: drizzleAdapter(db, { - provider: "sqlite", - }), - emailAndPassword: { - enabled: true, - }, - user: { - modelName: "usersTable", - additionalFields: { - username: { - type: "string", - returned: true, - required: true, - }, - hasDownloadedResticPassword: { - type: "boolean", - returned: true, + emailAndPassword: { + enabled: true, + }, + user: { + modelName: "usersTable", + additionalFields: { + username: { + type: "string", + returned: true, + required: true, + }, + hasDownloadedResticPassword: { + type: "boolean", + returned: true, + }, }, }, + session: { + modelName: "sessionsTable", + }, + plugins: [username({})], + }); + + return _auth; +}; + +export const auth = { + get api() { + if (!_auth) throw new Error("Auth not initialized. Call initAuth() first."); + return _auth.api; }, - session: { - modelName: "sessionsTable", + get handler() { + if (!_auth) throw new Error("Auth not initialized. Call initAuth() first."); + return _auth.handler; }, - plugins: [username({})], -}); +}; + +export const initAuth = createAuth; diff --git a/app/server/modules/lifecycle/startup.ts b/app/server/modules/lifecycle/startup.ts index 9d18aaa4..9b8ccfb6 100644 --- a/app/server/modules/lifecycle/startup.ts +++ b/app/server/modules/lifecycle/startup.ts @@ -50,6 +50,9 @@ export const startup = async () => { logger.error(`Error ensuring restic passfile exists: ${err.message}`); }); + const { initAuth } = await import("~/lib/auth"); + await initAuth(); + await ensureLatestConfigurationSchema(); const volumes = await db.query.volumesTable.findMany({