ykaragol
ykaragol

Reputation: 6221

What is the correct hook for Ember Route to check authorization?

In an Ember.js application, you can use various hooks to check authorization. There are beforeModel, willTransition, redirect hooks on route. also the same events applies on Router.

I'm developing authorization infrastructure for a project. All the route's are written by developers. But an abstract-route (which is extended by all routes) is my code.

  1. If I implement beforeModal or redirect hook in an abstract-route, when a developer writes his own beforeModal methods, my hook will be overwritten.
  2. If I implement willTransition, checking code will be laid on a route that starts transition. From the guide, it seems that willTransition is applicable when leaving the route.
  3. Is it a correct way to handle Router's events?

So what is the correct way to check authorization and abort/prevent transition?

Upvotes: 0

Views: 323

Answers (2)

Gennady Dogaev
Gennady Dogaev

Reputation: 5991

There is a nice plugin for authorization, ember-simple-auth, no need to re-invent the wheel.

If you insist to develop your own solution, you will need to: 1) Modify an adapter for ember data (to include auth headers in all queries) 2) Implement error handling on application route (handle 401 error) 3) (optional) Create a mixin for routes to check authorization on client side. beforeModel is a good place for this check, I guess. If developer will need to implement their own beforeModel hook, they just need to put this line in the beginning: this._super(...arguments);

Upvotes: 1

nucleartide
nucleartide

Reputation: 3988

Use beforeModel. Example from ember-simple-auth:

beforeModel(transition) {
  if (!this.get('session.isAuthenticated')) {
    transition.abort();
    this.transitionTo(Configuration.authenticationRoute);
  } else {
    return this._super(...arguments);
  }
}

As Gennady suggests, you should look into ember-simple-auth since it does exactly what you want.

Upvotes: 1

Related Questions