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