Skip to content Skip to sidebar Skip to footer

Angularjs Authentication Using $locationchangestart

I'm authenticating an angular app code given below, Basically I'm checking token from backend called if token is valid then we can allow users to view allowed page. It's working so

Solution 1:

i don't want to show jobs page initially for few seconds it should be redirect quickly or it will not load jobs page.

When using the ui-router, avoid putting code in the $locationChangeStart block. This will cause conflicts with ui-router operation.

To prevent the jobs page from loading, check the authorization in the resolver for the state.

$stateProvider.state("jobs", {
    url: "/jobs",
    templateUrl: "views/dashboard.html",
    controller: "JobController as JobCtrl",
    resolve : {
        formInfo : ["AuthService",function (AuthService) {
            return AuthService.getFormInfo();
        }],
        //CHECK permission
        permission: ["AuthService", function (AuthService) {
            return AuthService.checkPermission()
              .then(function(data) {
                if(!data.active){
                    return data 
                } else {
                    //REJECT if not authorizedthrow"Not Authorized";
                };
            }).catch(function(error) {
                console.log("ERROR");
                throwerror;
            });
        }];
    }
})

By rejecting the resolve, the state change will be aborted and the page will not load.


Update

I can put in resolve state but if we have more state for example we have 50 different URL then every time do we have to put permission:

["AuthService", function (AuthService) { 
       returnAuthService.checkPermission() 
         .then( function(data) { 
           if(!data.active){ 
               return data
           } else { 
               //REJECT if not authorized throw "Not Authorized";
           }; 
       }).catch( function(error) { 
           console.log("ERROR");
           throw error;
       });

All of that code can be re-factored into a service:

app.service("permissionService",["AuthService", function (AuthService) { 
    this.get = function () {
       returnAuthService.checkPermission() 
         .then( function(data) { 
           if(!data.active){ 
               return data
           } else { 
               //REJECT if not authorized throw"Not Authorized";
           }; 
       }).catch( function(error) { 
           console.log("ERROR");
           throw error;
       });
    };
}]);

Then use it in each resolver:

//CHECK permissionpermission: ["permissionService", function (permissionService) {
            return permissionService.get();
        }];

By re-factoring the code, the resolver can be greatly simplified.

Post a Comment for "Angularjs Authentication Using $locationchangestart"