2015-01-21 84 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将负责检查本地存储器中是否有令牌。