Files
adminandClaude Sonnet 4.6 d18d29168a feat(auth): phase 3 — replace Supabase GoTrue with bcryptjs+jose
Custom auth stack: bcryptjs password hashing (cost 10, GoTrue-compatible),
jose JWT session cookies (edge-safe, 8hr TTL), new API routes for
login/logout/reset/change-password, middleware rewritten to JWT-only
verification with no DB access. All 38 protected pages and API routes
migrated from supabase.auth.getUser() to getSession(). Supabase .from()
queries retained for Phase 4. lib/db/index.ts refactored to lazy Proxy
singleton to avoid module-level throw during Next.js build.

tsc: clean, build: clean, tests: 4/4 passed

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-23 16:20:04 +08:00

55 lines
1.6 KiB
TypeScript

import 'server-only'
import { Pool } from 'pg'
import { drizzle } from 'drizzle-orm/node-postgres'
import * as schema from './schema'
function getDb() {
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL not configured')
}
if (!process.env.DATABASE_URL_ADMIN) {
throw new Error('DATABASE_URL_ADMIN not configured')
}
// app_user pool: RLS enforced. Used for all normal user operations.
const userPool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 10,
})
// app_admin pool: BYPASSRLS. Used for admin user CRUD and service operations.
const adminPool = new Pool({
connectionString: process.env.DATABASE_URL_ADMIN,
max: 5,
})
return {
userDb: drizzle(userPool, { schema }),
adminDb: drizzle(adminPool, { schema }),
}
}
// Lazy singleton — pools are created on first access, not at module load time.
// This prevents Next.js build from throwing during static analysis when env vars
// are not present in the build environment.
let _dbs: ReturnType<typeof getDb> | null = null
function dbs() {
if (!_dbs) _dbs = getDb()
return _dbs
}
export const userDb = new Proxy({} as ReturnType<typeof getDb>['userDb'], {
get(_target, prop) {
return (dbs().userDb as unknown as Record<string | symbol, unknown>)[prop]
},
})
export const adminDb = new Proxy({} as ReturnType<typeof getDb>['adminDb'], {
get(_target, prop) {
return (dbs().adminDb as unknown as Record<string | symbol, unknown>)[prop]
},
})
export type UserDb = ReturnType<typeof getDb>['userDb']
export type AdminDb = ReturnType<typeof getDb>['adminDb']