AngularJS - 评估路线中的cookie和模板

时间:2013-09-12 19:40:56

标签: javascript angularjs cookies

我正在尝试使用Cookie整理登录系统,以便用户的登录在离开应用程序后仍然存在。我能够正确设置cookie,但我不知道如何使用存储的cookie限制用户访问登录屏幕(如果他们已经登录)。

我认为最好的方法是在路线内。这就是我目前的文件:

var routes = angular.module('we365', ['rcForm', 'ngCookie', 'ngCookies']);
routes.config(function ($routeProvider) {

    $routeProvider
    .when('/login', {

        templateUrl: 'views/login.html',
        controller: 'loginCtrl'

    })

    .when('/', {// get digest view

        templateUrl: 'views/getDigest.html',
        controller: 'GetDigestCtrl'

    })

    .when('/artifact/:artifact_id', {// single artifact view

        templateUrl: 'views/artifact.html',
        controller: 'artifactCtrl'

    })

    .otherwise({

        redirectTo: '/'

    });

});

此外,我想隐藏父视图中的“登录”按钮,以便用户无法点击它。这就是现在的观点:

<div class="container">
    <div class="page-header col col-lg-12">
        <h1>Welcome!</h1>
        <a href="/#/login/" class="btn btn-sm btn-primary button-login">Login</a>
        <a href="/#/" class="btn btn-sm btn-primary button-getDigest">Load Digest Data</a>
    </div>
</div>

1 个答案:

答案 0 :(得分:2)

有很多方法,我有两个是我最喜欢的方式:

1)检查路线变更

angular.module('MyApp', [])
.run(function($rootScope, myLoginService) {
$rootScope.$on('$routeChangeStart', function () {
  if (!myLoginService.isUserLoggedIn()) {
    $location.path('/login');
  }
});

您可以将isUserLogged替换为接收用户想要去的地方的映射器服务;如果用户具有适当的权限(以令牌的形式存储在cookie或本地存储中),则让路由成功。否则,显示错误,或将他路由到任何你想要的地方。在我的例子中,myLoginService检查localStorage。

2)对服务器的任何数据请求都有一个包含在标头中的令牌;在用户被重定向时,拦截并存储失败的请求(401)

这个更适用于CRUD应用程序而不一定用于路由,但概念很简单:用户A可以执行N个操作,只要他/她有权这样做;如果他试图执行他不被允许的动作(或M动作),那么请求被拦截并排队,以便让他向可以执行这些动作的用户进行身份验证

.factory('securityInterceptor', ['$injector', 'securityRetryQueue', function($injector, queue) {
  return function(promise) {
    // Intercept failed requests
    return promise.then(null, function(originalResponse) {
      if(originalResponse.status === 401) {
        // The request bounced because it was not authorized - add a new request to the retry queue
        promise = queue.pushRetryFn('unauthorized-server', function retryRequest() {
          // We must use $injector to get the $http service to prevent circular dependency
          return $injector.get('$http')(originalResponse.config);
        });
      }
      return promise;
    });
  };
}]);

同样,这是针对更多“类似数据”的请求,而不一定是路由。这是从AngularJS示例应用中窃取的。您应该查看它以获取更多示例。