-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.ts
71 lines (58 loc) · 2.17 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
import { NextRequest, NextResponse } from 'next/server'
import StoreKeys from './lib/constants/storeKeys'
import userApi from './features/user/user.service'
// Limit the middleware to paths starting with `/api/`
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico|icons|assets|audio).*)',
],
}
const serverApiUrl = 'https://cotuong.azurewebsites.net/api'
const authPaths = ['/signin', '/signup']
const publicPaths = ['/', '/contact']
export async function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname
const inPublicPath = publicPaths.includes(pathname)
console.log(`pathname ${pathname}`, `inPublicPath ${inPublicPath}`)
if (inPublicPath) return NextResponse.next()
const inAuthPath =
authPaths.includes(pathname) || pathname.startsWith('/sign')
console.log(`inAuthPath ${inAuthPath}`)
const userToken = request.cookies.get(StoreKeys.ACCESS_TOKEN)?.value
if (!userToken && inAuthPath) {
return NextResponse.next()
}
if (userToken) {
const onErrorRes = () => {
const nextRes = NextResponse.redirect(
new URL(authPaths.shift() ?? '/', request.url)
)
nextRes.cookies.delete(StoreKeys.ACCESS_TOKEN)
nextRes.cookies.delete(StoreKeys.USER)
return nextRes
}
try {
const res = await fetch(
`${serverApiUrl}/users/check-authorization`,
{
headers: {
Authorization: `Bearer ${userToken}`,
},
}
)
if (!res.ok) {
return onErrorRes()
}
const data = await res.json()
const nextRes = inAuthPath
? NextResponse.redirect(new URL('/', request.url))
: NextResponse.next()
nextRes.cookies.set(StoreKeys.USER, JSON.stringify(data))
return nextRes
} catch (error) {
console.error(error)
return onErrorRes()
}
}
return NextResponse.redirect(new URL(authPaths.shift() ?? '/', request.url))
}