-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
96 lines (69 loc) · 2.49 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { getToken } from 'next-auth/jwt'
import { IUser } from './interfaces';
// export async function middleware(req: NextRequest) {
// const session = await getToken({ req: req, secret: process.env.NEXTAUTH_SECRET });
// if( !session ) {
// if (req.nextUrl.pathname.startsWith('/api/admin')) {
// return NextResponse.redirect(new URL('/api/auth/unauthorized', req.url));
// }
// const requestedPage = req.nextUrl.pathname;
// const url = req.nextUrl.clone();
// url.pathname = `/auth/login`
// url.search = `p=${ requestedPage }`
// return NextResponse.redirect( url );
// }
// const validRoles = ['admin', 'super-user', 'SEO'];
// const user: IUser = session.user as IUser;
// if (req.nextUrl.pathname.startsWith('/admin')) {
// if (!validRoles.includes(user!.role)) {
// const url = req.nextUrl.clone()
// url.pathname = '/'
// return NextResponse.redirect(url)
// }
// }
// if (req.nextUrl.pathname.startsWith('/api/admin')) {
// if (!validRoles.includes(user!.role)) {
// return NextResponse.redirect(new URL('/api/auth/unauthorized', req.url));
// }
// }
// return NextResponse.next();
// }
// // Supports both a single string value or an array of matchers
// export const config = {
// matcher: ['/checkout/:path*', '/admin/:path*', '/api/admin/:path*'],
// }
export async function middleware(req: NextRequest) {
const session = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
if (!session) {
const requestedPage = req.nextUrl.pathname;
const url = req.nextUrl.clone();
url.pathname = `/auth/login`;
url.search = `p=${requestedPage}`;
return NextResponse.redirect(url);
}
if (req.nextUrl.pathname.startsWith('/admin')) {
const validRoles = ['admin','superuser'];
const user: IUser = session.user as IUser;
console.log(user)
if ( !validRoles.includes(user.role) ) {
const requestedPage = req.nextUrl.pathname;
const url = req.nextUrl.clone();
url.pathname = `/`;
return NextResponse.redirect(url);
}
}
return NextResponse.next();
}
// See "Matching Paths" below to learn more
export const config = {
matcher: [
'/checkout/address',
'/checkout/summary',
'/admin',
'/admin/orders',
'/admin/products'
]
};