Skip to content

Instantly share code, notes, and snippets.

@cjpartridgeb
Created March 25, 2013 07:22
Show Gist options
  • Save cjpartridgeb/5235434 to your computer and use it in GitHub Desktop.
Save cjpartridgeb/5235434 to your computer and use it in GitHub Desktop.
middleware example
// mw.getUserAndAgency
var middleware = function(req, res, next) {
req.statsdName = 'user_middleware';
var get = cabinet
.read('users', req.token.user_id)
.with('agencies');
get.execute(function(err, empty, result) {
if(err) return next(err);
if(empty) return next(new Error('User not found.'));
req.user = result.users;
req.agency = result.agencies;
return next();
});
};
// mw.authorizePrincipal
module.exports = function(req, res, next) {
if(!req.user.principal) {
var err = new Error('Principal access is required to complete this action.');
err.code=62;
err.statusCode=403;
return next(err);
}
return next();
};
// app routes
app.all('*', mw.getUserAndAgency);
app.get('/users', mw.authorizePrincipal, routes.users.index);
app.post('/users', mw.authorizePrincipal, routes.users.create);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment