forked from open-sauced/app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
57 lines (48 loc) · 1.77 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
import { createMiddlewareClient } from "@supabase/auth-helpers-nextjs";
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { pathToRegexp } from "path-to-regexp";
// HACK: this is to get around the fact that the normal next.js middleware is not always functioning
// correctly.
// see https://github.com/open-sauced/insights/pull/1549
// prettier-ignore
const pathsToMatch = [
"/hub/insights/:path*",
"/feed/",
"/user/notifications",
"/user/settings",
"/account-deleted"
];
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
if (!pathsToMatch.some((matcher) => pathToRegexp(matcher).test(req.nextUrl.pathname))) {
return res;
}
// Create authenticated Supabase Client.
const supabase = createMiddlewareClient({ req, res });
// Check if we have a session
const {
data: { session },
} = await supabase.auth.getSession();
if (session?.user && req.nextUrl.pathname === "/account-deleted") {
// Delete the account from Supabase and log the user out.
await supabase.auth.admin.deleteUser(session.user.id);
await supabase.auth.signOut();
return res;
}
// Check auth condition
if (session?.user || req.nextUrl.searchParams.has("login")) {
// Authentication successful, forward request to protected route.
return res;
}
// Auth condition not met, redirect to home page.
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = "/feed";
if (req.nextUrl.pathname === "/feed" && req.nextUrl.searchParams.has("new")) {
redirectUrl.searchParams.set("signIn", "true");
}
redirectUrl.searchParams.set("redirectedFrom", req.nextUrl.pathname);
if (!req.nextUrl.searchParams.has("redirectedFrom")) {
return NextResponse.redirect(redirectUrl);
}
}