|
| 1 | +import { createServerClient } from '@supabase/ssr' |
| 2 | +import { NextResponse, type NextRequest } from 'next/server' |
| 3 | + |
| 4 | +/** |
| 5 | + * LMXEngine Middleware |
| 6 | + * Unified security and session management layer. |
| 7 | + */ |
| 8 | +export default async function middleware(request: NextRequest) { |
| 9 | + let response = NextResponse.next({ |
| 10 | + request: { |
| 11 | + headers: request.headers, |
| 12 | + }, |
| 13 | + }) |
| 14 | + |
| 15 | + const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 16 | + const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; |
| 17 | + |
| 18 | + if (!supabaseUrl || !supabaseAnonKey) { |
| 19 | + return response; |
| 20 | + } |
| 21 | + |
| 22 | + const supabase = createServerClient( |
| 23 | + supabaseUrl, |
| 24 | + supabaseAnonKey, |
| 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 | + response = NextResponse.next({ |
| 33 | + request: { |
| 34 | + headers: request.headers, |
| 35 | + }, |
| 36 | + }) |
| 37 | + cookiesToSet.forEach(({ name, value, options }) => |
| 38 | + response.cookies.set(name, value, options) |
| 39 | + ) |
| 40 | + }, |
| 41 | + }, |
| 42 | + } |
| 43 | + ) |
| 44 | + |
| 45 | + // Using getUser() is the secure way to check auth, but we handle the specific "refresh_token_not_found" error. |
| 46 | + const { data: { user }, error } = await supabase.auth.getUser() |
| 47 | + |
| 48 | + // 1. Handle Refresh Token Error / Missing Session |
| 49 | + if (error && error.code === 'refresh_token_not_found') { |
| 50 | + // Clear cookies and bounce to login if trying to access protected routes |
| 51 | + const isProtected = request.nextUrl.pathname.startsWith('/admin') || request.nextUrl.pathname.startsWith('/checkout'); |
| 52 | + if (isProtected) { |
| 53 | + const redirectResponse = NextResponse.redirect(new URL('/login', request.url)) |
| 54 | + // Attempt to clear session cookies |
| 55 | + redirectResponse.cookies.delete('sb-access-token') |
| 56 | + redirectResponse.cookies.delete('sb-refresh-token') |
| 57 | + return redirectResponse |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + // 2. Admin Portal Protection |
| 62 | + if (request.nextUrl.pathname.startsWith('/admin')) { |
| 63 | + if (!user) { |
| 64 | + return NextResponse.redirect(new URL('/login', request.url)) |
| 65 | + } |
| 66 | + |
| 67 | + const { data: profile } = await supabase |
| 68 | + .from('profiles') |
| 69 | + .select('role') |
| 70 | + .eq('id', user.id) |
| 71 | + .single() |
| 72 | + |
| 73 | + if (!profile || profile.role !== 'admin') { |
| 74 | + return NextResponse.redirect(new URL('/', request.url)) |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + // 3. Checkout Flow Protection |
| 79 | + if (request.nextUrl.pathname.startsWith('/checkout')) { |
| 80 | + if (!user) { |
| 81 | + return NextResponse.redirect(new URL(`/login?next=${request.nextUrl.pathname}`, request.url)) |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + // 4. Login Redirect Logic |
| 86 | + if (user && request.nextUrl.pathname.startsWith('/login')) { |
| 87 | + return NextResponse.redirect(new URL('/', request.url)) |
| 88 | + } |
| 89 | + |
| 90 | + // 5. Kill Switch (Store Enabled Check) |
| 91 | + if (!request.nextUrl.pathname.startsWith('/admin') && |
| 92 | + !request.nextUrl.pathname.startsWith('/api') && |
| 93 | + !request.nextUrl.pathname.startsWith('/login') && |
| 94 | + !request.nextUrl.pathname.startsWith('/_next') && |
| 95 | + !request.nextUrl.pathname.startsWith('/maintenance')) { |
| 96 | + |
| 97 | + // Use service role or public check for settings? |
| 98 | + // profiles RLS is based on is_admin(), so for public we need to ensure site_settings is public. |
| 99 | + const { data: settings } = await supabase |
| 100 | + .from('site_settings') |
| 101 | + .select('setting_value') |
| 102 | + .eq('setting_key', 'store_enabled') |
| 103 | + .single(); |
| 104 | + |
| 105 | + if (settings && settings.setting_value === false) { |
| 106 | + return NextResponse.redirect(new URL('/maintenance', request.url)); |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + return response |
| 111 | +} |
| 112 | + |
| 113 | +export const config = { |
| 114 | + matcher: [ |
| 115 | + /* |
| 116 | + * Match all request paths except for the ones starting with: |
| 117 | + * - _next/static (static files) |
| 118 | + * - _next/image (image optimization files) |
| 119 | + * - favicon.ico (favicon file) |
| 120 | + * - api/webhooks (Stripe needs public access) |
| 121 | + */ |
| 122 | + '/((?!_next/static|_next/image|favicon.ico|api/webhooks|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)', |
| 123 | + ], |
| 124 | +} |
0 commit comments