2

我正在使用令牌身份验证,目前如果用户未登录,他们将被定向到“/login”的 url 路径,我希望允许用户转到路径“/createUser”。如果用户未登录,下面的代码会将用户引导至登录页面。如果用户是新用户,我将如何允许他们导航到“/createUser”路径?

angular.module('Demo', [
    'ngRoute'
]).run(function(
  $rootScope,
  $location,
  $http,
  $window,
  AuthFactory,
  UserFactory,
  TitleFactory,
  SkillsFactory
) {
  $rootScope.$on('$routeChangeStart', function(event, next) {
      console.log(next);
      if (AuthFactory.isAuthenticated()) {
        $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('demo.user');

      UserFactory.fetch();
      TitleFactory.fetch();
      SkillsFactory.fetch();
    } else {
     $location.path('/login');
   }
   });
});
4

3 回答 3

0

Have a look at ui-router, which allows you to create state hierarchy. With state hierarchy you can add a "redirect if not logged in" logic just to your 'authenticated' state (ancestor of all states requiring authentication) and let the user switch between other states without any trouble.

于 2014-11-23T17:34:57.670 回答
0

下面的答案是有 ui-router 示例,但您也可以将类似的概念与 ng-route 一起使用。

在您的路由器对象上添加一个属性以指示该路由是否需要身份验证

.config(function ($stateProvider) {
    $stateProvider
      .state('welcome', {
        url: '/',
        templateUrl: 'app/welcome/welcome.html',
        controller: 'WelcomeCtrl',
        **needsAuth: false**
      });
     $stateProvider
      .state('main', {
        url: '/',
        templateUrl: 'app/main/main.html',
        controller: 'MainCtrl',
        **needsAuth: true**
      });
  });

然后在路由更改时,如果页面是安全的并且用户未登录,则将他重定向到登录页面,否则让正常过程继续......

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState)                { //, fromParams
       console.log(toState.name + "," + fromState.name);
           if (toState.needsAuth && !Auth.isLoggedIn()) {
               $toState.go('login');
               event.preventDefault();
           }
    }
于 2014-11-23T17:54:14.193 回答
0

我添加了一个条件来查看路径是否为“/createUser”,并且因为在每次更改路由之前都会触发 $routeChangeStart,如果用户转到“/createUser”,它将不会检查用户是否经过身份验证。我发现解决问题的最简单方法。如果有人注意到答案中有任何缺陷,请告诉我。

$rootScope.$on('$routeChangeStart', function(event, next) {
  if ($location.path() === '/createUser'){
  } else if (AuthFactory.isAuthenticated()) {
    $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('demo.user');
    UserFactory.fetch();
    TitleFactory.fetch();
    SkillsFactory.fetch();
} else {
  $location.path('/login');
}
});
于 2014-11-23T18:30:15.427 回答