Benny Alex
Benny Alex

Reputation: 156

Ember: wait for promise in router.willTransition hook

I want to allow some users to enter a route and others don't.

I used simple auth for authentication and it will load the user data with a promise. The Problem is that willTransition() does not wait until my user is loaded so, it will show the index route before I can check if the user has access to it.

So in router.js I have:

willTransition(oldRoute, nextRoute, transition) {
    return this.get('session').authenticate('authenticator:application').then(() => {
      if(this.get('user.isAdmin')) return true
      else alert('not allowed to enter')
    })
}

This is just an example in real I have more like user.isCat and cat are allowed to enter /cats and /cute routes.

I know that I can check user.isAdmin also in beforeModel() of the route but I have many other routes and permission groups, so I want to have a single place in the router to manage that.

Upvotes: 2

Views: 1131

Answers (2)

Josa
Josa

Reputation: 746

You could abort the transition and retry it after the promise has been resolved.

So your example would look like this:

willTransition(transition) {
  if (this.get('pendingTransition.targetName') == transition.targetName) {
    this.set('pendingTransition', null);
    return true;
  }

  transition.abort();

  this.get('session').authenticate('authenticator:application').then(() => {
    if (this.get('user.isAdmin')) {
      this.set('pendingTransition', transition);
      transition.retry();

    } else {
      alert('not allowed to enter')
    }
  })
}

See:

Upvotes: 5

iOS dev
iOS dev

Reputation: 470

willTransitionTo does not stop on promises. So the best way to achieve is to abort the transition in these kind of scenarios. Something like below could do the trick for you.

willTransition: function(transition) {
   return this.get('session').authenticate('authenticator:application').then(() => {
      if(!this.get('user.isAdmin')){
         transition.abort();
      }
      if(!this.get('user.isCat')){
         transition.abort();
      }
   });
}

Hope this helps.

Upvotes: 0

Related Questions