48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { verifyCredentials, createToken } from '@/lib/auth';
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const { username, password } = await request.json();
|
|
|
|
if (!username || !password) {
|
|
return NextResponse.json(
|
|
{ error: 'Username and password required' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const isValid = await verifyCredentials(username, password);
|
|
|
|
if (!isValid) {
|
|
return NextResponse.json(
|
|
{ error: 'Invalid credentials' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
const token = createToken(username);
|
|
|
|
const response = NextResponse.json(
|
|
{ success: true, username },
|
|
{ status: 200 }
|
|
);
|
|
|
|
response.cookies.set('auth-token', token, {
|
|
httpOnly: true,
|
|
secure: process.env.NODE_ENV === 'production',
|
|
sameSite: 'lax',
|
|
maxAge: 60 * 60 * 24, // 24 hours
|
|
path: '/',
|
|
});
|
|
|
|
return response;
|
|
} catch (error) {
|
|
console.error('Login error:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Internal server error' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|