1
0
Fork 0
nodejs-backend-template/server/middlewares/verify-user-jwt.js

30 lines
1.1 KiB
JavaScript

const { User } = require('../dao/models');
const ApplicationError = require('../utils/application-error');
const jwt = require('jsonwebtoken');
/**
* Middleware for verifying and processing user tokens.
*
* This middleware checks for the presence and validity of the user token in the request.
* If the user token is valid, the user object is added to the `req.user` property
* property for further use in other parts of the application. If the token is missing or invalid,
* an error of type `ApplicationError.BadToken` is thrown.
*
* @param {object} req - Express request object.
* @param {object} res - The Express response object.
* @param {function} next - A function to move to the next middleware.
*/
module.exports = async (req, res, next) => {
let userJwt;
try {
userJwt = jwt.verify(req.accessToken, process.env.USER_JWT_ACCESS_SECRET);
} catch(err) {
throw ApplicationError.BadToken();
}
req.user = await User.findOne({ where: { id: userJwt.id }, attributes: { exclude: ['salt', 'passwordHashed']}});
if (!req.user) {
throw ApplicationError.BadToken();
}
next();
};