2016-07-14 54 views
1

我正在开发一个使用angularJS和PHP的网站。用户可以登录,如果凭证是有效的,如果有效,PHP设置会话并返回存储在localStorage中的令牌。AngularJS-从网站注销不工作

我创建了一个服务来检查令牌的真实性。我也有一个注销控制器。但是我的注销功能无法正常工作。我删除本地存储令牌并销毁会话,然后导航到索引页面,但仍然可以查看其他页面更改URL。

这是我登录控制器

(function() { 

    angular 
    .module('myApp.login', []) 

    .controller('LoginController', function($scope, $http, $location) { 
    var vm = this; 

    $scope.post = {}; 
    $scope.post.login = []; 
    $scope.vm = {}; 
    $scope.index = ''; 

    var baseUrl = 'api/'; 

    // function to submit the form after all validation has occurred    
    vm.login = function(isValid) { 
     // check to make sure the form is completely valid 
     if (isValid) { 
     $http({ 
      method: 'post', 
      url: baseUrl + 'login', 
      data: $.param($scope.vm), 
      headers: { 
       'Content-Type': 'application/x-www-form-urlencoded' 
      } 
      }) 
      .success(function(data, status, headers, config) { 
      if (data.success) { 
       if (localStorage['token']) { 
       localStorage.removeItem('token'); 
       } 
       localStorage.setItem("token", JSON.stringify(data.login_token)); 

       $location.path('/home'); 
      } else { 

       if (localStorage['token']) { 
       localStorage.removeItem('token'); 
       } 

       vm.errorMessage = data.msg; 
      } 
      }). 
     error(function(data, status, headers, config) { 
      if (localStorage['token']) { 
      localStorage.removeItem('token'); 
      } 
      vm.errorMessage = data.msg; 
     }); 
     } 
    }; 


    }); 

})(); 

一旦登录成功,设置令牌。你可以看到,上面再我重定向用户家庭控制器,看起来像这样:

