feat: sessão #3 — lib (db/auth/email/validations), API routes, NextAuth v5, middleware, páginas account/shelters/shelter-dashboard, Prisma v7 fix
This commit is contained in:
48
middleware.ts
Normal file
48
middleware.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
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*',
|
||||
],
|
||||
};
|
||||
Reference in New Issue
Block a user