Restrict willtransition for certain model attributes


#1

I would like restrict access for editing certain resources to the authors of those items.

A logical place to police such access seems to be within the willTransition hook.

From the transition object I am able to access transition.targetName which is fine, but I require the model.author field of the target route as well in order to decide whether or not the current_user is allowed to proceed.

However, it is not very clear to me if the transition object contains this information somewhere (I find the documentation unclear).

Maybe my approach is incorrect and there’s another standard more elegant manner to enforce authorization for routes.


#2

I would use the destination route’s afterModel hook for this. To prevent the transition either transition elsewhere

this.transitionTo('some.route')

or abort it

transition.abort();

Something like this:

afterModel(model, transition) {
  if (model.get('author.id') !== this.get('currentUser.id')) {
    console.debug("not allowed");
    this.transitionTo('application'); 
  }
  return this._super(...arguments);
}

#3

Thanks @tcjr, that’s the right approach.

Earlier I’d tried the same thing within the afterModel() hook, but the page still showed in a brief flash before being redirected, and when I hit the back button it didn’t work either.

Come to the rescue ‘transition.abort()’ and ‘return this._super(...arguments);