-(function() { 

    angular 
     .module('myApp.home', []) 

    .factory('myHomeService', function($http) { 
     var baseUrl = 'api/'; 
     return { 
     getUserSessInfo: function() { 
      return $http.get(baseUrl + 'get_user_session'); 
     } 
     }; 
    }) 

    .controller('HomeController', function($scope, $routeParams, myHomeService, AuthService) { 
     var vm = this; 
     var token; 
     if (localStorage['token']) { 
      token = JSON.parse(localStorage['token']); 
     } else { 
      token = ""; 
     } 

     if (token) { 
      AuthService.checkToken(token); 

      //To get user session value 
      myHomeService.getUserSessInfo().success(function(data) { 
      vm.id = data.id; 
      //vm.userName = data.username; 
      }); 

      $scope.logout = function() { 
      var data = { 
       token: token 
      } 
      AuthService.logOut(token); 
      } 

     }); 
    })(); 

在家居控制器,我检查令牌和调用哪个做用户认证服务AuthService

这里是AuthService。它有两个功能。一个检查令牌和其他要注销。

(function() { 

angular 
.module('myApp.AuthenticationService', []) 

.factory('AuthService', ["$http", "$location", function($http, $location){ 
    var vm = this; 
    var baseUrl = 'api/'; 
    vm.checkToken = function(token) 
    {   
     var data = {token: token}; 

     $http.post(baseUrl + 'validateUserToken', data).success(function(response) 
     { 
      if (response.msg === "unauthorized") 
      { 
       //console.log("Logged out"); 
       $location.path('/login'); 
      } 
      else 
      { 
       //console.log("Logged In"); 
       return response.msg; 
      } 
     }).error(function(error) 
     { 
      $location.path('/login'); 
     }) 

    } 

    vm.logOut = function(token) 
    {   
     var data = {token: token}; 

     $http.post(baseUrl + 'destroyUserToken', data).success(function(response) 
     { 
      if (response.msg === "Logged out") 
      { 
       localStorage.clear(); 
       //console.log("Logged out"); 
       $location.path('/login'); 
      } 
     }).error(function(error) 
     { 
       localStorage.clear(); 
      $location.path('/login'); 
     }) 

    } 
    return vm; 
}]); 

})(); 

而当用户点击一个注销链接,注销控制器被调用。这是它:

(function() { 

    angular 
    .module('myApp.logout', []) 

    .controller('LogoutController', function($scope, $routeParams, AuthService) { 
    var vm = this; 

    //If user is not logged in 
    var token; 
    if (localStorage['entrp_token']) { 
     token = JSON.parse(localStorage['entrp_token']); 
    } else { 
     token = "something stupid"; 
    } 
    AuthService.logOut(token); 

    }); 
})(); 

但即使做完所有这些,用户可以通过更改url导航到较旧的页面。我怎样才能防止这个?

+0

做你的服务器有新的数据响应使用? – Arif

+0

是的..没有使用会话参数的函数返回结果,使用会话参数的函数返回错误。@Arif – Annabelle

+0

所以你想重定向用户回登录页面,如果他们没有登录,并试图查看较旧的页面,对不对? – Arif

回答

0

您需要在路由期间处理事情。当用户没有登录并且请求的页面需要其他的时候,你应该重定向到不同的页面,比如'Unauthorized.html'或类似的东西。

我使用$routeProvider进行路由。我还没有尝试使用角度ui路由器,所以原谅我,如果这不符合您的需求。

我在路由以及requiredRoles上添加了属性loginRequired,以确定当前用户是否可以访问特定页面。

使用$routeChangeStart我检查页面条件是否满足,如当前用户是否登录并有权访问该页面。如果不符合条件,我会导航到其他页面。从我的老项目中提取

代码:

.config(["$locationProvider", "$routeProvider", "$httpProvider", "KeepaliveProvider", "IdleProvider", 
      function ($locationProvider, $routeProvider, $httpProvider, KeepaliveProvider, IdleProvider) { 

      var templateLocation = "/Templates"; 

      $locationProvider.html5Mode({ 
       enabled: true, 
       requireBase: true, 
       rewriteLinks: true 
      }).hashPrefix("#"); 

      $routeProvider 
       .when("/", { 
        templateUrl: templateLocation + "/Home.html", //"/Product-List.html", // 
        controller: "HomeController", //"ProductController", // 
        loginRequired: false, 
        requiredRoles: [] 
       }) 
       .when("/Report", { 
        templateUrl: templateLocation + "/Report.html", 
        controller: "ReportController", 
        loginRequired: true, 
        requiredRoles: ["Admin"] 
       }) 
       .when("/About", { 
        templateUrl: templateLocation + "/About.html", 
        controller: "AboutController", 
        loginRequired: false, 
        requiredRoles: [] 
       }) 
       .when("/Contact", { 
        templateUrl: templateLocation + "/Contact.html", 
        controller: "ContactController", 
        loginRequired: false, 
        requiredRoles: [] 
       }) 
       .when("/Register", { 
        templateUrl: templateLocation + "/Register.html", 
        controller: "RegisterController", 
        loginRequired: false, 
        requiredRoles: [] 
       }) 
       .when("/Login", { 
        templateUrl: templateLocation + "/Login.html", 
        controller: "LoginController", 
        loginRequired: false, 
        requiredRoles: [] 
       }) 
       .when("/User-List", { 
        templateUrl: templateLocation + "/User-List.html", 
        controller: "UserController", 
        loginRequired: true, 
        requiredRoles: ["Admin", "Secretary"] 
       }) 
       .when("/User-Profile/:userId", { 
        templateUrl: templateLocation + "/User-Profile.html", 
        controller: "UserController", 
        loginRequired: true, 
        requiredRoles: [] 
       }) 
       .when("/TermsAndCondition", { 
        templateUrl: templateLocation + "/Terms-And-Condition.html", 
        controller: "SupportController", 
        loginRequired: false, 
        requiredRoles: [] 
       }) 
       .when("/EmailConfirmed", { 
        templateUrl: templateLocation + "/EmailConfirmed.html", 
        controller: "SupportController", 
        loginRequired: false, 
        requiredRoles: [] 
       }) 
       .when("/ResetPassword", { 
        templateUrl: templateLocation + "/ResetPassword.html", 
        controller: "SupportController", 
        loginRequired: false, 
        requiredRoles: [] 
       }) 
       .when("/ForgotPassword", { 
        templateUrl: templateLocation + "/ForgotPassword.html", 
        controller: "SupportController", 
        loginRequired: false, 
        requiredRoles: [] 
       }) 
       .when("/Unauthorized", { 
        templateUrl: templateLocation + "/Unauthorized.html", 
        controller: "UnauthorizedController", 
        loginRequired: false, 
        requiredRoles: [] 
       }) 
       .when("/ErrorHandler", { 
        templateUrl: templateLocation + "/ErrorHandler.html", 
        controller: "ErrorController", 
        loginRequired: false, 
        requiredRoles: [] 
       }) 
       .otherwise({ 
        templateUrl: templateLocation + "/Error404.html", 
        controller: "ErrorController", 
        loginRequired: false, 
        requiredRoles: [] 
       }); 

     }])    
.run(["$q", "$rootScope", "$location", "AccountService", "Idle", function ($q, $rootScope, $location, AccountService, Idle) { 

      Idle.watch(); 
      var templateLocation = "/Templates"; 
      var postLogInRoute; 

      $rootScope.$on("$routeChangeStart", function (event, nextRoute, currentRoute) { 
       if (AccountService.isLoggedIn() && 
        (nextRoute.templateUrl == templateLocation + "/Register.html" || 
        nextRoute.templateUrl == templateLocation + "/Login.html")) { 
        $location.path("/Unauthorized").replace(); 
        postLogInRoute = $location.path(); 
       } 
       else if (nextRoute.loginRequired && !AccountService.isLoggedIn()) { 
        $location.path("/Login").replace(); 
        postLogInRoute = $location.path(); 
       } 
       else if (nextRoute.templateUrl.length != templateLocation + "/Unauthorized.html" && !AccountService.isUserAuthorized(nextRoute.requiredRoles)) { 
        $location.path("/Unauthorized").replace(); 
        postLogInRoute = $location.path(); 
       } 
       //else if (postLogInRoute && AccountService.isLoggedIn()) { 
       // $location.path(postLogInRoute).replace(); 
       // postLogInRoute = null; 
       //} 
       else { 
        // Do nothing 
       } 
      }); 

     }]) 
1

您可以使用您的路线resolve找出如果用户登录或没有渲染模板之前。

检查这个Fiddle有一个想法,当用户通过更改网址导航到旧的页面怎么办呢

var onlyLoggedIn = function ($location,$q,Auth) { 
    var deferred = $q.defer(); 
    if (Auth.isLogin()) { 
     deferred.resolve(); 
    } else { 
     deferred.reject(); 
     $location.url('/login'); 
    } 
    return deferred.promise; 
}; 


angular.module('YourModule') 
.factory('Auth', function() { 
var isLogin = function() { 
console.log(localStorage.isLogged) 
return localStorage.isLogged === "true"; 
} 
return {isLogin: isLogin} 
}) 

.config(function ($routeProvider) { 
    $routeProvider. 
    when('/home', { 
     templateUrl: 'embedded.home.html', 
     controller: 'HomeController' 
    }). 
    when('/about', { 
     templateUrl: 'embedded.about.html', 
     controller: 'AboutController', 
     resolve: {loggedIn: onlyLoggedIn} 
    }). 
    otherwise({ 
     redirectTo: '/home' 
    }); 
}); 
+0

好的,我会试试这个。 @Arif – Annabelle