-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmiddleware.ts
83 lines (75 loc) · 2.44 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
import { authMiddleware, redirectToSignIn } from "@clerk/nextjs";
import {
RequestCookies,
ResponseCookies,
} from "next/dist/compiled/@edge-runtime/cookies";
import { NextRequest, NextResponse } from "next/server";
import { anonAuthMiddleware } from "./lib/anon-auth/anon-auth-middleware";
const authMiddlewareConfig = {
publicRoutes: [
"/",
"/api/webhooks/stripe",
"/api/adventure",
"/sitemap.xml",
"/api/cron/(.*)",
"/api/clerk/webhook",
"/share/quest",
"/_axiom/logs",
"/api/shared/(.*)",
"/api/adventure/create-instance",
"/adventures",
"/play/(.*)",
"/error",
"/play/(.*)/(.*)",
/^\/api\/chat.*$/,
/^\/api\/game\/.*$/,
/^\/api\/agent\/.*$/,
/^\/api\/block\/.*$/,
"/policies/(.*)",
"/adventures/tagged/(.*)",
/^\/adventures\/(?!(create|play|editor))[^\/]*$/,
"/(.*)/opengraph-image",
],
};
// For future: This is a hack to make cookies immediately available on the request object.
function ApplySetCookie(req: NextRequest, res: NextResponse): void {
// parse the outgoing Set-Cookie header
const setCookies = new ResponseCookies(res.headers);
// Build a new Cookie header for the request by adding the setCookies
const newReqHeaders = new Headers(req.headers);
const newReqCookies = new RequestCookies(newReqHeaders);
setCookies.getAll().forEach((cookie) => newReqCookies.set(cookie));
// set “request header overrides” on the outgoing response
NextResponse.next({
request: { headers: newReqHeaders },
}).headers.forEach((value, key) => {
if (
key === "x-middleware-override-headers" ||
key.startsWith("x-middleware-request-")
) {
res.headers.set(key, value);
}
});
}
export default authMiddleware({
...authMiddlewareConfig,
async afterAuth(auth, req, evt) {
const response = await anonAuthMiddleware(req);
let returnBackUrl = new URL(
`${process.env.NEXT_PUBLIC_WEB_BASE_URL}/api/account/post-sign-in`
);
returnBackUrl.searchParams.set("redirectUrl", req.url);
// TODO(ted): See if we cna use the post-sign-in one.
const effectiveReturnBackUrl = req.url; // returnBackUrl.toString()
// Handle users who aren't authenticated
if (!auth.userId && !auth.isPublicRoute) {
return redirectToSignIn({
returnBackUrl: effectiveReturnBackUrl,
});
}
return response;
},
});
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};