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
28
back/libs/middlewares.js
Normal file
28
back/libs/middlewares.js
Normal file
|
@ -0,0 +1,28 @@
|
|||
const jwt = require('jsonwebtoken');
|
||||
const { getConnection, getUser } = require('./mysql');
|
||||
|
||||
async function checkAuth(req, res, next) {
|
||||
const { token } = req.body;
|
||||
if (!token) {
|
||||
return res.status(401).send({ error: 'No token provided' });
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
const connection = await getConnection();
|
||||
const user = await getUser(connection, decoded.id);
|
||||
connection.end();
|
||||
if (!user[0]) {
|
||||
return res.status(401).send({ error: 'Invalid token' });
|
||||
}
|
||||
req.user = user[0];
|
||||
next();
|
||||
}
|
||||
catch (err) {
|
||||
return res.status(401).send({ error: 'Invalid token' });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
checkAuth,
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue