| import { createServerClient, type CookieOptions } from '@supabase/ssr' |
| import { cookies } from 'next/headers' |
| import { NextResponse } from 'next/server' |
|
|
| export interface AuthResult { |
| authenticated: true |
| userId: string |
| email: string | undefined |
| } |
|
|
| interface AuthError { |
| authenticated: false |
| response: NextResponse |
| } |
|
|
| async function getUserFromBearerToken( |
| supabaseUrl: string, |
| supabaseAnonKey: string, |
| token: string, |
| ) { |
| const response = await fetch(`${supabaseUrl}/auth/v1/user`, { |
| headers: { |
| apikey: supabaseAnonKey, |
| Authorization: `Bearer ${token}`, |
| }, |
| cache: 'no-store', |
| }) |
|
|
| if (!response.ok) { |
| return { data: { user: null }, error: new Error('Invalid bearer token') } |
| } |
|
|
| const user = await response.json() |
| return { data: { user }, error: null } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| export async function requireAuth(request?: Request): Promise<AuthResult | AuthError> { |
| try { |
| const cookieStore = await cookies() |
| const authHeader = request?.headers.get('authorization') ?? null |
|
|
| const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL |
| const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY |
| if (!supabaseUrl || !supabaseAnonKey) { |
| return { |
| authenticated: false as const, |
| response: NextResponse.json( |
| { error: 'Sunucu yapılandırma hatası' }, |
| { status: 500 } |
| ), |
| } |
| } |
|
|
| const supabase = createServerClient( |
| supabaseUrl, |
| supabaseAnonKey, |
| { |
| cookies: { |
| getAll() { |
| return cookieStore.getAll() |
| }, |
| setAll(cookiesToSet: { name: string; value: string; options: CookieOptions }[]) { |
| try { |
| cookiesToSet.forEach(({ name, value, options }) => |
| cookieStore.set(name, value, options) |
| ) |
| } catch { |
| |
| } |
| }, |
| }, |
| } |
| ) |
|
|
| |
| const { data: { user }, error } = await supabase.auth.getUser() |
|
|
| if (user && !error) { |
| return { authenticated: true, userId: user.id, email: user.email } |
| } |
|
|
| |
| if (request) { |
| if (authHeader?.startsWith('Bearer ')) { |
| const token = authHeader.slice(7) |
| const { data: { user: tokenUser }, error: tokenError } = |
| await getUserFromBearerToken(supabaseUrl, supabaseAnonKey, token) |
|
|
| if (tokenUser && !tokenError) { |
| return { authenticated: true, userId: tokenUser.id, email: tokenUser.email } |
| } |
| } |
| } |
|
|
| return { |
| authenticated: false, |
| response: NextResponse.json( |
| { error: 'Kimlik doğrulama gerekli. Lütfen giriş yapın.' }, |
| { status: 401 } |
| ), |
| } |
| } catch { |
| return { |
| authenticated: false, |
| response: NextResponse.json( |
| { error: 'Kimlik doğrulama hatası' }, |
| { status: 401 } |
| ), |
| } |
| } |
| } |
|
|