fix(admin): RLS 재귀 수정 + OAuth 쿠키 + 코드 정리

- RLS: profiles 재귀 참조 → app_metadata 기반으로 교체
- auth callback: 쿠키를 response에 직접 설정 (세션 유지)
- middleware: Supabase 세션 갱신 추가
- layout: requireAdmin() 사용으로 통합 (중복 제거)
- admin-guard: app_metadata.role 기반 (JWT, DB 쿼리 불필요)
- debug 라우트 제거
- config.toml: localhost:3000/3001 redirect URL 추가
This commit is contained in:
윤찬 2026-04-12 20:52:56 +09:00
parent 46673ee941
commit eb4c504fea
7 changed files with 142 additions and 53 deletions

View file

@ -1,5 +1,5 @@
// apps/admin/src/app/(admin)/layout.tsx
// Admin 인증 가드 + Sidebar 레이아웃
// Admin 레이아웃 — requireAdmin() 가드 + Sidebar
import { Box } from '@mui/material'
import { requireAdmin } from '@/lib/admin-guard'

View file

@ -1,42 +1,46 @@
// apps/admin/src/app/auth/callback/route.ts
// OAuth 콜백 핸들러
// OAuth 콜백 — code를 session으로 교환
import { NextResponse, type NextRequest } from 'next/server'
import { createServerClient, type CookieOptions } from '@supabase/ssr'
import type { Database } from '@d3ro/api-client'
export async function GET(request: NextRequest): Promise<NextResponse> {
const { searchParams, origin } = new URL(request.url)
const code = searchParams.get('code')
if (code) {
const supabase = createServerClient<Database>(
process.env.NEXT_PUBLIC_SUPABASE_URL ?? '',
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',
{
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookiesToSet: Array<{ name: string; value: string; options: CookieOptions }>) {
cookiesToSet.forEach(({ name, value, options }) => {
request.cookies.set({ name, value, ...options })
})
},
},
}
)
const { error } = await supabase.auth.exchangeCodeForSession(code)
if (!error) {
const response = NextResponse.redirect(`${origin}/`)
// 세션 쿠키를 응답에 복사
request.cookies.getAll().forEach((cookie) => {
response.cookies.set(cookie.name, cookie.value)
})
return response
}
if (!code) {
return NextResponse.redirect(`${origin}/login?error=no_code`)
}
return NextResponse.redirect(`${origin}/login`)
// 쿠키를 수집할 배열
const cookiesToSet: Array<{ name: string; value: string; options: CookieOptions }> = []
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL ?? '',
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',
{
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookies) {
cookiesToSet.push(...cookies)
},
},
}
)
const { error } = await supabase.auth.exchangeCodeForSession(code)
if (error) {
return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(error.message)}`)
}
// 세션 교환 성공 후 response 생성 + 수집된 쿠키 적용
const response = NextResponse.redirect(`${origin}/`)
for (const { name, value, options } of cookiesToSet) {
response.cookies.set({ name, value, ...options })
}
return response
}

View file

@ -1,5 +1,5 @@
// apps/admin/src/lib/admin-guard.ts
// RSC용 admin 가드 — profile.role='admin' 체크
// RSC용 admin 가드 — app_metadata.role='admin' 체크
import { redirect } from 'next/navigation'
import { getSupabaseServerClient } from './supabase-server'
@ -18,32 +18,22 @@ export async function requireAdmin(): Promise<AdminUser> {
redirect('/login')
}
// role은 DB 타입에 미정의이므로 raw 캐스팅
const { data: profile } = await supabase
.from('profiles')
.select('id, name')
.eq('id', user.id)
.maybeSingle()
if (!profile) {
redirect('/login')
}
// role 별도 조회 (DB 타입에 role 컬럼 미정의)
const { data: roleData } = await supabase
.from('profiles')
.select('role' as 'id')
.eq('id', user.id)
.maybeSingle()
const role = (roleData as unknown as { role: string } | null)?.role
// app_metadata.role 체크 (JWT에 포함, RLS 재귀 없음)
const role = (user.app_metadata as Record<string, unknown>)?.role as string | undefined
if (role !== 'admin') {
redirect('/unauthorized')
}
// profile 이름 조회 (자기 자신은 기존 RLS로 접근 가능)
const { data: profile } = await supabase
.from('profiles')
.select('name')
.eq('id', user.id)
.maybeSingle()
return {
id: user.id,
email: user.email ?? null,
name: (profile as { name: string | null }).name,
name: (profile as { name: string | null } | null)?.name ?? null,
}
}

View file

@ -0,0 +1,37 @@
// apps/admin/src/middleware.ts
// Supabase 세션 갱신 미들웨어 — 모든 요청에서 쿠키 기반 세션을 갱신
import { NextResponse, type NextRequest } from 'next/server'
import { createServerClient, type CookieOptions } from '@supabase/ssr'
export async function middleware(request: NextRequest): Promise<NextResponse> {
const response = NextResponse.next({ request: { headers: request.headers } })
const url = process.env.NEXT_PUBLIC_SUPABASE_URL
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
if (!url || !key) return response
const supabase = createServerClient(url, key, {
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookiesToSet: Array<{ name: string; value: string; options: CookieOptions }>) {
cookiesToSet.forEach(({ name, value, options }) => {
request.cookies.set({ name, value, ...options })
response.cookies.set({ name, value, ...options })
})
},
},
})
// 세션 갱신 (토큰 리프레시)
await supabase.auth.getUser()
return response
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}