49 lines
1.3 KiB
TypeScript
49 lines
1.3 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { auth } from '@/lib/auth/config';
|
|
import { NextRequest } from 'next/server';
|
|
|
|
const PROTECTED = ['/main/account', '/shelter/dashboard'];
|
|
const SHELTER_ONLY = ['/shelter/'];
|
|
const ADMIN_ONLY = ['/admin/'];
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl;
|
|
const session = await auth();
|
|
|
|
const needsAuth = PROTECTED.some((p) => pathname.startsWith(p));
|
|
if (needsAuth && !session) {
|
|
const loginUrl = new URL('/auth/login', request.url);
|
|
loginUrl.searchParams.set('callbackUrl', pathname);
|
|
return NextResponse.redirect(loginUrl);
|
|
}
|
|
|
|
const role = (session?.user as { role?: string })?.role;
|
|
|
|
if (SHELTER_ONLY.some((p) => pathname.startsWith(p))) {
|
|
if (!session || (role !== 'SHELTER_ADMIN' && role !== 'ADMIN')) {
|
|
return NextResponse.redirect(new URL('/', request.url));
|
|
}
|
|
}
|
|
|
|
if (ADMIN_ONLY.some((p) => pathname.startsWith(p))) {
|
|
if (!session || role !== 'ADMIN') {
|
|
return NextResponse.redirect(new URL('/', request.url));
|
|
}
|
|
}
|
|
|
|
if (session && pathname.startsWith('/auth/')) {
|
|
return NextResponse.redirect(new URL('/', request.url));
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: [
|
|
'/main/account/:path*',
|
|
'/shelter/:path*',
|
|
'/admin/:path*',
|
|
'/auth/:path*',
|
|
],
|
|
};
|