61 lines
1.8 KiB
JavaScript
61 lines
1.8 KiB
JavaScript
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
|
|
|
|
|
|
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
|
|
const headerToken = req.headers.authorization.split(' ')[1]
|
|
if (headerToken && headerToken !== 'undefined' && headerToken !== 'null' && headerToken.trim() !== '') {
|
|
token = headerToken.trim()
|
|
}
|
|
}
|
|
|
|
if (!token && req.cookies) {
|
|
token = req.cookies['bm-token'] || req.cookies['belonging_token'] || req.cookies['jwt']
|
|
}
|
|
|
|
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')
|
|
|
|
|
|
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()
|
|
}
|