-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
75 lines (63 loc) · 2.31 KB
/
proxy.ts
File metadata and controls
75 lines (63 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { updateSession } from "@/lib/supabase/middleware";
const PUBLIC_PATHS = ["/", "/auth", "/pricing", "/api/webhooks", "/suspended", "/unauthorized"];
export async function proxy(req: NextRequest) {
const response = await updateSession(req);
const { pathname } = req.nextUrl;
if (
pathname === "/" ||
PUBLIC_PATHS.filter((p) => p !== "/").some((p) => pathname.startsWith(p))
) {
return response;
}
if (pathname.startsWith("/dashboard") || pathname.startsWith("/suadmin")) {
const { getSupabaseServer } = await import("@/lib/supabase/server");
const supabase = await getSupabaseServer();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
const url = req.nextUrl.clone();
if (pathname.startsWith("/suadmin")) {
url.pathname = "/auth/login";
url.searchParams.set("next", "/suadmin");
} else {
url.pathname = "/unauthorized";
}
// Re-create redirect with response base if needed, or manually copy cookies
const redirectRes = NextResponse.redirect(url);
response.cookies.getAll().forEach((c) => redirectRes.cookies.set(c.name, c.value, c));
return redirectRes;
}
// Check profile for status & admin role
const { data } = await supabase
.from("profiles")
.select("is_admin, status")
.eq("id", user.id)
.single();
const profile = data as { is_admin: boolean; status: string } | null;
if (profile?.status === "suspended") {
const url = req.nextUrl.clone();
url.pathname = "/suspended";
const redirectRes = NextResponse.redirect(url);
response.cookies.getAll().forEach((c) => redirectRes.cookies.set(c.name, c.value, c));
return redirectRes;
}
if (pathname.startsWith("/suadmin") && profile?.is_admin !== true) {
const url = req.nextUrl.clone();
url.pathname = "/unauthorized";
const redirectRes = NextResponse.redirect(url);
response.cookies.getAll().forEach((c) => redirectRes.cookies.set(c.name, c.value, c));
return redirectRes;
}
}
return response;
}
export const config = {
matcher: [
"/dashboard/:path*",
"/suadmin/:path*",
"/((?!_next/static|_next/image|favicon.ico).*)",
],
};