-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.js
More file actions
48 lines (45 loc) · 1.47 KB
/
middleware.js
File metadata and controls
48 lines (45 loc) · 1.47 KB
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 { withAuth } from 'next-auth/middleware';
import { NextResponse } from 'next/server';
const Response = {
ADMIN: (req) => {
const { origin, pathname } = req.nextUrl;
return NextResponse.rewrite(new URL(pathname, origin));
},
TEMAN: (req) => {
const { origin, pathname } = req.nextUrl;
if (pathname.startsWith('/dashboard/teman')) {
return NextResponse.rewrite(new URL(pathname, origin));
}
return NextResponse.rewrite(new URL('/dashboard/teman', origin));
},
USER: (req) => {
const { origin, pathname } = req.nextUrl;
if (pathname.startsWith('/dashboard/user')) {
return NextResponse.rewrite(new URL(pathname, origin));
}
return NextResponse.rewrite(new URL('/dashboard/user', origin));
},
};
export default withAuth(
(req) => {
// console.log(req.nextauth.token);
const { role } = req.nextauth.token;
const { pathname, origin } = req.nextUrl;
if (pathname === '/dashboard') {
return NextResponse.redirect(
`${origin}${pathname}/${role.toLowerCase()}`,
);
}
try {
return Response[role.toUpperCase()](req);
} catch (error) {
return NextResponse.rewrite(new URL('/', origin));
}
},
{
callbacks: {
authorized: ({ token }) => !!token,
},
},
);
export const config = { matcher: ['/dashboard/:path*'] };