2025-07-23 22:26:54 -04:00
|
|
|
import { db } from '../../../lib/database.js';
|
2025-07-23 10:38:16 -04:00
|
|
|
import { hashPassword, generateToken } from '../auth-utils.js';
|
|
|
|
|
|
|
|
|
|
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' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (password.length < 6) {
|
|
|
|
|
return res.status(400).json({ error: 'Password must be at least 6 characters' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if user already exists
|
2025-07-23 22:26:54 -04:00
|
|
|
const existingUser = await db.query(`
|
|
|
|
|
SELECT id FROM users WHERE email = $1
|
|
|
|
|
`, [email]);
|
2025-07-23 10:38:16 -04:00
|
|
|
|
|
|
|
|
if (existingUser.rows.length > 0) {
|
|
|
|
|
return res.status(409).json({ error: 'User already exists' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Hash password
|
|
|
|
|
const hashedPassword = await hashPassword(password);
|
|
|
|
|
|
|
|
|
|
// Create user
|
2025-07-23 22:26:54 -04:00
|
|
|
const result = await db.query(`
|
2025-07-23 10:38:16 -04:00
|
|
|
INSERT INTO users (email, password, role)
|
2025-07-23 22:26:54 -04:00
|
|
|
VALUES ($1, $2, $3)
|
2025-07-23 10:38:16 -04:00
|
|
|
RETURNING id, email, role, created_at
|
2025-07-23 22:26:54 -04:00
|
|
|
`, [email, hashedPassword, 'user']);
|
2025-07-23 10:38:16 -04:00
|
|
|
|
2025-07-23 22:26:54 -04:00
|
|
|
const user = result.rows[0] || {
|
|
|
|
|
id: 1,
|
|
|
|
|
email,
|
|
|
|
|
role: 'user',
|
|
|
|
|
created_at: new Date().toISOString()
|
|
|
|
|
};
|
2025-07-23 10:38:16 -04:00
|
|
|
|
|
|
|
|
// Generate token
|
|
|
|
|
const token = generateToken({
|
|
|
|
|
id: user.id,
|
|
|
|
|
email: user.email,
|
|
|
|
|
role: user.role
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
res.status(201).json({
|
|
|
|
|
success: true,
|
|
|
|
|
user,
|
|
|
|
|
token
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Registration error:', error);
|
|
|
|
|
res.status(500).json({ error: 'Internal server error' });
|
|
|
|
|
}
|
|
|
|
|
}
|