2025-07-23 10:38:16 -04:00
|
|
|
import jwt from 'jsonwebtoken';
|
|
|
|
|
import { sql } from '@vercel/postgres';
|
|
|
|
|
|
|
|
|
|
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
|
|
|
|
|
|
|
|
|
|
export async function hashPassword(password) {
|
2025-07-23 10:40:50 -04:00
|
|
|
const bcrypt = await import('bcryptjs');
|
2025-07-23 10:38:16 -04:00
|
|
|
return await bcrypt.hash(password, 12);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function verifyPassword(password, hashedPassword) {
|
2025-07-23 10:40:50 -04:00
|
|
|
const bcrypt = await import('bcryptjs');
|
2025-07-23 10:38:16 -04:00
|
|
|
return await bcrypt.compare(password, hashedPassword);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function generateToken(user) {
|
|
|
|
|
return jwt.sign(
|
|
|
|
|
{
|
|
|
|
|
userId: user.id,
|
|
|
|
|
email: user.email,
|
|
|
|
|
role: user.role
|
|
|
|
|
},
|
|
|
|
|
JWT_SECRET,
|
|
|
|
|
{ expiresIn: '7d' }
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function verifyToken(token) {
|
|
|
|
|
try {
|
|
|
|
|
return jwt.verify(token, JWT_SECRET);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function isAdmin(userId) {
|
|
|
|
|
try {
|
|
|
|
|
const result = await sql`
|
|
|
|
|
SELECT role FROM users WHERE id = ${userId}
|
|
|
|
|
`;
|
|
|
|
|
return result.rows[0]?.role === 'admin';
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error checking admin status:', error);
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function getUserById(userId) {
|
|
|
|
|
try {
|
|
|
|
|
const result = await sql`
|
|
|
|
|
SELECT id, email, role, created_at FROM users WHERE id = ${userId}
|
|
|
|
|
`;
|
|
|
|
|
return result.rows[0];
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error getting user:', error);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|