Search code examples
meteoriron-router

iron:router + alanning:roles => why this role check working randomly?


I'm using iron:router and alanning:roles and I want to restrict my SecretArea for only users who has been added to admin role. This works just fine if user is not logged in. But if user has logged in and she is an admin then the trouble starts.

I can get Meteor.userId() on every page load which is made against SecreArea. The problem is Roles.userIsInRole sometimes it returns true and sometimes false. It doesn't make much sense..

And this is ofc really annoying for users who know they should have admin rights and still this is routing them pretty much randomly. I think the ratio here is something like 90-10 percents, most of time it's working, but one time out of ten its not.

Not sure, but this could be mostly happening when made changes to code and meteor reloads.

SecretAreaController = RouteController.extend({
    layoutTemplate: 'secretAreaLayout',
    onBeforeAction: function () {
        if (!Roles.userIsInRole(Meteor.userId(), ['admin']))
            Router.go('/');
        else
            this.next();
    }
});

Worth of mentioning: all SecreArea routes are extending this controller.

Packages I'm using for this:

So am I doing something wrong in here, or is there better solution for this?

Any help appreciated!


Solution

  • After few frustrating hours later this solved the problem for me.

    SecretAreaController = RouteController.extend({
        layoutTemplate: 'secretAreaLayout',
        waitOn: function () {
            return [ Meteor.subscribe("roles") ];
        },
        onBeforeAction: function () {
            if (!Roles.userIsInRole(Meteor.userId(), ['admin']))
                Router.go('/');
            else
                this.next();
        }
    });
    

    And on server side publication:

    Meteor.publish("roles", function (){ 
        return Meteor.roles.find({});
    });
    

    In documentaion of alanning:roles says "The currently logged-in user's roles field is automatically published to the client.". I think there was some kind of timing issue with this one and that caused this problem. Because after adding waitOn the problem just disappeared.