const { promisify } = require('util') const jwt = require('jsonwebtoken') const User = require('../components/user/userModel') const AppError = require('../globalErrorHandler/AppError') exports.loginProtect = async (req, res, next) => { // 1) Getting token and check if it's there let token token = req.cookies.jwt || req.cookies['crm-jwt'] if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) { token = req.headers.authorization.split(' ')[1] } if (!token) { return next(new AppError('NotLoggedIn', 401)) } // 2) Verification token let decodedToken try { decodedToken = await promisify(jwt.verify)(token, process.env.JWT_SECRET) } catch (err) {} if (!decodedToken) { return next(new AppError('TokenUserNotExist', 401)) } // 3) check if user still exist const loggedInUser = await User.findById(decodedToken.id).populate('role addresses') if (!loggedInUser) { return next(new AppError('TokenUserNotExist', 401, {})) } // 4) check if user changed password after the token was issued // if (loggedInUser.changedPasswordAfter(decodedToken.iat)) { // return next(new AppError('UserChangedPasswordRecently', 401)) // } // GRANT ACCESS TO PROTECTED ROUTE req.user = loggedInUser next() } exports.webServiceProtect = async (req, res, next) => { if (req.query.token !== process.env.WEB_SERVICE_TOKEN) { return next(new AppError('NoWebServiceAccess', 401)) } next() }