[Solved] Weird bug with groups and meteor roles

So in my routes (FlowRouter) I have a group for my admin panel

var ACPRoutes = FlowRouter.group({
    prefix: '/admin',
    name: 'admin',
    triggersEnter: [function(context, redirect) {
        if(!Meteor.userId()) {
            FlowRouter.go('/');
        } else {
            if(!Roles.userIsInRole(Meteor.userId(), ['admin'])) {
                FlowRouter.go('/');
            }
        }
    }],
    action: function() {
        Session.set('DocumentTitle', 'Admin Control Panel');
    }
});

The problem here is that if I reload the page with CTRL+R or navigate to /admin through anything that is not a link on the site, the role check always return false. Why is that? How can it be fixed?

Often the data about which roles a user is in hasn’t been loaded by the time the router fires.

I have this block of code at the top of my routes file to wait for the Roles publication before allowing routing:

// Pause FlowRouter until Roles information is ready
FlowRouter.wait();
Tracker.autorun(() => {
    // if the roles subscription is ready, start routing
    // there are specific cases that this reruns, so we also check
    // that FlowRouter hasn't initalized already
    if (Roles.subscription.ready() && !FlowRouter._initialized) {
        FlowRouter.initialize();
    }
});
2 Likes

That’s very useful! Thank you.