borsa / nextjs-app /src /lib /api-auth.ts
veteroner's picture
feat: live position monitoring with charts + trading system production ready
656ac31
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
}
/**
* Verify that the incoming request belongs to an authenticated Supabase user.
*
* Usage in any API route:
* ```ts
* const auth = await requireAuth()
* if (!auth.authenticated) return auth.response
* // auth.userId is available
* ```
*
* Works with both cookie-based sessions (browser) and
* Authorization: Bearer <token> header (API clients).
*/
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 {
// Cannot set cookies in read-only context
}
},
},
}
)
// Try cookie-based auth first
const { data: { user }, error } = await supabase.auth.getUser()
if (user && !error) {
return { authenticated: true, userId: user.id, email: user.email }
}
// Fallback: try Authorization header (for API clients)
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 }
),
}
}
}