generated from lucien/api-template
add: added auth to the api
This commit is contained in:
parent
6017eb9d1f
commit
217c763abd
8 changed files with 790 additions and 279 deletions
57
back/api/auth.js
Normal file
57
back/api/auth.js
Normal file
|
@ -0,0 +1,57 @@
|
|||
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' });
|
||||
});
|
||||
|
||||
router.post('/me', checkAuth, async (req, res) => {
|
||||
const user = req.user;
|
||||
res.send({ id: user.id, name: user.name, lastname: user.lastname, admin: user.admin });
|
||||
});
|
||||
|
||||
module.exports = router;
|
|
@ -1,14 +1,6 @@
|
|||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const cors = require('cors');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(express.json());
|
||||
router.use(cookieParser());
|
||||
router.use(cors());
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
res.send('Hello World!');
|
||||
});
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue