How to protect routes for different user groups

爱⌒轻易说出口 提交于 2019-12-20 06:02:50

问题


I'm building an app with backbone.js and wonder, how to protect routes for different user groups.

I've seen many tutorials with some simple authentication methods, but i doesn't find any information about user groups.

Let's say i have 2 user groups for my app: admins (read/write) and guests (read). How can i setup a secure authentication system with backbone.js, so that guests won't be able to open http://example.com/foo/1/edit?

Any ideas?


回答1:


One option is to only set-up the routes if the user is in the admin group.

var router = new appRouter();

if (user.group === 'admin') {
  router.route('foo/:id/edit','edit',function {
    // your admin route logic here.
  });

  // or define the function in your router and reference it
  // such as: router.route('foo/:id/edit','edit',router.edit);
}

Backbone.history.start();

If you had alot of routes you could create an object that contains your admin routes like the following: (may want to add a property for the route name though)

var adminRoutes = {
  'foo/:id/edit':function() {
       // your logic here
   },
  'another/route': // same set-up as above
  ...
};

Then set them up in your if condition with a loop:

for (var k in adminRoutes)
  router.route(k,k,adminRoutes[k]);

Anyway, there are a few different set-up options with this method.

The advantage with this approach is you don't have to check the route and user permissions each route the user navigates to. Either the route is set-up or it isn't.

If your users have the ability to upgrade to admin rights then wrap the route set-up logic in a function and invoke it when user is granted admin access.

Aside from all this, to my knowledge, it is not possible to set-up a secure authentication system on the frontend. You must also check permissions server-side, regardless of any approach you decide upon.




回答2:


You can have a single router managing all the routes for you and then you can listen on the router's "all" event to see which route is the user trying to navigate to. Then, you can decide based on the user and route whether he be allowed to go there or not. Something like this might work :

app.router.on("all",function(a){
    var routeRegex = /^route:(.*)$/g;
    var routeType = a.match(/route:(.*)$/)[1];

 if( routeType === "edit" && !app.isCurrentUserAllowedAdminAccess() ){
       //re-route the user to a different page
       app.router.navigate("user/access_denied", {trigger:true});
    }
}


来源:https://stackoverflow.com/questions/17974259/how-to-protect-routes-for-different-user-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!