| 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 |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| export async function requireAuth(request?: Request): Promise<AuthResult | AuthError> { |
| try { |
| const cookieStore = await cookies() |
|
|
| 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) { |
| const authHeader = request.headers.get('authorization') |
| if (authHeader?.startsWith('Bearer ')) { |
| const token = authHeader.slice(7) |
| const { data: { user: tokenUser }, error: tokenError } = |
| await supabase.auth.getUser(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 } |
| ), |
| } |
| } |
| } |
|
|