Files
ims/middleware.ts
T
adminandClaude Sonnet 4.6 1a813d54f2 fix(middleware): exclude /api/ routes from role-prefix guard
API routes were being redirected for non-admin roles (e.g. capa_owner
calling PATCH /api/capa/[id] got redirected to /capa-owner, breaking
all API calls from role-restricted users).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WMymkhHZiaYZtUeH9MEHZQ
2026-07-22 20:00:27 +08:00

69 lines
2.8 KiB
TypeScript

import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
import { ROLE_HOME, isValidRole, type UserRole } from '@/lib/auth/roles'
export async function middleware(request: NextRequest) {
let supabaseResponse = NextResponse.next({ request })
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() { return request.cookies.getAll() },
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
supabaseResponse = NextResponse.next({ request })
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options),
)
},
},
},
)
const { data: { user } } = await supabase.auth.getUser()
const { pathname } = request.nextUrl
const isPublicRoute = pathname.startsWith('/login') || pathname.startsWith('/auth') || pathname.startsWith('/api/cron') || pathname.startsWith('/api/users') || pathname.startsWith('/forgot-password') || pathname.startsWith('/reset-password')
const isSharedRoute = pathname.startsWith('/report') || pathname.startsWith('/account')
// Use NEXT_PUBLIC_APP_URL to ensure redirects use the public host, not Next.js's internal host
const appBase = process.env.NEXT_PUBLIC_APP_URL?.replace(/\/$/, '')
?? `${request.nextUrl.protocol}//${request.nextUrl.host}${request.nextUrl.basePath ?? ''}`
if (!user && !isPublicRoute) {
return NextResponse.redirect(
`${appBase}/login?redirect=${encodeURIComponent(pathname + request.nextUrl.search)}`
)
}
if (user && (pathname === '/' || pathname === '/login')) {
const redirect = request.nextUrl.searchParams.get('redirect')
if (redirect && redirect.startsWith('/') && !redirect.startsWith('//')) {
return NextResponse.redirect(`${appBase}${redirect}`)
}
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
const role = profile?.role
if (isValidRole(role)) {
return NextResponse.redirect(`${appBase}${ROLE_HOME[role as UserRole]}`)
}
}
if (user && !isPublicRoute && !isSharedRoute && !pathname.startsWith('/api/') && pathname !== '/') {
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
const role = profile?.role
if (isValidRole(role) && role !== 'admin') {
const allowedPrefix = ROLE_HOME[role as UserRole]
if (!pathname.startsWith(allowedPrefix)) {
return NextResponse.redirect(`${appBase}${allowedPrefix}`)
}
}
}
return supabaseResponse
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'],
}