tanuki-s-forum/back/libs/middlewares.js

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,
};