From ade50cb2487e90de65c5480622bc407b49351442 Mon Sep 17 00:00:00 2001 From: sundowndev Date: Fri, 16 Nov 2018 17:31:37 +0100 Subject: [PATCH] [Fix #5] Verify user exists in authentication middleware --- app/validation/auth/auth.js | 44 +++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 app/validation/auth/auth.js diff --git a/app/validation/auth/auth.js b/app/validation/auth/auth.js new file mode 100644 index 0000000..2e6c002 --- /dev/null +++ b/app/validation/auth/auth.js @@ -0,0 +1,44 @@ +const Joi = require('joi'); +const jwt = require('jsonwebtoken'); +const mongoose = require('mongoose'); + +const secret = require.main.require('./config/secret'); + +module.exports = (req, res, next) => { + const UserModel = mongoose.model('User'); + + const schema = Joi.object().keys({ + access_token: Joi.string().required(), + }); + + Joi.validate({ + access_token: req.headers.authorization, + }, + schema, (validateErr) => { + if (validateErr) { + return next({ status: 401, error: validateErr.details }); + } + + return jwt.verify(req.headers.authorization, secret, (err, decoded) => { + if (err) { + return next({ status: 401, message: 'Token error.', error: [err] }); + } + + return UserModel.countDocuments( + { + _id: decoded.user.id, + }, (QueryError, count) => { + if (count !== 1) { + return next({ + status: 403, + message: 'Your session is invalid. Please try sign in again.', + error: [], + }); + } + + return next(); + }, + ); + }); + }); +};