@@ -3,24 +3,32 @@ import { NextApiRequest, NextApiResponse } from 'next';
3
3
import prisma from '@/lib/prisma' ;
4
4
import jwt , { JwtPayload } from 'jsonwebtoken' ;
5
5
6
+ // This function is a middleware that adds authorization checks to your Next.js API route.
6
7
export default function withAuthorization ( next : Function ) {
7
8
return async function ( req : NextApiRequest , res : NextApiResponse ) {
8
9
try {
10
+ // Validate the authorization header using the BOT_API_TOKEN.
9
11
validate ( req . headers . authorization ! , process . env . BOT_API_TOKEN ! ) ;
12
+
13
+ // Parse the user data from the authorization header.
10
14
const urlParams = new URLSearchParams ( req . headers . authorization ) ;
11
15
const userData = JSON . parse ( urlParams . get ( 'user' ) ! ) ;
12
16
console . log ( userData . id ) ;
17
+
13
18
if ( req . cookies . token ) {
19
+ // If a token exists in cookies, verify it using the BOT_API_TOKEN.
14
20
const decoded = jwt . verify (
15
21
req . cookies . token ,
16
22
process . env . BOT_API_TOKEN !
17
23
) as JwtPayload ;
18
24
} else {
25
+ // If there's no token in cookies, create a new token and associate it with the user.
19
26
const signToken = jwt . sign (
20
27
{ id : userData . id } ,
21
28
process . env . BOT_API_TOKEN !
22
29
) ;
23
30
31
+ // Check if the user exists in the database, and create if not.
24
32
const user = await prisma . user . findUnique ( {
25
33
where : {
26
34
userId : userData . id . toString ( ) ,
@@ -46,13 +54,17 @@ export default function withAuthorization(next: Function) {
46
54
} ) ;
47
55
}
48
56
57
+ // Set the newly created token in cookies for future requests.
49
58
res . setHeader ( 'Set-Cookie' , `token=${ signToken } ; Path=/; HttpOnly` ) ;
50
59
}
60
+
61
+ // Call the next middleware or API handler with the user's ID.
51
62
next ( req , res , userData . id . toString ( ) ) ;
52
63
} catch ( error ) {
53
64
console . log ( error ) ;
54
65
console . log ( 'Unauthorized user' ) ;
55
66
67
+ // Respond with a 401 Unauthorized status and an error message.
56
68
res . status ( 401 ) . json ( {
57
69
error : 'Unauthorized user' ,
58
70
} ) ;
0 commit comments