Skip to content

Instantly share code, notes, and snippets.

@brianium
Last active January 2, 2016 02:39
Show Gist options
  • Save brianium/8238437 to your computer and use it in GitHub Desktop.
Save brianium/8238437 to your computer and use it in GitHub Desktop.
create authenticted app in express
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;
}, {});
};
@brianium
Copy link
Author

brianium commented Jan 3, 2014

Sample usage. req.user is populated by leveraging passportjs

var app = require('express')()
  , authed = require('authenticated')(app);

//unauthenticated
app.get('/api/thing', function(req, res, next) {

});

//authenticated
authed.get('/api/restrictedthing', function(req, res, next) {

});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment