-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
97 lines (79 loc) · 2.31 KB
/
Copy pathproxy.ts
File metadata and controls
97 lines (79 loc) · 2.31 KB
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
import { NextResponse } from "next/server";
import {
AUTH0_CONNECTION_COOKIE_PREFIX,
AUTH0_LEGACY_SESSION_COOKIE_NAME,
AUTH0_SESSION_COOKIE_NAME,
AUTH0_TRANSACTION_COOKIE_PREFIX,
assertAuth0Config,
auth0,
isRecoverableAuth0SessionError,
} from "@/lib/auth0";
// In Auth0 v4, the proxy handles all auth routes automatically via auth0.middleware()
// The auth routes are at /auth/login, /auth/callback, /auth/logout (not /api/auth/)
const PROTECTED_PATH_PREFIXES = [
"/dashboard",
"/connections",
"/history",
"/settings",
"/api/",
];
function getCookieNames(request: Request) {
const cookieHeader = request.headers.get("cookie");
if (!cookieHeader) {
return [];
}
return cookieHeader
.split(";")
.map((entry) => entry.trim().split("=", 1)[0]?.trim())
.filter((name): name is string => Boolean(name));
}
function getInvalidSessionRedirectTarget(pathname: string) {
const isProtectedPath = PROTECTED_PATH_PREFIXES.some((prefix) =>
pathname.startsWith(prefix)
);
if (isProtectedPath) {
return "/auth/login";
}
return "/";
}
function clearInvalidAuthCookies(response: NextResponse, request: Request) {
const cookieNames = new Set(getCookieNames(request));
cookieNames.add(AUTH0_SESSION_COOKIE_NAME);
cookieNames.add(AUTH0_LEGACY_SESSION_COOKIE_NAME);
for (const cookieName of cookieNames) {
if (
cookieName === AUTH0_SESSION_COOKIE_NAME ||
cookieName === AUTH0_LEGACY_SESSION_COOKIE_NAME ||
cookieName.startsWith(AUTH0_TRANSACTION_COOKIE_PREFIX) ||
cookieName.startsWith(AUTH0_CONNECTION_COOKIE_PREFIX)
) {
response.cookies.set(cookieName, "", {
expires: new Date(0),
path: "/",
});
}
}
}
export async function proxy(request: Request) {
assertAuth0Config();
try {
return await auth0.middleware(request);
} catch (error) {
if (!isRecoverableAuth0SessionError(error)) {
throw error;
}
const url = new URL(request.url);
const redirectUrl = new URL(
getInvalidSessionRedirectTarget(url.pathname),
request.url
);
const response = NextResponse.redirect(redirectUrl);
clearInvalidAuthCookies(response, request);
return response;
}
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
};