-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.ts
97 lines (87 loc) · 2.8 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
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
import { NextResponse, NextRequest } from "next/server";
import { verifyAuthToken } from "./lib/privy";
import { Receiver } from "@upstash/qstash";
export const config = {
matcher: "/api/:function*",
};
export async function middleware(req: NextRequest) {
if (req.url.includes("/api/public/")) {
// If the request is for a public endpoint, continue processing the request
return NextResponse.next();
}
if (req.url.includes("/api/users") && req.method === "POST") {
// If the request is for the user creation endpoint, continue processing the request
return NextResponse.next();
}
if (req.url.includes("/api/payment-links/") && req.url.includes("/verify")) {
// If the request is for the payment link verification endpoint, continue processing the request
return NextResponse.next();
}
if (req.url.includes("/api/qstash/")) {
// If the request is for a QStash endpoint, check the signature
const receiver = new Receiver({
currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY!,
nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY!,
});
const signature = req.headers.get("Upstash-Signature")!;
const body = await req.text();
try {
await receiver.verify({
body,
signature,
});
} catch (error) {
return NextResponse.json(
{ success: false, message: `Invalid signature: ${error}` },
{
status: 401,
headers: { "Content-Type": "application/json" },
}
);
}
return NextResponse.next();
}
// Get the Privy 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 { isValid, user } = await verifyAuthToken(token);
if (!isValid) {
// 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();
// privy embedded wallet address
const address = user?.wallet?.address.toLowerCase();
response.headers.set("x-address", address!);
return response;
} catch (error) {
// Handle errors related to token verification or other issues
return NextResponse.json(
{
success: false,
message: "Authentication failed",
},
{
status: 401,
headers: { "Content-Type": "application/json" },
}
);
}
}