-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
60 lines (47 loc) · 1.5 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
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { JWTPayload } from 'jose'
import { z } from 'zod'
import { verifyToken } from '@lib/auth'
export async function middleware(req: NextRequest) {
const authorization = req.headers.get('Authorization')
if (!authorization) {
return new NextResponse(
JSON.stringify({ success: false, message: 'Authentication failed.' }),
{ status: 400, headers: { 'content-type': 'application/json' } }
)
}
const token = authorization.split(' ')[1]
let payload: JWTPayload
try {
payload = await verifyToken(token)
} catch (error) {
return new NextResponse(
JSON.stringify({ message: 'Invalid access token.' }),
{ status: 401, headers: { 'content-type': 'application/json' } }
)
}
const userScheme = z.object({
name: z.string(),
email: z.string().email(),
avatar_url: z.string().url(),
subscribe: z.boolean(),
})
const parsedUser = userScheme.safeParse(payload)
if (!parsedUser.success) {
return new NextResponse(
JSON.stringify({ message: 'Invalid access token.' }),
{ status: 401, headers: { 'content-type': 'application/json' } }
)
}
const requestHeaders = new Headers(req.headers)
requestHeaders.append('user-data', JSON.stringify(parsedUser.data))
return NextResponse.next({
request: {
headers: requestHeaders,
},
})
}
export const config = {
matcher: '/api/((?!user/create|article|advertisers|feedback).*)',
}