Skip to content

Instantly share code, notes, and snippets.

@mikeuduc
Created May 14, 2015 01:10
Show Gist options
  • Save mikeuduc/387025d99251c22b09ea to your computer and use it in GitHub Desktop.
Save mikeuduc/387025d99251c22b09ea to your computer and use it in GitHub Desktop.
// Authentication Middleware for routes
// Author: Mike McCabe
var _ = require('underscore');
// Publicly accessible auth middleware functions
// Allows for mix/match of different auth middleware functions
// The module only passes back the middleware functions that do the actual work
module.exports = {
// route middleware to make sure user is logged in
requireLoggedIn: function() {
return requireLoggedIn;
},
// route middleware to make user has company permission
requireUserInCompany: function() {
return [
requireLoggedIn,
requireUserInCompany
]
},
// route middleware to check user role "owner" "admin" "agent" etc
requireCompanyRole: function(roles){
return [
requireLoggedIn,
requireUserInCompany,
requireCompanyRole(roles)
]
}
}
// Actual middleware functions that are passed back to the router
var requireLoggedIn = function(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated()){
next();
}
// if they aren't redirect them to the home page
else{
res.redirect('/');
}
}
// route middleware to make user has company permission
var requireUserInCompany = function(req, res, next) {
req.company = _.find(req.user.Company, function(company){
return company.id === req.param('companyid');
});
req.company !== undefined
? next()
: res.send(403);
}
var requireCompanyRole = function(roles){
return function(req, res, next){
roles.indexOf(req.company.role) > -1 ? next() : res.send(403);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment