// app/api/auth/login/route.ts import { cookies } from 'next/headers'; import { NextRequest, NextResponse } from 'next/server'; export async function POST(request: NextRequest) { try { const body = await request.json(); const { username, password } = body; console.log('🟢 [API] Login attempt for:', username); if (!username || !password) { return NextResponse.json( { message: 'Username and password are required' }, { status: 400 } ); } const formdata = new FormData() formdata.append("username", username) formdata.append("password", password) // Call backend const loginResponse = await fetch( 'https://byteriot-candidateexplorer.hf.space/CandidateExplorer/admin/login', { method: 'POST', body: formdata, } ); if (!loginResponse.ok) { console.log('🟢 [API] Backend rejected login'); return NextResponse.json( { message: 'Invalid credentials' }, { status: 401 } ); } const { access_token } = await loginResponse.json(); console.log('🟢 [API] Got token from backend'); // Get user data const userResponse = await fetch( 'https://byteriot-candidateexplorer.hf.space/CandidateExplorer/admin/me', { headers: { Authorization: `Bearer ${access_token}` }, } ); if (!userResponse.ok) { console.log('🟢 [API] Failed to get user data'); return NextResponse.json( { message: 'Failed to get user data' }, { status: 500 } ); } const userData = await userResponse.json(); console.log('🟢 [API] Got user data:', userData); // Set cookie using Next.js cookies API (no 'cookie' package needed!) const cookieStore = await cookies(); cookieStore.set('auth_token', access_token, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', path: '/', maxAge: 7 * 24 * 60 * 60, // 7 days }); console.log('🟢 [API] Cookie set successfully'); return NextResponse.json(userData, { status: 200 }); } catch (error) { console.error('🟢 [API] Login error:', error); return NextResponse.json( { message: 'Login failed' }, { status: 500 } ); } }