Reputation: 3566
Im using FlowRouter
with FlowTemplate
and in both/router/router.js
I am checking is it user in role admin
:
....
action: function () {
if(Roles.userIsInRole(Meteor.userId(), 'admin')){
FlowLayout.render('layout', {
sidebar: 'sidebar', main:'admin', cart:'cart'
})
} else {
FlowLayout.render('layout', {
sidebar: 'sidebar', main:'unauthorised', cart:'cart'
})
}
console.log(Meteor.userId());
}
....
and returns FALSE
, but when I use it in the WEB console is TRUE
. This line console.log(Meteor.userId());
output the correct userID
and when I am logged in, if I do this in the WEB console Roles.userIsInRole(Meteor.userId(), 'admin')
, it is TRUE
. If I do this Meteor.user().roles
, the result is ['admin']
If I check in the template is it user in role:
{{#if isInRole 'admin' }}
ADMIN
{{/if}}
It is TRUE
, but in the router.js
returns FALSE
.
How to fix it ?
Upvotes: 1
Views: 336
Reputation: 2386
yep, sounds like the timing issues i encountered. 2 race conditions i had to solve (one with AccountsTemplates, the other with the roles being ready). it's discussed here:
https://github.com/kadirahq/flow-router/issues/608
here is my solution. it goes at the top of the routes.js:
import {Tracker} from 'meteor/tracker';
if (Meteor.isClient) {
FlowRouter.wait();
let tracker;
let self = this;
self.getATReady = () => AccountsTemplates._initialized;
let timer = Meteor.setInterval(function() {
if (self.getATReady()) {
tracker.invalidate();
clearInterval(timer);
}
}, 500);
tracker = Tracker.autorun(function() {
if (!FlowRouter._initialized && Roles.subscription.ready() && self.getATReady()) {
clearInterval(timer);
FlowRouter.initialize();
}
});
}
basically, this code prevents the initialization of FlowRouter until both the roles and AccountsTemplates are ready. once they're both ready, FR is initialized and you can use your routes knowing you can check roles.
i've had this fix in since August 2016, across several Meteor versions, and i've not seen the problem recur.
Upvotes: 1
Reputation: 16478
It is likely that the roles
field is received at a later stage (based on a different subscription).
You should make sure that this subscription is ready - either directly or by using some other mechanism to make sure that you get the field (for example making sure that it is an array), and only then make the routing/rendering decision.
Upvotes: 2