route-middleware restrict to self AND restrict to admin

109 views
Skip to first unread message

zeMirco

unread,
Aug 25, 2012, 10:36:12 AM8/25/12
to expre...@googlegroups.com
In the examples folder I found some nice middleware functions for managing users and roles:

function andRestrictToSelf(req, res, next) {
  if (req.authenticatedUser.id == req.user.id) {
    next();
  } else {
    next(new Error('Unauthorized'));
  }
}

function andRestrictTo(role) {  
return function(req, res, next) {    
if (req.authenticatedUser.role == role) {      
next();    
} else {      
next(new Error('Unauthorized'));    
}  
}
}

app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){  
res.send('Editing user ' + req.user.name);
});

app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){  
res.send('Deleted user ' + req.user.name);
});

However I would like to have a route that is restricted to the user himself AND to an admin user:

app.get('/user/:id/moreStuff', loadUser, andRestrictToSelf, andRestrictTo('admin'), function(req, res){    
res.send('Only viewable for admin and the user himself');
});

As far as I can tell this doesn't work. andRestrictToSelf would produce an error for the admin user and andRestrictTo('admin') would produce an error for the user himself. Does anyone have an idea for an elegant solution to allow access for the user and an admin?

Thanks!






zeMirco

unread,
Aug 25, 2012, 10:39:52 AM8/25/12
to expre...@googlegroups.com
fixing some formatting

Ryan Schmidt

unread,
Aug 25, 2012, 6:55:13 PM8/25/12
to expre...@googlegroups.com
You mean you would like to restrict the route to the user himself OR to an admin user. (Middleware is ANDed together already.) I'd just write a new middleware function for this.

function andRestrictToSelfOr(role) {
return function(req, res, next) {
if ((req.authenticatedUser.id == req.user.id) || (req.authenticatedUser.role == role)) {
next();
} else {
next(new Error('Unauthorized'));
}
}
}

app.get('/user/:id/moreStuff', loadUser, andRestrictToSelfOr('admin'), function(req, res){

zeMirco

unread,
Aug 27, 2012, 2:37:32 AM8/27/12
to expre...@googlegroups.com
awesome! Thank you

deitch

unread,
Aug 27, 2012, 1:05:15 PM8/27/12
to expre...@googlegroups.com
I had the same problem, plus authentication issues, look at my cansecurity project

Reply all
Reply to author
Forward
0 new messages