Search code examples
meteorrolesiron-router

Stop users from navigating to a page that is restricted to their role


I want to restrict access to certain pages depending on users roles. So I don't want a logged in user to be able to just change the URL in their browser to navigate to a page they shouldn't have access to. So for such a route I'm doing something like:

action: function () {
    if (!Roles.userIsInRole(Meteor.user(), 'admin')) {
        this.render("AcressRestricted");
    } else {
        // Do routing for admin users here....
    }
}

Is that the standard way to go? And do I need to add this code to every page I want to restrict or is there a more general solution / short cut?


Solution

  • You can use Router.onBeforeAction:

    Router.onBeforeAction(function() {
        if (!Roles.userIsInRole(Meteor.user(), 'admin')) {
            this.render("AcressRestricted");
        } else {
            this.next();
        }
    }, {only : 'route_one', 'route_two'});
    

    This will only work for route_one and route_two.

    Be sure to name what you use in 'only' or 'except' in your route definitions:

    Router.route('/' {
        name: 'route_one',
        ...
    });