forked from openstatusHQ/openstatus
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
203 lines (189 loc) · 5.93 KB
/
Copy pathmiddleware.ts
File metadata and controls
203 lines (189 loc) · 5.93 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
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { authMiddleware, redirectToSignIn } from "@clerk/nextjs";
import { db, eq } from "@openstatus/db";
import {
monitor,
user,
usersToWorkspaces,
workspace,
} from "@openstatus/db/src/schema";
import { createI18nMiddleware } from 'next-international/middleware'
import { env } from "./env";
const I18nMiddleware = createI18nMiddleware({
locales: ['en', 'es', 'fr', 'de'],
defaultLocale: 'en',
urlMappingStrategy: 'rewriteDefault'
})
const before = (req: NextRequest) => {
const url = req.nextUrl.clone();
if (url.pathname.includes("api/trpc")) {
return NextResponse.next();
}
const host = req.headers.get("host");
const subdomain = getValidSubdomain(host);
if (subdomain) {
// Subdomain available, rewriting
console.log(
`>>> Rewriting: ${url.pathname} to /status-page/${subdomain}${url.pathname}`,
);
url.pathname = `/status-page/${subdomain}${url.pathname}`;
return NextResponse.rewrite(url);
}
return NextResponse.next();
};
export const getValidSubdomain = (host?: string | null) => {
let subdomain: string | null = null;
if (!host && typeof window !== "undefined") {
// On client side, get the host from window
host = window.location.host;
}
// we should improve here for custom vercel deploy page
if (host && host.includes(".") && !host.includes(".vercel.app")) {
const candidate = host.split(".")[0];
if (candidate && !candidate.includes("www")) {
// Valid candidate
subdomain = candidate;
}
}
if (host && host.includes("ngrok-free.app")) {
return null;
}
// In case the host is a custom domain
if (
host &&
!(host?.includes(env.NEXT_PUBLIC_URL) || host?.endsWith(".vercel.app"))
) {
subdomain = host;
}
return subdomain;
};
export default authMiddleware({
publicRoutes: [
"/",
"/play",
"/play/(.*)",
"/monitor/(.*)",
"/api/(.*)",
"/api/webhook/clerk",
"/api/checker/regions/(.*)",
"/api/checker/cron/10m",
"/blog",
"/blog/(.*)",
"/changelog",
"/changelog/(.*)",
"/legal/(.*)",
"/discord",
"/github",
"/oss-friends",
"/status-page/(.*)",
"/incidents", // used when trying subdomain slug via status.documenso.com/incidents
],
ignoredRoutes: ["/api/og", "/discord", "github", "/status-page/(.*)"], // FIXME: we should check the `publicRoutes`
beforeAuth: before,
debug: false,
async afterAuth(auth, req) {
const host = req.headers.get("host");
const subdomain = getValidSubdomain(host);
if (subdomain || req.nextUrl.pathname.includes('/status-page/')) {
return I18nMiddleware(req)
}
// handle users who aren't authenticated
if (!auth.userId && !auth.isPublicRoute) {
return redirectToSignIn({ returnBackUrl: req.url });
}
// redirect them to organization selection page
if (
auth.userId &&
(req.nextUrl.pathname === "/app" || req.nextUrl.pathname === "/app/")
) {
console.log('>>> Redirecting to "/app/workspace"');
// improve on sign-up if the webhook has not been triggered yet
const userQuery = db
.select()
.from(user)
.where(eq(user.tenantId, auth.userId))
.as("userQuery");
const result = await db
.select()
.from(usersToWorkspaces)
.innerJoin(userQuery, eq(userQuery.id, usersToWorkspaces.userId))
.all();
if (result.length > 0) {
console.log(">>> User has workspace");
const currentWorkspace = await db
.select()
.from(workspace)
.where(eq(workspace.id, result[0].users_to_workspaces.workspaceId))
.get();
if (currentWorkspace) {
const firstMonitor = await db
.select()
.from(monitor)
.where(eq(monitor.workspaceId, currentWorkspace.id))
.get();
if (!firstMonitor) {
console.log(`>>> Redirecting to onboarding`);
const onboarding = new URL(
`/app/onboarding?workspaceSlug=${currentWorkspace.slug}`,
req.url,
);
return NextResponse.redirect(onboarding);
}
const orgSelection = new URL(
`/app/${currentWorkspace.slug}/monitors`,
req.url,
);
console.log(`>>> Redirecting to ${orgSelection}`);
return NextResponse.redirect(orgSelection);
}
} else {
console.log("redirecting to onboarding");
// return NextResponse.redirect(new URL("/app/onboarding", req.url));
// probably redirect to onboarding
// or find a way to wait for the webhook
}
console.log("redirecting to onboarding");
return;
}
if (
auth.userId &&
req.nextUrl.pathname === "/app/integrations/vercel/configure"
) {
const userQuery = db
.select()
.from(user)
.where(eq(user.tenantId, auth.userId))
.as("userQuery");
const result = await db
.select()
.from(usersToWorkspaces)
.innerJoin(userQuery, eq(userQuery.id, usersToWorkspaces.userId))
.all();
if (result.length > 0) {
const currentWorkspace = await db
.select()
.from(workspace)
.where(eq(workspace.id, result[0].users_to_workspaces.workspaceId))
.get();
if (currentWorkspace) {
const configure = new URL(
`/app/${currentWorkspace.slug}/integrations/vercel/configure`,
req.url,
);
return NextResponse.redirect(configure);
}
}
}
},
});
export const config = {
matcher: [
"/((?!api|assets|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
"/",
"/app/integrations/vercel/configure",
"/(api/webhook|api/trpc)(.*)",
"/(!api/checker/:path*|!api/og|!api/ping)",
"/api/analytics", // used for tracking vercel beta integration click events
],
};