-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
46 lines (42 loc) · 1.42 KB
/
middleware.ts
File metadata and controls
46 lines (42 loc) · 1.42 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
// middleware/authMiddleware.ts
import { withAuth } from 'next-auth/middleware'
import { NextResponse } from 'next/server'
export default withAuth(
async function middleware(req) {
if (req.method === 'POST') {
const body = await req.json()
if (req.nextauth.token && body.user_id) {
console.log('Middleware was called: User authenticated')
const { sub } = req.nextauth.token
if (sub && sub === body.user_id) {
console.log('Middleware was called: User ID matches')
return NextResponse.next()
} else {
console.log('Middleware was called: User ID does not match')
return new NextResponse('Forbidden', { status: 403 })
}
} else {
console.log('Middleware was called: User not authenticated')
return new NextResponse('Unauthorized', { status: 401 })
}
} else {
if (req.nextauth.token) {
console.log('Middleware was called: User authenticated')
const { sub } = req.nextauth.token
if (sub) {
req.headers.set('x-user-id', sub)
}
return NextResponse.next()
} else {
console.log('Middleware was called: User not authenticated')
return new NextResponse('Unauthorized', { status: 401 })
}
}
},
{
callbacks: {
authorized: ({ token }) => !!token
},
},
)
export const config = { matcher: ['/api/user/:path*', "/dashboard"] }