Last active
January 2, 2016 02:39
-
-
Save brianium/8238437 to your computer and use it in GitHub Desktop.
create authenticted app in express
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var _ = require('lodash') | |
, problem = require('../errors').problem; | |
/** | |
* Check the request for a user. If none found | |
* create an API-Problem style error | |
*/ | |
function check(req, res, next) { | |
if (!req.user) return next( | |
problem(new Error("Resource requires authorization"), { | |
title:'Unauthorized', | |
httpStatus: 401 | |
}) | |
); | |
next(); | |
} | |
/** | |
* Returns a module that delegates to express' app methods | |
* but first ensures that a user exists on the request | |
*/ | |
module.exports = function(app) { | |
return _.reduce(['post', 'put', 'del', 'get'], function(authed, m) { | |
authed[m] = (function(method) { | |
return function(route /**, middleware **/) { | |
var args = [route, check].concat(_.rest(_.toArray(arguments))); | |
return app[method].apply(app, args); | |
} | |
})(m); | |
return authed; | |
}, {}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage. req.user is populated by leveraging passportjs