forked from kinotio/gelda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
50 lines (39 loc) · 1.59 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
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { verify } from '@/lib/jsonwebtoken'
import { PATH, TOKEN_NAME, ROLE_BY_NAME } from '@/lib/constants'
const middleware = async (request: NextRequest) => {
const token = request.cookies.get(TOKEN_NAME)?.value as string
const path = request.nextUrl.pathname
if (!token) {
if (path === PATH.HOME || [PATH.SIGNIN, PATH.SIGNUP].includes(path)) {
return NextResponse.next()
}
return NextResponse.redirect(new URL(PATH.SIGNIN, request.url))
}
try {
const { role_id } = await verify(token)
if (path === PATH.SIGNIN || path === PATH.SIGNUP) {
return NextResponse.redirect(new URL(PATH.HOME, request.url))
} else if (role_id === ROLE_BY_NAME.CLIENT) {
if (path.startsWith(PATH.ADMIN)) {
return NextResponse.redirect(new URL(PATH.CLIENT, request.url))
}
return path.startsWith(PATH.CLIENT)
? NextResponse.next()
: NextResponse.redirect(new URL(PATH.CLIENT, request.url))
} else if (role_id === ROLE_BY_NAME.ADMIN) {
if (path.startsWith(PATH.CLIENT)) {
return NextResponse.redirect(new URL(PATH.ADMIN_DASHBOARD, request.url))
}
return path.startsWith(PATH.ADMIN)
? NextResponse.next()
: NextResponse.redirect(new URL(PATH.ADMIN_DASHBOARD, request.url))
}
} catch (error) {
return NextResponse.redirect(new URL(PATH.SIGNIN, request.url))
}
return NextResponse.next()
}
export const config = { matcher: ['/', '/auth/:path*', '/client/:path*', '/admin/:path*'] }
export { middleware }