gaurv007 commited on
Commit
9a7656d
·
verified ·
1 Parent(s): b496127

fix: upload actual middleware.ts content (previous commit had file path instead of content)

Browse files
Files changed (1) hide show
  1. web/middleware.ts +76 -1
web/middleware.ts CHANGED
@@ -1 +1,76 @@
1
- file:/app/web_middleware.ts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * ClauseGuard — Next.js Middleware v4.1
3
+ * FIX: This file was MISSING entirely. Without it, the auth guard in proxy.ts
4
+ * never executes, meaning anyone can access /dashboard-pages/* without logging in.
5
+ *
6
+ * This middleware:
7
+ * 1. Refreshes Supabase auth tokens on every request
8
+ * 2. Redirects unauthenticated users away from protected routes
9
+ * 3. Redirects authenticated users away from auth pages
10
+ */
11
+
12
+ import { createServerClient } from "@supabase/ssr";
13
+ import { NextResponse, type NextRequest } from "next/server";
14
+
15
+ export async function middleware(request: NextRequest) {
16
+ let supabaseResponse = NextResponse.next({ request });
17
+
18
+ if (!process.env.NEXT_PUBLIC_SUPABASE_URL || !process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY) {
19
+ return supabaseResponse;
20
+ }
21
+
22
+ const supabase = createServerClient(
23
+ process.env.NEXT_PUBLIC_SUPABASE_URL,
24
+ process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY,
25
+ {
26
+ cookies: {
27
+ getAll() {
28
+ return request.cookies.getAll();
29
+ },
30
+ setAll(cookiesToSet) {
31
+ cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value));
32
+ supabaseResponse = NextResponse.next({ request });
33
+ cookiesToSet.forEach(({ name, value, options }) =>
34
+ supabaseResponse.cookies.set(name, value, options)
35
+ );
36
+ },
37
+ },
38
+ }
39
+ );
40
+
41
+ // MUST await — otherwise auth cookie refresh doesn't work
42
+ const {
43
+ data: { user },
44
+ } = await supabase.auth.getUser();
45
+
46
+ const pathname = request.nextUrl.pathname;
47
+ const isAuthPage =
48
+ pathname.startsWith("/auth/") && !pathname.includes("callback");
49
+ const isDashboard =
50
+ pathname.startsWith("/dashboard-pages") || pathname.startsWith("/admin");
51
+
52
+ // Logged-in user on auth pages → redirect to dashboard
53
+ if (user && isAuthPage) {
54
+ return NextResponse.redirect(
55
+ new URL("/dashboard-pages/dashboard", request.url)
56
+ );
57
+ }
58
+
59
+ // Not logged in on protected pages → redirect to login
60
+ if (!user && isDashboard) {
61
+ const url = request.nextUrl.clone();
62
+ url.pathname = "/auth/login";
63
+ url.searchParams.set("next", pathname);
64
+ return NextResponse.redirect(url);
65
+ }
66
+
67
+ return supabaseResponse;
68
+ }
69
+
70
+ export const config = {
71
+ matcher: [
72
+ "/dashboard-pages/:path*",
73
+ "/auth/:path*",
74
+ "/admin/:path*",
75
+ ],
76
+ };