I need a systematic redirection to a login page when user is not authenticated. For that purpose, beforeModel in the application route seemed to be the best option, but it seems that beforeModel is not triggered for all transitions, unlike willTransition, which is always called, but when the route is exited, not entered…
For instance, beforeModel is not called when changing the URL manually.
I’ve read this Gist which explains that willTransition is always called, which I confirm, but it doesn’t explain if beforeModel should always be called or not, and in which conditions.
I’m using Ember 1.2.0 beta 3 but I have the same problem with 1.1.2 and login redirection is actually handled by ember-simple-auth (my issue on the repo: #27).
Could someone explain when should beforeModel be called ?
The Router has a logger that is disabled by default, but here is a jsbin with that logging turned on, to give you a feel for the different phases that the router passes through. (Be sure to look at the developer console.)
Could you show us how you are doing that redirection?
I have come across the same kind of issue before: I was doing a redirection where I was giving a model as parameter.
In that case, the beforeModel handler would not be triggered.
So I simply assumed that beforeModel is only called when the route is trying to determine its model, when it’s not already provided to the route.
@Porecreat@kayhadrin The beforeModel hook should always be called, whether you provided a model or not.
Take a look at the jsbin (open your js console when you click on the links/buttons.)
There are two methods for going to a route (link-to and transitionToRoute), each one with and without a model provided, and you’ll see if you open the console log that the beforeModel and afterModel hooks get called in every case. The only hook that isn’t called is the model hook, and it is only skipped when the model is provided.
@Porecreat The solution is to put the ‘beforeModel’ in the FooIndexRoute rather than in the FooRoute. Because if you changing the URL manually (for example /foo) the route you change to is actually its indexroute (/foo/index). So you have to put the redirection in the index route.