使用$ locationChangeStart进行angularjs身份验证 [英] angularjs authentication using $locationChangeStart

查看:60
本文介绍了使用$ locationChangeStart进行angularjs身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在验证下面给出的有角度的应用程序代码,基本上是从后端检查令牌,如果令牌有效,那么我们可以允许用户查看允许的页面.

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.

它在某种程度上起作用,但问题是当我要进入/jobs页面时正在加载某些东西,然后重定向到登录页面,但是我不想在最初显示作业页面几秒钟,它应该被快速重定向,否则就不会加载作业页面.

It's working somewhat but problem is when I'm going to /jobs page is somewhat loading then redirecting to login page but i don't want to show jobs page initially for few seconds it should be redirect quickly or it will not load jobs page.

在app.js中

    var app = angular.module('ttt', ['ui.router', 'ui.bootstrap', 'ngResource', "ngStorage", "ngProgress", "ngCookies", 'angular-jwt', 'ngLodash','tagged.directives.infiniteScroll']);
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', "$httpProvider", function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
    $locationProvider.html5Mode(true);
    $urlRouterProvider.otherwise(function ($stateParams) {
        console.log("val check", $stateParams, window.location);
        window.location.href = "/undefined";

    });
    $stateProvider.state("jobs", {
        url: "/jobs",
        templateUrl: "views/dashboard.html",
        controller: "JobController as JobCtrl",
        resolve : {
            formInfo : ["AuthService",function (AuthService) {
                return AuthService.getFormInfo();
            }]
        }
    }).state("undefined", {
        url: "/undefined",
        templateUrl: "views/pagenotfound.html",
        bodyClass: "errors errors-404 errors-centered"
    }).state("login", {
        url: "/login",
        templateUrl: "views/login.html",
        controller: "LoginController as LoginCtrl",
        resolve : {
            formInfo : ["AuthService",function (AuthService) {
                return AuthService.getFormInfo();
            }]
        }
    })
}]);

app.run(['$rootScope', 'ngProgressFactory', '$state', '$compile', '$location', '$cookies', 'jwtHelper','AuthService', function ($rootScope, ngProgressFactory, $compile, $state, $location, $cookies, jwtHelper,AuthService) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
        $rootScope.progressbar = ngProgressFactory.createInstance();
        $rootScope.progressbar.start();
        $rootScope.location = $location;
    });

  var authPreventer =  $rootScope.$on('$locationChangeStart', function (event, toState, toParams, fromState, fromParams, options) {

        var notCheckRoute = ["/undefined", "/signin", "/login"];
        //event.preventDefault();
         if(notCheckRoute.indexOf($location.path()) !== -1){
            AuthService.checkPermission()
            .then(function(data) {
                //event.preventDefault();
                if(data.active){
                    $location.path('/home'); 
                }else{
                    $location.path('/login');
                }
            });
         }else{
             //event.preventDefault();
            AuthService.checkPermission()
            .then(function(data) {
                if(!data.active){
                    $location.path('/login'); 
                }else{
                    //$location.path('/jobs'); 
                }
            });
         }
    });

    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        $rootScope.progressbar.complete();
        $rootScope.bodyClass = toState.bodyClass;
    });

    $rootScope.$on('$stateChangeError', function (event) {
        //$state.go('undefined');
    });
}]);

在使用中

    app.service('AuthService',['jwtHelper','$cookies','$location','$window','$http','$q',function (jwtHelper,$cookies,$location,$window,$http,$q) {

    this.login = function (token){
        var payload = jwtHelper.decodeToken(token);
    };

    this.logout = function (data) {

    };


var validatetoken = undefined;

this.checkPermission = function () {
    if (!validatetoken) {

        // create deferred object using $q
        var deferred = $q.defer();

        // get validatetoken form backend
        $http.post('/api/validatetoken', {token: $cookies.get('token')})
          .then(function(result) {
            // save fetched validatetoken to the local variable
            validatetoken = result.data;
            // resolve the deferred
            deferred.resolve(validatetoken);
          }, function(error) {
            validatetoken = error;
            deferred.reject(error);
          });
        // set the validatetoken object to be a promise until result comeback
        validatetoken = deferred.promise;
      }

      return $q.when(validatetoken);
}

    this.getFormInfo = function () {
         return $http.get("/api/getloginurl");
    }


}]);

推荐答案

我最初几秒钟不想显示作业页面,应该快速重定向它,否则将不会加载作业页面.

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

使用ui路由器时,避免将代码放入$locationChangeStart.这将导致与ui路由器操作发生冲突.

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 authorized
                    throw "Not Authorized";
                };
            }).catch(function(error) {
                console.log("ERROR");
                throw error;
            });
        }];
    }
})

通过拒绝解决,状态更改将被中止并且页面将不会加载.

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

我可以进入解析状态,但是例如,如果我们有更多状态,则我们有50个不同的URL,那么每次都要输入权限:

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) { 
       return AuthService.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 () {
       return AuthService.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 permission
        permission: ["permissionService", function (permissionService) {
            return permissionService.get();
        }];

通过重构代码,可以大大简化解析器.

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

这篇关于使用$ locationChangeStart进行angularjs身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