| |
| 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) |
|
|
| |
| 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'); |
|
|
| |
| 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); |
|
|
| |
| 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, |
| }); |
|
|
| 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 } |
| ); |
| } |
| } |