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>
52 lines
2.1 KiB
TypeScript
52 lines
2.1 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { verifySession } from '@/lib/auth/session'
|
|
import { ROLE_HOME, isValidRole } from '@/lib/auth/roles'
|
|
|
|
const PUBLIC_ROUTES = ['/login', '/auth', '/api/cron', '/api/users', '/forgot-password', '/reset-password', '/api/auth']
|
|
const SHARED_ROUTES = ['/report', '/account']
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl
|
|
|
|
const isPublicRoute = PUBLIC_ROUTES.some(r => pathname.startsWith(r))
|
|
const isSharedRoute = SHARED_ROUTES.some(r => pathname.startsWith(r))
|
|
|
|
// Derive appUrl from env or request
|
|
const appUrl = (process.env.APP_URL ?? `${request.nextUrl.protocol}//${request.nextUrl.host}`).replace(/\/$/, '')
|
|
|
|
// Read session from cookie (edge-compatible: jose only, no DB)
|
|
const token = request.cookies.get('ims_session')?.value ?? ''
|
|
const session = token ? await verifySession(token) : null
|
|
|
|
if (!session) {
|
|
if (isPublicRoute) return NextResponse.next()
|
|
const loginUrl = new URL(`${appUrl}/login`)
|
|
loginUrl.searchParams.set('redirect', pathname)
|
|
return NextResponse.redirect(loginUrl)
|
|
}
|
|
|
|
// Authed user on login or root
|
|
if (pathname === '/login' || pathname === '/') {
|
|
const redirectParam = request.nextUrl.searchParams.get('redirect')
|
|
const safeRedirect = redirectParam && redirectParam.startsWith('/') && !redirectParam.startsWith('//') ? redirectParam : null
|
|
const dest = safeRedirect ?? ROLE_HOME[session.role as keyof typeof ROLE_HOME] ?? '/login'
|
|
return NextResponse.redirect(new URL(`${appUrl}${dest}`))
|
|
}
|
|
|
|
if (isSharedRoute || isPublicRoute) return NextResponse.next()
|
|
|
|
// Role-prefix guard (no DB needed — role is in JWT)
|
|
if (!pathname.startsWith('/api/') && isValidRole(session.role) && session.role !== 'admin') {
|
|
const allowedPrefix = ROLE_HOME[session.role as keyof typeof ROLE_HOME]
|
|
if (allowedPrefix && !pathname.startsWith(allowedPrefix)) {
|
|
return NextResponse.redirect(new URL(`${appUrl}${allowedPrefix}`))
|
|
}
|
|
}
|
|
|
|
return NextResponse.next()
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'],
|
|
}
|