2015-05-23 19 views
0

我使用Devise在我的Rails和Angular應用程序中進行身份驗證。我試圖根據用戶是否通過身份驗證來對其中一個狀態執行條件語句。AngularJS:基於驗證的UI路由器條件

我使用onEnter回調函數來確定用戶是否通過身份驗證。

路線:

// Dashboard state 
.state('dashboard', { 
    url: '/dashboard', 
    templateUrl: 'dashboard.html', 
    controller: 'MainCtrl', 
}) 

// Login state 
.state('login', { 
    url: '/login', 
    templateUrl: '_login.html', 
    controller: 'AuthCtrl', 
    onEnter: ['$state', 'Auth', function($state, Auth) { 
    Auth.currentUser().then(function(){ 
     $state.go('dashboard'); 
    }) 
    }] 
}) 

// Register state 
.state('register', { 
    url: '/register', 
    templateUrl: '_register.html', 
    controller: 'AuthCtrl', 
    onEnter: ['$state', 'Auth', function($state, Auth) { 
    Auth.currentUser().then(function(){ 
     $state.go('dashboard'); 
    }) 
    }] 
}) 

$urlRouterProvider.otherwise('dashboard'); 

導航控制器

// NAV controller 
// ------------------------------ 
.controller('NavCtrl', ['$scope', 'Auth', 

    // Main scope (used in views) 
    function($scope, Auth) { 

     $scope.signedIn = Auth.isAuthenticated; 
     $scope.logout = Auth.logout; 

     Auth.currentUser().then(function (user){ 
      $scope.user = user; 
     }); 

     $scope.$on('devise:new-registration', function (e, user){ 
      $scope.user = user; 
     }); 

     $scope.$on('devise:login', function (e, user){ 
      $scope.user = user; 
     }); 

     $scope.$on('devise:logout', function (e, user){ 
      $scope.user = {}; 
     }); 
    } 

]) 

身份認證控制器

// Authentification controller 
// ------------------------------ 
.controller('AuthCtrl', ['$scope', '$state', 'Auth', 

// Main scope (used in views) 
function($scope, $state, Auth) { 

    $scope.login = function() { 
     Auth.login($scope.user).then(function(){ 
      $state.go('home'); 
     }); 
    }; 

    $scope.register = function() { 
     Auth.register($scope.user).then(function(){ 
      $state.go('home'); 
     }); 
    }; 

} 

]); 

如何確定儀表盤上的狀態未驗證用戶,並重定向他們登錄?

回答

0

你有幾種選擇走下來這樣的事情:

1)在MainCtrl添加一個init()函數,檢查if(!Auth.isAuthenticated) $state.go('login')。缺點是如果在控制器被實例化後失去認證,這不會重定向它們。

2)我認爲你正在做一些需要認證的後端調用。如果是這樣,如果他們沒有被認證,你可以通過http攔截器捕獲401響應,並重定向他們在那裏登錄。這是我總是使用的方法。

3)附上$手錶Auth.isAuthenticated做從那裏重定向