Reputation: 819
I need to perform authorization on what routes the user is allowed to access. According to the documentation for ember i should use 'WillTransition'
http://guides.emberjs.com/v1.11.0/routing/preventing-and-retrying-transitions/
When a transition is attempted, whether via {{link-to}}, transitionTo, or a URL change, a willTransition action is fired on the currently active routes. This gives each active route, starting with the leaf-most route, the opportunity to decide whether or not the transition should occur.
So i put this code in my application route to try and first log all the times its called.
actions: {
willTransition: function(){
console.log('Transitioning');
}
}
This works fine when i'm inside my app and then click to transition to another route. But if i go directly to a protected route it doesn't fire. Ex. /myapp/protected/route
But with the debug flag
NV.APP.LOG_TRANSITIONS = true;
set i get these logs inside the console. Even when the 'WillTransition' event hasn't fired.
Preparing to transition from 'myapp.index' to 'myapp.protected.index'
Transitioned into 'myapp.protected.index'
So i go and look at the log event in the ember source and i see
/**
Handles notifying any listeners of an impending URL
change.
Triggers the router level `willTransition` hook.
@method willTransition
@private
@since 1.11.0
*/
willTransition: function (oldInfos, newInfos, transition) {
run['default'].once(this, this.trigger, "willTransition", transition);
if (property_get.get(this, "namespace").LOG_TRANSITIONS) {
Ember['default'].Logger.log("Preparing to transition from '" + EmberRouter._routePath(oldInfos) + "' to '" + EmberRouter._routePath(newInfos) + "'");
}
},
Right above the line that writes the console log is a line that looks like it is supposed to fire the event, but its not reaching my code. What am i doing wrong?
Upvotes: 3
Views: 1880
Reputation: 313
Authorization check it might be better directly on the routes, in the beforeModel function.
You can create a mixin and implement it on every route
App.Auth = Ember.Mixin.create({
beforeModel: function(){
if(!this.get('userAuthorized')){
//prevent entering and go to login route
this.transitionTo('login');
//show msg to user that it needs access
}
}
});
You can implement the mixin on routes like this
App.UserStuffRoute = Ember.Route.extend(App.Auth,{ });
Upvotes: 2