-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
29 lines (27 loc) · 952 Bytes
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// middleware.ts
import { getToken } from 'next-auth/jwt';
import { NextRequest, NextResponse } from 'next/server';
// paths that require authentication or authorization
const requireAuth: string[] = ['/admin', '/events', '/register', '/profile'];
export async function middleware(request: NextRequest) {
const res = NextResponse.next();
const pathname = request.nextUrl.pathname;
if (requireAuth.some((path) => pathname.startsWith(path))) {
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET,
});
//check not logged in
if (!token) {
const url = new URL(`/api/auth/signin`, request.url);
url.searchParams.set('callbackUrl', encodeURI(request.url));
return NextResponse.redirect(url);
}
//check if not authorized
if (token.role !== 'ADMIN') {
const url = new URL(`/403`, request.url);
return NextResponse.rewrite(url);
}
}
return res;
}