-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
107 lines (90 loc) · 2.8 KB
/
middleware.ts
File metadata and controls
107 lines (90 loc) · 2.8 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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
import { NextRequest, NextResponse } from 'next/server'
const BACKEND_URL = process.env.BACKEND_URL
async function refreshAccessToken(refreshToken: string): Promise<{
accessToken?: string
refreshToken?: string
success: boolean
}> {
try {
const response = await fetch(`${BACKEND_URL}/auth/user/refresh_token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ refresh_token: refreshToken }),
})
if (response.ok) {
const data = await response.json()
return {
accessToken: data.access_token,
refreshToken: data.refresh_token,
success: true,
}
}
return { success: false }
} catch (error) {
console.error('Error refreshing token:', error)
return { success: false }
}
}
async function isTokenValid(accessToken: string): Promise<boolean> {
try {
const response = await fetch(`${BACKEND_URL}/auth/user/check_token`, {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ token: accessToken }),
})
return response.ok
} catch (error) {
console.error('Error checking token:', error)
return false
}
}
async function handleTokenRefresh(request: NextRequest): Promise<NextResponse | null> {
const accessToken = request.cookies.get('access_token')?.value
const refreshToken = request.cookies.get('refresh_token')?.value
if (!accessToken || !refreshToken) {
return null
}
const tokenIsValid = await isTokenValid(accessToken)
if (tokenIsValid) {
return null
}
const refreshResult = await refreshAccessToken(refreshToken)
if (refreshResult.success && refreshResult.accessToken) {
const response = NextResponse.next()
const isProduction = process.env.NODE_ENV === 'production'
response.cookies.set('access_token', refreshResult.accessToken, {
httpOnly: true,
secure: isProduction,
sameSite: isProduction ? 'none' : 'lax',
path: '/',
})
if (refreshResult.refreshToken) {
response.cookies.set('refresh_token', refreshResult.refreshToken, {
httpOnly: true,
secure: isProduction,
sameSite: isProduction ? 'none' : 'lax',
path: '/',
})
}
return response
} else {
const response = NextResponse.redirect(new URL('/login', request.url))
response.cookies.delete('access_token')
response.cookies.delete('refresh_token')
return response
}
}
export async function middleware(request: NextRequest) {
const tokenRefreshResponse = await handleTokenRefresh(request)
if (tokenRefreshResponse) {
return tokenRefreshResponse
}
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico|images|.*\\..*).*)'],
}