-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.js
87 lines (80 loc) · 2.23 KB
/
middleware.js
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
import { NextResponse } from 'next/server'
import { withAuth } from 'next-auth/middleware'
const { NODE_ENV } = process.env
const getApiAccessRoles = pathname => {
if (
pathname.startsWith('/api/v1/swap/pending')
) {
return ['root']
} else if (
pathname.startsWith('/api/v1/admin/restart')
) {
return ['root', 'admin', 'operator']
} else if (
pathname.startsWith('/api/v1/admin') ||
pathname.startsWith('/api/v1/stats')
) {
return ['root', 'admin']
} else if (
pathname.startsWith('/api/v1/swap/share-with')
) {
return ['root', 'admin', 'lp:']
}
}
const getPageAccessRoles = pathname => {
if (
pathname.startsWith('/pending')
) {
return ['root']
} else if (
pathname.startsWith('/relayer') ||
pathname.startsWith('/premium') ||
pathname.startsWith('/stats') ||
pathname.startsWith('/rules') ||
pathname.startsWith('/banners')
) {
return ['root', 'admin']
} else if (
pathname.startsWith('/lp')
) {
return ['root', 'admin', 'operator']
} else if (
pathname.startsWith('/pool') ||
pathname.startsWith('/swap/share-with')
) {
return ['root', 'admin', 'lp:']
}
}
export const middleware = withAuth(
async function middleware(req) {
if (NODE_ENV !== 'production') {
return
}
if (req.headers.get('x-forwarded-proto') !== 'https') {
return NextResponse.redirect(`https://${req.headers.get('host')}${req.nextUrl.pathname}`)
}
const token = req.nextauth.token
const roles = token?.roles || []
const pathname = req.nextUrl.pathname
if (pathname.startsWith('/api/v1')) {
const apiRoles = getApiAccessRoles(pathname)
if (apiRoles && !apiRoles.some(ar => roles.find(r => r === ar || r.startsWith(ar)))) {
return NextResponse.rewrite(new URL('/api/401', req.url))
}
} else {
const pageRoles = getPageAccessRoles(pathname)
if (pageRoles) {
if (!token) {
return NextResponse.redirect(new URL('/', req.url))
} else if (!pageRoles.some(pr => roles.find(r => r === pr || r.startsWith(pr)))) {
return NextResponse.rewrite(new URL('/unauthorized', req.url))
}
}
}
},
{
callbacks: {
authorized: () => true
}
}
)