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>
This commit is contained in:
2026-07-23 16:20:04 +08:00
co-authored by Claude Sonnet 4.6
parent a95273b182
commit d18d29168a
67 changed files with 966 additions and 591 deletions
+61
View File
@@ -0,0 +1,61 @@
export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { asAdmin } from '@/lib/db/with-user'
import { users } from '@/lib/db/schema'
import { eq } from 'drizzle-orm'
import { verifyPassword } from '@/lib/auth/password'
import { createSession } from '@/lib/auth/session'
export async function POST(req: NextRequest) {
const { email, password } = await req.json()
if (!email || !password) {
return NextResponse.json({ error: 'Email and password required' }, { status: 400 })
}
const [user] = await asAdmin(db =>
db.select({
id: users.id,
email: users.email,
name: users.name,
role: users.role,
siteId: users.siteId,
passwordHash: users.passwordHash,
active: users.active,
}).from(users).where(eq(users.email, email.toLowerCase())).limit(1)
)
if (!user || !user.active) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 })
}
if (!user.passwordHash) {
return NextResponse.json({ error: 'Account not configured — contact admin' }, { status: 401 })
}
const valid = await verifyPassword(password, user.passwordHash)
if (!valid) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 })
}
// Update last_login_at
await asAdmin(db => db.update(users).set({ lastLoginAt: new Date() }).where(eq(users.id, user.id)))
const token = await createSession({
sub: user.id,
role: user.role,
siteId: user.siteId ?? null,
name: user.name,
})
const appUrl = process.env.APP_URL ?? ''
const res = NextResponse.json({ ok: true })
res.cookies.set('ims_session', token, {
httpOnly: true,
secure: appUrl.startsWith('https'),
sameSite: 'lax',
maxAge: 8 * 60 * 60,
path: '/',
})
return res
}