2025-07-24 20:57:19 -04:00
|
|
|
import bcrypt from 'bcryptjs';
|
|
|
|
|
import { sql } from '@vercel/postgres';
|
2026-05-23 10:47:11 -04:00
|
|
|
import { generateToken } from '../auth-utils.js';
|
2025-07-23 10:38:16 -04:00
|
|
|
|
|
|
|
|
export default async function handler(req, res) {
|
|
|
|
|
// Set CORS headers
|
|
|
|
|
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
|
|
|
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
|
|
|
|
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
|
|
|
|
|
|
|
|
// Handle preflight requests
|
|
|
|
|
if (req.method === 'OPTIONS') {
|
|
|
|
|
res.status(200).end();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (req.method !== 'POST') {
|
|
|
|
|
return res.status(405).json({ error: 'Method not allowed' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const { email, password } = req.body;
|
|
|
|
|
|
|
|
|
|
if (!email || !password) {
|
|
|
|
|
return res.status(400).json({ error: 'Email and password are required' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Get user from database
|
2025-07-24 20:57:19 -04:00
|
|
|
const result = await sql`
|
|
|
|
|
SELECT id, email, password, role, created_at
|
|
|
|
|
FROM users
|
|
|
|
|
WHERE email = ${email}
|
|
|
|
|
`;
|
2025-07-23 10:38:16 -04:00
|
|
|
|
|
|
|
|
if (result.rows.length === 0) {
|
|
|
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const user = result.rows[0];
|
|
|
|
|
|
|
|
|
|
// Verify password
|
2025-07-24 20:57:19 -04:00
|
|
|
const isValidPassword = await bcrypt.compare(password, user.password);
|
|
|
|
|
|
|
|
|
|
if (!isValidPassword) {
|
2025-07-23 10:38:16 -04:00
|
|
|
return res.status(401).json({ error: 'Invalid credentials' });
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-24 20:57:19 -04:00
|
|
|
// Generate JWT token
|
2026-05-23 10:47:11 -04:00
|
|
|
const token = generateToken({ id: user.id, email: user.email, role: user.role });
|
2025-07-23 10:38:16 -04:00
|
|
|
|
|
|
|
|
// Return user data (without password) and token
|
|
|
|
|
const { password: _, ...userWithoutPassword } = user;
|
|
|
|
|
|
|
|
|
|
res.status(200).json({
|
|
|
|
|
success: true,
|
|
|
|
|
user: userWithoutPassword,
|
|
|
|
|
token
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Login error:', error);
|
|
|
|
|
res.status(500).json({ error: 'Internal server error' });
|
|
|
|
|
}
|
|
|
|
|
}
|