-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
228 lines (195 loc) · 7.66 KB
/
Copy pathmiddleware.ts
File metadata and controls
228 lines (195 loc) · 7.66 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { routing } from "./apps/i18n/routing";
const IS_DEVELOPMENT = process.env.NODE_ENV === "development";
type Locale = (typeof routing.locales)[number];
/* -------------------------------------------------------------------------- *
* Domain ↔ route group mapping
* -------------------------------------------------------------------------- */
type DomainGroup = "sso" | "console" | "main";
const SSO_HOSTS = ["sso.zenthcloud.com", "sso.zenthcloud.lan"];
const CONSOLE_HOSTS = ["console.zenthcloud.com", "console.zenthcloud.lan"];
const MAIN_HOSTS = ["zenthcloud.com", "zenthcloud.lan", "www.zenthcloud.com"];
const AUTH_PATHS = [
"/login",
"/register",
"/profile-change",
"/mfa-validate",
"/mfa-setup",
"/mfa-verify",
"/mfa-recovery",
"/mfa-recovery-setup",
"/mfa-recovery-verify",
];
const PLATFORM_PATHS = ["/dash"];
function detectGroup(host: string): DomainGroup {
const hostname = host.split(":")[0];
if (SSO_HOSTS.includes(hostname)) return "sso";
if (CONSOLE_HOSTS.includes(hostname)) return "console";
return "main";
}
function getDomainForGroup(group: DomainGroup, currentUrl: URL): string {
const hostname = currentUrl.hostname;
const protocol = currentUrl.protocol;
if (IS_DEVELOPMENT) {
switch (group) {
case "sso":
return `${protocol}//sso.zenthcloud.localhost`;
case "console":
return `${protocol}//console.zenthcloud.localhost`;
case "main":
return `${protocol}//zenthcloud.localhost`;
}
}
switch (group) {
case "sso":
return `${protocol}//sso.zenthcloud.com`;
case "console":
return `${protocol}//console.zenthcloud.com`;
case "main":
return `${protocol}//${hostname}`;
}
}
function belongsToGroup(pathname: string, group: DomainGroup): boolean {
switch (group) {
case "sso":
return AUTH_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"));
case "console":
return PLATFORM_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"));
case "main":
return true;
}
}
function getTargetGroup(pathname: string): DomainGroup | null {
if (AUTH_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"))) return "sso";
if (PLATFORM_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"))) return "console";
return null;
}
/* -------------------------------------------------------------------------- *
* Locale helpers
* -------------------------------------------------------------------------- */
const countryToLocale: Record<string, Locale> = { FR: "fr", EN: "en" };
function getCountryFromRequest(request: NextRequest): string | null {
return (
request.headers.get("cf-ipcountry") ||
request.headers.get("x-vercel-ip-country") ||
request.headers.get("x-fastly-geo-country") ||
null
);
}
function getLocaleFromCountry(country: string | null): Locale {
if (country && country in countryToLocale) return countryToLocale[country];
return routing.defaultLocale;
}
function isValidLocale(segment: string): segment is Locale {
return routing.locales.includes(segment as Locale);
}
/* -------------------------------------------------------------------------- *
* Auth helpers
* -------------------------------------------------------------------------- */
const REFRESH_COOKIE = "zenthcloud_refresh";
const ACCESS_TOKEN_COOKIE = "zenthcloud_access_token";
function isAuthCookiePresent(request: NextRequest): boolean {
const refresh = request.cookies.get(REFRESH_COOKIE);
const access = request.cookies.get(ACCESS_TOKEN_COOKIE);
return Boolean(
(refresh?.value && refresh.value.length > 0) || (access?.value && access.value.length > 0)
);
}
function getAccessToken(request: NextRequest): string | null {
return request.cookies.get(ACCESS_TOKEN_COOKIE)?.value || null;
}
function hasAdminAccess(request: NextRequest): boolean {
try {
const token = getAccessToken(request);
if (!token) return false;
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
const roles: string[] = payload.roles || [];
return roles.includes("admin") || roles.includes("superadmin") || roles.includes("owner");
} catch {
return false;
}
}
/* -------------------------------------------------------------------------- *
* Middleware entry
* -------------------------------------------------------------------------- */
export default function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const host = request.headers.get("host") || request.nextUrl.hostname;
const currentGroup = detectGroup(host);
/* ---- Root path ---- */
if (pathname === "/" || pathname === "") {
switch (currentGroup) {
case "sso":
return NextResponse.redirect(new URL("/login", request.url));
case "console":
return NextResponse.redirect(new URL("/dash", request.url));
case "main":
default: {
if (isAuthCookiePresent(request)) {
return NextResponse.redirect(new URL("/profile-change", request.url));
}
const locale = getLocaleFromCountry(getCountryFromRequest(request));
return NextResponse.redirect(new URL(`/${locale}/discover`, request.url));
}
}
}
/* ---- Cross-domain routing ---- */
const targetGroup = getTargetGroup(pathname);
if (targetGroup && targetGroup !== currentGroup) {
return NextResponse.redirect(
new URL(pathname, getDomainForGroup(targetGroup, request.nextUrl))
);
}
/* ---- SSO domain: only auth routes ---- */
if (currentGroup === "sso") {
return NextResponse.next();
}
/* ---- Console domain: only platform routes ---- */
if (currentGroup === "console") {
if (PLATFORM_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"))) {
if (IS_DEVELOPMENT) return NextResponse.next();
if (isAuthCookiePresent(request) && hasAdminAccess(request)) return NextResponse.next();
return NextResponse.redirect(new URL("/dash", request.url));
}
return NextResponse.redirect(new URL("/dash", request.url));
}
/* ---- Main domain: public routes ---- */
const segments = pathname.split("/").filter(Boolean);
const firstSegment = segments[0];
if (firstSegment && isValidLocale(firstSegment)) {
const localePath = `/${firstSegment}`;
if (
AUTH_PATHS.some((p) => pathname.startsWith(localePath + p) || pathname === localePath + p)
) {
const cleanPath = pathname.replace(localePath, "");
return NextResponse.redirect(new URL(cleanPath || "/", request.url));
}
if (
PLATFORM_PATHS.some((p) => pathname.startsWith(localePath + p) || pathname === localePath + p)
) {
const cleanPath = pathname.replace(localePath, "");
return NextResponse.redirect(new URL(cleanPath || "/", request.url));
}
return NextResponse.next();
}
if (firstSegment && !isValidLocale(firstSegment)) {
if (AUTH_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"))) {
return NextResponse.next();
}
if (PLATFORM_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"))) {
return NextResponse.next();
}
const locale = getLocaleFromCountry(getCountryFromRequest(request));
// Preserve the original query string (e.g. `?ep=<episodeId>` on watch
// links) — `new URL(path, base)` would silently drop it, sending users
// to the wrong episode after the locale redirect.
const url = request.nextUrl.clone();
url.pathname = `/${locale}${pathname}`;
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|.*\\..*|health).*)"],
};