-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
88 lines (77 loc) · 2.45 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
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
const isApiRoute = createRouteMatcher(["/api(.*)"]);
const isAuthRoute = createRouteMatcher(["/(.*)"]);
const isCheckoutApiRoute = createRouteMatcher(["/api/create-checkout-session"]);
const isWebhookRoute = createRouteMatcher([
"/top-up-success",
"/top-up-cancelled",
]);
const isCheckoutRedirectRoute = createRouteMatcher(["/api/checkout-complete"]);
const userManagementMiddleware = () =>
clerkMiddleware(async (auth, req) => {
if (
isWebhookRoute(req) ||
isApiRoute(req) ||
isCheckoutRedirectRoute(req)
) {
return NextResponse.next();
}
if (isCheckoutApiRoute(req) || isAuthRoute(req)) {
auth().protect();
}
return NextResponse.next();
});
const soloApiKeyMiddleware = (req: NextRequest) => {
if (isApiRoute(req)) {
const header = req.headers.get("authorization");
if (!header) {
return new Response("No Authorization header", { status: 401 });
}
const token = header.replace("Bearer ", "");
if (token !== process.env.SOLO_API_KEY) {
return new Response("Unauthorized", { status: 401 });
}
}
return NextResponse.next();
};
export default async function middleware(
req: NextRequest,
event: NextFetchEvent
) {
const res = NextResponse.next();
// Allow all origins
res.headers.set("Access-Control-Allow-Origin", "*");
res.headers.set(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS"
);
res.headers.set(
"Access-Control-Allow-Headers",
"Content-Type, Authorization"
);
if (req.method === "OPTIONS") {
// Handle preflight requests
return new NextResponse(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Max-Age": "86400",
},
});
}
const enableUserManagement = process.env.ENABLE_USER_MANAGEMENT === "true";
const isSoloInstance =
process.env.SOLO_API_KEY && process.env.SOLO_API_KEY.length > 0;
if (enableUserManagement) {
return userManagementMiddleware()(req, event);
} else if (isSoloInstance) {
return soloApiKeyMiddleware(req);
}
return res;
}
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};