Files
HadiJobs/backend/routes/auth.js
2026-05-08 15:16:04 +02:00

80 lines
2.3 KiB
JavaScript

import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import { prisma } from '../prisma.js'
export const login = async (req, res) => {
// Get data
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'All fields are required' })
}
// Check data is correct
const user = await prisma.user.findFirst({ where: { email } });
if (!user || !await bcrypt.compare(password, user.password)) {
return res.status(400).json({ error: 'Credenciales erroneas' })
}
// Generate JWT
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '7d' })
// Return
res.status(200).json({
id: user.id,
username: user.username,
email: user.email,
token
})
}
export const register = async (req, res) => {
// Get data
const {username, email, password, type } = req.body
// Check is not empty
if (!username || !email || !password) {
return res.status(400).json({ error: 'Todos los campos son obligatorios' })
}
// Validate data
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
if (username.length < 3 ||username.length > 14) { return res.status(400).json({ error: 'El nombre de usuario debe tener entre 3 y 14 caracteres' })}
if (email.length > 30 || !emailRegex.test(email)) { return res.status(400).json({ error: 'Correo electronico no valido' })}
if (password.length < 6 || password.length > 32) { return res.status(400).json({ error: 'La contraseƱa debe tener entre 6 y 32 caracteres' })}
if (type !== "candidato" && type !== "reclutador") { return res.status(400).json({ error: 'El tipo de cuenta no es valido' })}
// Check email and username doesnt exists
const userExists = await prisma.user.findFirst({
where: {
OR: [ { email } ]
}
});
// If username or email exists, send error
if (userExists) {
return res.status(409).json({
error: 'Este usuario ya existe'
})
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 10)
// Create user
const user = await prisma.user.create({
data: { username, email, password: hashedPassword, type }
})
// Generates token
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '7d' })
// Return user
res.status(201).json({ id: user.id, username: user.username, email: user.email, token })
}