1

TL;DR? I made a jsFiddle here if you want to go to (nearly) working code.

Suppose I have an Ember router described below. I'd like to have it manage the state of the current user's authentication. Is it possible to cancel a state transition?

App.Router = Ember.Router.extend({

    init: function() {
        this.set('authenticated', false);
        return this._super();
    },

    /*
     * "Authentication" method - just toggle the state
     */
    toggleAuthentication: function() {
        var auth = this.get('authenticated');
        this.set('authenticated', !auth);
        if (auth) {
            this.transitionTo('root.home');
        } else {
            this.transitionTo('loggedIn.home');
        }
    },

    /*
     * Root state
     * Logged out state tree
     */
    root: Ember.State.extend({
        home: Ember.State.extend()
    }),

    /*
     * Authenticated state tree
     */
    loggedIn: Ember.State.extend({

        /* Enter checks user is authenticated */
        enter: function(manager, transition, async, resume) {

            if (manager.get('authenticated')) {
                // proceed
            } else {
                // cancel the transition & redirect to root.home
            }
        },

        /* Exit sets authenticated to false just to be sure */
        exit: function(manager, transition, async, resume) {
            manager.set('authenticated', false);
        },

        /* Sub-states */
        home: Ember.State.extend(),

        news: Ember.State.extend({
            list: Ember.State.extend()
        })
    })
});
Dean Brundage
  • 2,038
  • 18
  • 31
  • This is covered in another stackoverflow question http://stackoverflow.com/questions/11190928/emberjs-conditional-redirect-in-router – 林奕忠 Jan 09 '13 at 00:09

2 Answers2

2

That would be a "Not yet". https://github.com/emberjs/ember.js/issues/745

Dean Brundage
  • 2,038
  • 18
  • 31
0

The ticket Dean mentioned has been closed; however there is a way to do this. You can override Router.enterState, as follows:

App.Router = Ember.Router.extend({
    enterState: function(transition) {
        if (!transition.finalState.get('isLeafRoute') || !App.User.get('authenticated')) {
            // Only transition when your user is authenticated
            this._super.apply(this, arguments);
        } else {
            // Otherwise "cancel this transition and move to the login state
            App.get('router').transitionTo('users.login');
        }
    },

    root: Ember.Route.extend({}) // Your routes
});

This is working for me in ember 1.0 pre. Personally I think this approach is justified as there are many ways to transition to a route (URL, action, etcetera) and many ways to suddenly get unauthenticated. I'm not sure this is actually something intended by the Ember team though ;).

Elte Hupkes
  • 2,773
  • 2
  • 23
  • 18