forked from CamiloCortesM/RexBuy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
48 lines (40 loc) · 1.26 KB
/
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { NextResponse, type NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';
import { PERMISSION_ROLES } from './constants';
const createUnauthorizedResponse = () => {
return new Response(JSON.stringify({ message: 'Not authorized' }), {
status: 401,
headers: {
'Content-Type': 'application/json',
},
});
};
const redirectTo = (url: string, req: NextRequest) => {
const finalUrl = new URL(url, req.nextUrl.origin);
return NextResponse.redirect(finalUrl);
};
export async function middleware(req: NextRequest) {
const previousPage = req.nextUrl.pathname;
const session: any = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET,
});
if (!session) {
if (previousPage.startsWith('/api/admin'))
return createUnauthorizedResponse();
return redirectTo('/auth/login?p=' + previousPage, req);
}
if (
(previousPage.startsWith('/admin') ||
previousPage.startsWith('/api/admin')) &&
!PERMISSION_ROLES.includes(session.user.role)
) {
if (previousPage.startsWith('/api/admin'))
return createUnauthorizedResponse();
return redirectTo('/', req);
}
return NextResponse.next();
}
export const config = {
matcher: ['/checkout/:path*', '/admin/:path*', '/api/admin/:path*'],
};