Files
tabatago/admin-web/middleware.ts
Millian Lamiaux e0057e18e0 feat: implement full authentication system with middleware protection
- Install @supabase/ssr package for server-side auth
- Create middleware.ts for route protection (redirects to login if not authenticated)
- Fix login page admin check to verify specific user ID
- Add AUTH_SETUP.md with complete setup instructions
- Add setup-admin.sql for database configuration
- Logout button already exists in sidebar
2026-03-17 10:59:52 +01:00

57 lines
1.7 KiB
TypeScript

import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
let response = NextResponse.next({
request: {
headers: request.headers,
},
})
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
return request.cookies.get(name)?.value
},
set(name: string, value: string, options: any) {
request.cookies.set({ name, value, ...options })
response = NextResponse.next({
request: { headers: request.headers },
})
response.cookies.set({ name, value, ...options })
},
remove(name: string, options: any) {
request.cookies.set({ name, value: '', ...options })
response = NextResponse.next({
request: { headers: request.headers },
})
response.cookies.set({ name, value: '', ...options })
},
},
}
)
// Check if user is authenticated
const { data: { user } } = await supabase.auth.getUser()
// Protect all routes except /login
if (!user && request.nextUrl.pathname !== '/login') {
return NextResponse.redirect(new URL('/login', request.url))
}
// If user is authenticated and tries to access login, redirect to home
if (user && request.nextUrl.pathname === '/login') {
return NextResponse.redirect(new URL('/', request.url))
}
return response
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
}