|
1 | 1 | import createServerAuth from '#auth/server' |
2 | | -import { useRuntimeConfig } from '#imports' |
| 2 | +import { useEvent, useRuntimeConfig } from '#imports' |
3 | 3 | import { betterAuth } from 'better-auth' |
4 | 4 | import { drizzleAdapter } from 'better-auth/adapters/drizzle' |
| 5 | +import { getRequestURL } from 'h3' |
5 | 6 | import { db, schema } from 'hub:db' |
6 | 7 |
|
7 | 8 | type AuthInstance = ReturnType<typeof betterAuth> |
8 | 9 | let _auth: AuthInstance | undefined |
9 | 10 |
|
| 11 | +function getBaseURL(siteUrl?: string): string { |
| 12 | + if (siteUrl) |
| 13 | + return siteUrl |
| 14 | + |
| 15 | + // Fallback: detect from current request |
| 16 | + try { |
| 17 | + const event = useEvent() |
| 18 | + return getRequestURL(event).origin |
| 19 | + } |
| 20 | + catch { |
| 21 | + return '' |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +let _kv: typeof import('hub:kv').kv | undefined |
| 26 | + |
| 27 | +async function getKV() { |
| 28 | + if (!_kv) { |
| 29 | + const { kv } = await import('hub:kv') |
| 30 | + _kv = kv |
| 31 | + } |
| 32 | + return _kv |
| 33 | +} |
| 34 | + |
| 35 | +function createSecondaryStorage() { |
| 36 | + return { |
| 37 | + get: async (key: string) => (await getKV()).get(`_auth:${key}`), |
| 38 | + set: async (key: string, value: unknown, ttl?: number) => (await getKV()).set(`_auth:${key}`, value, { ttl }), |
| 39 | + delete: async (key: string) => (await getKV()).del(`_auth:${key}`), |
| 40 | + } |
| 41 | +} |
| 42 | + |
10 | 43 | export function serverAuth(): AuthInstance { |
11 | 44 | if (_auth) |
12 | 45 | return _auth |
13 | 46 |
|
14 | 47 | const runtimeConfig = useRuntimeConfig() |
| 48 | + const authConfig = runtimeConfig.auth as { secondaryStorage?: boolean } | undefined |
15 | 49 |
|
16 | 50 | // User's config function receives context with db |
17 | 51 | const userConfig = createServerAuth({ runtimeConfig, db }) |
18 | 52 |
|
19 | 53 | _auth = betterAuth({ |
20 | 54 | ...userConfig, |
21 | 55 | database: drizzleAdapter(db, { provider: 'sqlite', schema }), |
| 56 | + secondaryStorage: authConfig?.secondaryStorage ? createSecondaryStorage() : undefined, |
22 | 57 | secret: runtimeConfig.betterAuthSecret, |
23 | | - baseURL: runtimeConfig.public.siteUrl, |
| 58 | + baseURL: getBaseURL(runtimeConfig.public.siteUrl as string | undefined), |
24 | 59 | }) |
25 | 60 |
|
26 | 61 | return _auth |
|
0 commit comments