Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular route async authorization

Angular doesn't provide any authorization/access permission on routing (I'm talking default Angular route 1.x and not beta 2.0 or UI route). But I do have to implement it.

The problem I'm having is that I have a service that calls server to provide this info and returns a promise. This data however is only obtained once and then cached on the client, but it still needs to be obtained once.

I would now like to handle $routeChangeStart event that checks whether next route defines a particular property authorize: someRole. This handler should then get that data using my previously mentioned service and act accordingly to returned data.

Any ideas beside adding resolves to all my routes? Can I do this centrally somehow? Once for all routes that apply?

Final solution

With the help of accepted answer I was able to implement a rather simple and centralized solution that does async authorization. Click here to see it in action or check its inner working code.

like image 836
Robert Koritnik Avatar asked Oct 08 '15 12:10

Robert Koritnik


2 Answers

The most simple way is to deal with current route's resolve dependencies, and $routeChangeStart is a good place to manage this. Here's an example.

app.run(function ($rootScope, $location) {
  var unrestricted = ['', '/login'];

  $rootScope.$on('$routeChangeStart', function (e, to) {
    if (unrestricted.indexOf(to.originalPath) >= 0)
      return;

    to.resolve = to.resolve || {};
    // can be overridden by route definition
    to.resolve.auth = to.resolve.auth || 'authService';
  });

  $rootScope.$on('$routeChangeError', function (e, to, from, reason) {
    if (reason.noAuth) {
      // 'to' path and params should be passed to login as well
      $location.path('/login');
    }
  });
});

Another option would be adding default method to $routeProvider and patching $routeProvider.when to extend route definition from default object.

like image 182
Estus Flask Avatar answered Oct 03 '22 20:10

Estus Flask


ui-router have a lot of events that you can easy manipulate. I always use it.

State Change Events have everything you need. Something like this will be implement in the AngularJS 2.x.

But if you are looking the solution for native Angular 1.x.y router this solution will not help you. Sorry

like image 29
Kirill Husiatyn Avatar answered Oct 03 '22 20:10

Kirill Husiatyn