11import { getToken } from "next-auth/jwt" ;
22import { NextResponse } from "next/server" ;
33import type { NextRequest } from "next/server" ;
4- import { createClient } from "@supabase/supabase-js" ;
54
65export async function middleware ( request : NextRequest ) {
7- const token = await getToken ( {
6+ const token = await getToken ( {
87 req : request ,
98 secret : process . env . NEXTAUTH_SECRET
109 } ) ;
11-
10+
1211 const isAdminRoute = request . nextUrl . pathname . startsWith ( "/admin-dashboard" ) ;
1312 const isDashboardRoute = request . nextUrl . pathname . startsWith ( "/dashboard" ) ;
14-
13+
1514 // Protect dashboard and admin routes
1615 if ( isDashboardRoute || isAdminRoute ) {
1716 // Redirect to sign in if not authenticated
@@ -26,48 +25,21 @@ export async function middleware(request: NextRequest) {
2625 return NextResponse . redirect ( new URL ( "/auth/error" , request . url ) ) ;
2726 }
2827
29- // Check admin status directly from Supabase
30- if ( token . email ) {
31- try {
32- const supabase = createClient (
33- process . env . NEXT_PUBLIC_SUPABASE_URL ! ,
34- process . env . SUPABASE_SERVICE_ROLE_KEY ! ,
35- {
36- auth : {
37- autoRefreshToken : false ,
38- persistSession : false
39- }
40- }
41- ) ;
42-
43- const { data : userData , error } = await supabase
44- . from ( 'users' )
45- . select ( 'is_admin' )
46- . eq ( 'email' , token . email )
47- . single ( ) ;
48-
49- const isAdmin = userData ?. is_admin === 1 ;
50-
51- // Admin-only routes protection
52- if ( isAdminRoute ) {
53- if ( ! isAdmin ) {
54- // Non-admin users trying to access admin dashboard - redirect to regular dashboard
55- return NextResponse . redirect ( new URL ( "/dashboard" , request . url ) ) ;
56- }
57- }
58-
59- // Allow admins to access both /dashboard and /admin-dashboard
60- // No redirect needed for admins accessing regular dashboard
61- } catch ( error ) {
62- console . error ( 'Error checking admin status in middleware:' , error ) ;
63- // If there's an error, allow regular dashboard access but not admin
64- if ( isAdminRoute ) {
65- return NextResponse . redirect ( new URL ( "/dashboard" , request . url ) ) ;
66- }
28+ // Admin-only routes protection
29+ if ( isAdminRoute ) {
30+ // For Cloudflare Pages compatibility, admin check is done client-side
31+ // Middleware only protects the route with authentication
32+ // The page itself will check admin status from the JWT token
33+ if ( ! token . isAdmin ) {
34+ // Non-admin users trying to access admin dashboard - redirect to regular dashboard
35+ return NextResponse . redirect ( new URL ( "/dashboard" , request . url ) ) ;
6736 }
6837 }
38+
39+ // Allow admins to access both /dashboard and /admin-dashboard
40+ // No redirect needed for admins accessing regular dashboard
6941 }
70-
42+
7143 return NextResponse . next ( ) ;
7244}
7345
0 commit comments