From 29269dcfcdfff57e3a4d0c94e8b07c4c30dcd217 Mon Sep 17 00:00:00 2001 From: Paul Bienkowski Date: Tue, 24 Nov 2020 00:29:16 +0100 Subject: [PATCH] feat: load user object in auth middleware chain --- app.js | 1 + models/User.js | 2 ++ routes/auth.js | 27 ++++++++++++++++++++++++++- 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/app.js b/app.js index bdaf2b1..36f6417 100644 --- a/app.js +++ b/app.js @@ -14,6 +14,7 @@ const app = express(); app.use(cors()); app.use(auth.getUserIdMiddleware); +app.use(auth.loadUserMiddleware); // Normal express config defaults app.use(require('morgan')('dev')); diff --git a/models/User.js b/models/User.js index b80c16d..ff832ad 100644 --- a/models/User.js +++ b/models/User.js @@ -130,3 +130,5 @@ UserSchema.methods.isFollowing = function (id) { }; mongoose.model('User', UserSchema); + +module.exports = mongoose.model('User') diff --git a/routes/auth.js b/routes/auth.js index 70f4ed7..023c2cf 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -1,5 +1,6 @@ const jwt = require('express-jwt'); const secret = require('../config').secret; +const User = require('../models/User'); function getTokenFromHeader(req) { const authorization = req.headers.authorization; @@ -20,7 +21,7 @@ const jwtOptional = jwt({ algorithms: ['HS256'], }); -function getUserIdMiddleware(req, res, next) { +async function getUserIdMiddleware(req, res, next) { try { const authorization = req.headers.authorization; const [tokenType, token] = (authorization && authorization.split(' ')) || []; @@ -30,6 +31,13 @@ function getUserIdMiddleware(req, res, next) { } else if (tokenType === 'OBSUserId') { req.payload = { id: token.trim() }; next(); + } else if (!authorization && req.body && req.body.id && req.body.id.length === 24) { + const user = await User.findById(req.body.id); + if (user) { + req.payload = { id: user.id }; + req.user = user; + } + next(); } else { req.payload = null; next(); @@ -39,6 +47,22 @@ function getUserIdMiddleware(req, res, next) { } } +async function loadUserMiddleware(req, res, next) { + try { + if (req.payload && req.payload.id) { + req.user = await User.findById(req.payload.id); + + if (!req.user) { + return res.sendStatus(401); + } + } + + next(); + } catch (err) { + next(err); + } +} + module.exports = { required(req, res, next) { if (!req.payload) { @@ -51,4 +75,5 @@ module.exports = { return next(); }, getUserIdMiddleware, + loadUserMiddleware, };