-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware.ts
63 lines (57 loc) · 1.64 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
import { NextResponse } from "next/server";
import { jwtVerify, importSPKI } from "jose";
import type { NextRequest } from "next/server";
export const config = {
matcher: "/api/:function*",
};
export async function middleware(req: NextRequest) {
// Get the Dynamic token from the headers
const authToken = req.headers.get("Authorization");
if (!authToken) {
return NextResponse.json(
{ success: false, message: "Missing auth token" },
{
status: 401,
headers: { "Content-Type": "application/json" },
}
);
}
try {
const token = authToken.replace("Bearer ", "");
const key = await importSPKI(
process.env.NEXT_PUBLIC_DYNAMIC_PUBLIC_KEY!.replace(/\\n/g, "\n"),
"RS256"
);
const isAuthenticated = await jwtVerify(token, key);
if (!isAuthenticated) {
// Respond with JSON indicating an error message
return NextResponse.json(
{ success: false, message: "Authentication failed" },
{
status: 401,
headers: { "Content-Type": "application/json" },
}
);
}
// If authentication is successful, continue processing the request
const response = NextResponse.next();
response.headers.set(
"x-username",
isAuthenticated.payload.username as string
);
return response;
} catch (error: any) {
// Handle errors related to token verification or other issues
return NextResponse.json(
{
success: false,
message: "Authentication failed",
error: error.message,
},
{
status: 401,
headers: { "Content-Type": "application/json" },
}
);
}
}