generated from lucien/api-template
28 lines
No EOL
760 B
JavaScript
28 lines
No EOL
760 B
JavaScript
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,
|
|
}; |