Skip to content

Commit

Permalink
fix(writeapi): authenticate middleware logic to work better with await
Browse files Browse the repository at this point in the history
  • Loading branch information
julianlam committed Oct 8, 2020
1 parent f6433ef commit fd67355
Showing 1 changed file with 34 additions and 24 deletions.
58 changes: 34 additions & 24 deletions src/middleware/user.js
Expand Up @@ -16,17 +16,41 @@ const controllers = {
authentication: require('../controllers/authentication'),
};

const passportAuthenticateAsync = function (req, res) {
return new Promise((resolve, reject) => {
passport.authenticate('bearer', { session: false }, (err, user) => {
if (err) {
reject(err);
} else {
resolve(user);
}
})(req, res);
});
};

module.exports = function (middleware) {
async function authenticate(req, res) {
if (req.loggedIn) {
return true;
} else if (req.headers.hasOwnProperty('authorization')) {
passport.authenticate('bearer', { session: false }, function (err, user) {
if (err) { throw new Error(err); }
if (!user) { return false; }
const user = await passportAuthenticateAsync(req, res);
if (!user) { return true; }

// If the token received was a master token, a _uid must also be present for all calls
if (user.hasOwnProperty('uid')) {
req.login(user, async function (err) {
if (err) { throw new Error(err); }

await controllers.authentication.onSuccessfulLogin(req, user.uid);
req.uid = user.uid;
req.loggedIn = req.uid > 0;
return true;
});
} else if (user.hasOwnProperty('master') && user.master === true) {
if (req.body.hasOwnProperty('_uid') || req.query.hasOwnProperty('_uid')) {
user.uid = req.body._uid || req.query._uid;
delete user.master;

// If the token received was a master token, a _uid must also be present for all calls
if (user.hasOwnProperty('uid')) {
req.login(user, async function (err) {
if (err) { throw new Error(err); }

Expand All @@ -35,27 +59,13 @@ module.exports = function (middleware) {
req.loggedIn = req.uid > 0;
return true;
});
} else if (user.hasOwnProperty('master') && user.master === true) {
if (req.body.hasOwnProperty('_uid') || req.query.hasOwnProperty('_uid')) {
user.uid = req.body._uid || req.query._uid;
delete user.master;

req.login(user, async function (err) {
if (err) { throw new Error(err); }

await controllers.authentication.onSuccessfulLogin(req, user.uid);
req.uid = user.uid;
req.loggedIn = req.uid > 0;
return true;
});
} else {
throw new Error('A master token was received without a corresponding `_uid` in the request body');
}
} else {
winston.warn('[api/authenticate] Unable to find user after verifying token');
return false;
throw new Error('A master token was received without a corresponding `_uid` in the request body');
}
})(req, res);
} else {
winston.warn('[api/authenticate] Unable to find user after verifying token');
return true;
}
}

await plugins.fireHook('response:middleware.authenticate', {
Expand Down

0 comments on commit fd67355

Please sign in to comment.