2015-01-21 82 views
0

我正在使用JWT管理身份驗證。我正嘗試使用ng-show在我的導航欄中顯示/隱藏登錄和註銷按鈕。它工作正常,但在我刷新頁面後,它看起來像我不再登錄,變量$ scope.isAuthenticated刷新後返回false,我如何保持$ scope.isAuthenticated true只要我登錄?

app.js

myApp.controller('UserCtrl', function ($scope, $http, $window) { 
    $scope.user = {username: '', password: ''}; 
    $scope.isAuthenticated = false; 
    $scope.welcome = ''; 
    $scope.message = ''; 

    $scope.submit = function() { 
    $http 
     .post('/authenticate', $scope.user) 
     .success(function (data, status, headers, config) { 
     $window.sessionStorage.token = data.token; 
     $scope.isAuthenticated = true; 
     var encodedProfile = data.token.split('.')[1]; 
     var profile = JSON.parse(url_base64_decode(encodedProfile)); 
     $scope.welcome = 'Welcome ' + profile.first_name ; 
     $scope.error = ''; 
     }) 
     .error(function (data, status, headers, config) { 

     delete $window.sessionStorage.token; 
     $scope.error = 'Error: Invalid user or password'; 
     $scope.welcome = ''; 
     }); 
    }; 

    $scope.logout = function() { 
    $scope.welcome = ''; 
    $scope.message = ''; 
    $scope.isAuthenticated = false; 
    delete $window.sessionStorage.token; 
    }; 

}); 

的index.html

<div ng-controller="UserCtrl"> 
     <span ng-show="isAuthenticated">{{welcome}}</span> 
     <form ng-show="!isAuthenticated" ng-submit="submit()"> 
     <input ng-model="user.username" type="text" name="user" placeholder="Username" /> 
     <input ng-model="user.password" type="password" name="pass" placeholder="Password" /> 
     <input type="submit" value="Login" /> 

     </form> 

     <div ng-if="error" class="alert alert-danger"> {{error}}</div> 
     <div ng-show="isAuthenticated"> 
     <a ng-click="callRestricted()" href="">Shh, this is private!</a> 
     <br> 
     <div>{{message}}</div> 
     <a ng-click="logout()" href="">Logout</a> 
     </div> 
    </div> 
+1

您需要以某種方式保存「已認證」狀態(本地存儲,cookie等)並在第一次加載時讀取它(您的主模塊的「運行」模塊是一個很好的選擇) – Phil 2015-01-21 00:45:09

回答

1

您可以檢查是否有在本地存儲令牌和 「isAuthenticated」 設置值,因此使用服務:

$scope.isAuthenticated = AuthService.isAuthenticated(); 

然後,AuthService將負責檢查本地存儲器中是否有令牌。