generated from lucien/api-template
52 lines
No EOL
1.6 KiB
JavaScript
52 lines
No EOL
1.6 KiB
JavaScript
const express = require('express');
|
|
const sha256 = require("sha256");
|
|
const jwt = require('jsonwebtoken');
|
|
const { getConnection, addUser, getUserByEmail } = require('../libs/mysql');
|
|
const { checkAuth } = require('../libs/middlewares');
|
|
|
|
const router = express.Router();
|
|
|
|
router.post('/login', async (req, res) => {
|
|
const { email, password } = req.body;
|
|
|
|
if (!email || !password) {
|
|
return res.status(400).send({ error: 'Invalid email or password' });
|
|
}
|
|
|
|
const connection = await getConnection();
|
|
const user = await getUserByEmail(connection, email);
|
|
connection.end();
|
|
if (user[0]) {
|
|
if (user[0].password === sha256(password)) {
|
|
const token = jwt.sign({ id: user[0].id }, process.env.JWT_SECRET, {
|
|
expiresIn: 1000 * 60 * 60 * 24 * 7,
|
|
});
|
|
return res.send({ token: token });
|
|
}
|
|
}
|
|
res.status(401).send({ error: 'Invalid email or password' });
|
|
});
|
|
|
|
router.post('/register', async (req, res) => {
|
|
const { name, lastname, email, numero, password } = req.body;
|
|
const connection = await getConnection();
|
|
|
|
if (!name || !lastname || !password || !email || !numero) {
|
|
connection.end();
|
|
return res.status(400).send({ error: 'Invalid username or password' });
|
|
}
|
|
|
|
const user = await getUserByEmail(connection, email);
|
|
if (user[0]) {
|
|
connection.end();
|
|
return res.status(401).send({ error: 'Username already exists' });
|
|
}
|
|
|
|
const hash = sha256(password);
|
|
await addUser(connection, name, lastname, email, numero, hash);
|
|
connection.end();
|
|
|
|
res.send({ message: 'User added' });
|
|
});
|
|
|
|
module.exports = router; |