fix(auth): add forgot/reset to public routes, use Link for basePath, add session guard
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WMymkhHZiaYZtUeH9MEHZQ
This commit is contained in:
+11
-15
@@ -24,30 +24,28 @@ export async function middleware(request: NextRequest) {
|
||||
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
const { pathname } = request.nextUrl
|
||||
const isPublicRoute = pathname.startsWith('/login') || pathname.startsWith('/auth') || pathname.startsWith('/api/cron')
|
||||
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) {
|
||||
const redirectUrl = request.nextUrl.clone()
|
||||
redirectUrl.pathname = '/login'
|
||||
redirectUrl.searchParams.set('redirect', pathname + request.nextUrl.search)
|
||||
return NextResponse.redirect(redirectUrl)
|
||||
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('//')) {
|
||||
const url = request.nextUrl.clone()
|
||||
url.pathname = redirect
|
||||
url.search = ''
|
||||
return NextResponse.redirect(url)
|
||||
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)) {
|
||||
const url = request.nextUrl.clone()
|
||||
url.pathname = ROLE_HOME[role as UserRole]
|
||||
return NextResponse.redirect(url)
|
||||
return NextResponse.redirect(`${appBase}${ROLE_HOME[role as UserRole]}`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,9 +55,7 @@ export async function middleware(request: NextRequest) {
|
||||
if (isValidRole(role) && role !== 'admin') {
|
||||
const allowedPrefix = ROLE_HOME[role as UserRole]
|
||||
if (!pathname.startsWith(allowedPrefix)) {
|
||||
const url = request.nextUrl.clone()
|
||||
url.pathname = allowedPrefix
|
||||
return NextResponse.redirect(url)
|
||||
return NextResponse.redirect(`${appBase}${allowedPrefix}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user