import { NextRequest, NextResponse } from "next/server" import { supabase } from "@/lib/supabase" import { userService } from "@/lib/database" export interface AdminProfile { user_id: number user_name: string email: string user_type: "admin" | "user" | "moderator" } /** * Require valid Bearer token and admin user. Use in sensitive API routes. * Returns either { profile } or { error: NextResponse }. */ export async function requireAdmin( request: NextRequest ): Promise< | { profile: AdminProfile } | { error: NextResponse } > { const authHeader = request.headers.get("authorization") if (!authHeader || !authHeader.startsWith("Bearer ")) { return { error: NextResponse.json( { error: "Authorization header required" }, { status: 401 } ), } } const token = authHeader.slice(7) const { data: { user }, error: authError } = await supabase.auth.getUser(token) if (authError || !user) { return { error: NextResponse.json( { error: "Invalid or expired token" }, { status: 401 } ), } } const profile = await userService.getByEmail(user.email!) if (!profile) { return { error: NextResponse.json( { error: "User profile not found" }, { status: 404 } ), } } if (profile.user_type !== "admin") { return { error: NextResponse.json( { error: "Admin access required" }, { status: 403 } ), } } return { profile: profile as AdminProfile, } } /** * Require valid Bearer token (any authenticated user). Use for APIs that should not be anonymous. */ export async function requireAuth( request: NextRequest ): Promise< | { profile: { user_id: number; email: string; user_name: string } } | { error: NextResponse } > { const authHeader = request.headers.get("authorization") if (!authHeader || !authHeader.startsWith("Bearer ")) { return { error: NextResponse.json( { error: "Authorization header required" }, { status: 401 } ), } } const token = authHeader.slice(7) const { data: { user }, error } = await supabase.auth.getUser(token) if (error || !user) { return { error: NextResponse.json( { error: "Invalid or expired token" }, { status: 401 } ), } } const profile = await userService.getByEmail(user.email!) if (!profile) { return { error: NextResponse.json( { error: "User profile not found" }, { status: 404 } ), } } return { profile } }