add: added auth to the api

This commit is contained in:
Lukian 2025-04-22 12:10:22 +02:00
parent 6017eb9d1f
commit 217c763abd
8 changed files with 790 additions and 279 deletions

28
back/libs/middlewares.js Normal file
View 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,
};