feat: add user role types and auth middleware

- lib/auth/roles.ts: UserRole union, ALL_ROLES, ROLE_HOME, getRoleHome, isValidRole (pure, no Supabase imports)
- __tests__/lib/auth/roles.test.ts: 8 TDD tests (written before implementation)
- middleware.ts: createServerClient with request.cookies pattern, unauthenticated redirect to /login, role-based redirect on / and /login

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AWxyMibCuGGtSQSqfajDQ7
This commit is contained in:
2026-07-09 21:39:32 +08:00
co-authored by Claude Sonnet 4.6
parent 9b5b21381f
commit 6939a21183
3 changed files with 132 additions and 0 deletions
+61
View File
@@ -0,0 +1,61 @@
// middleware.ts
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
import { ROLE_HOME, isValidRole, type UserRole } from '@/lib/auth/roles'
export async function middleware(request: NextRequest) {
let supabaseResponse = NextResponse.next({ request })
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
supabaseResponse = NextResponse.next({ request })
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options),
)
},
},
},
)
const {
data: { user },
} = await supabase.auth.getUser()
const { pathname } = request.nextUrl
const isPublicRoute = pathname.startsWith('/login') || pathname.startsWith('/auth')
// Unauthenticated → force login
if (!user && !isPublicRoute) {
return NextResponse.redirect(new URL('/login', request.url))
}
// Authenticated + hitting root or login → redirect to role home
if (user && (pathname === '/' || pathname === '/login')) {
const { data: profile } = await supabase
.from('users')
.select('role')
.eq('id', user.id)
.single()
const role = profile?.role
if (isValidRole(role)) {
return NextResponse.redirect(new URL(ROLE_HOME[role as UserRole], request.url))
}
}
return supabaseResponse
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
],
}