AngularJS - prevent not authenticated user from accessing given routes

前端 未结 2 549
梦毁少年i
梦毁少年i 2021-01-13 10:01

In my app when user is logged in I have authService which sets internal flag isAuthenticated. Now on every route change I have listener attached to

2条回答
  •  长情又很酷
    2021-01-13 10:47

    I'd do something like this in the top level controller, which would be the first controller that's called when the page is refreshed (apologize for typos in the js, I'm a coffeescript guy):

    var authCheck = function (event, next, current) {
        if(isRouteRestricted(next)) {
            authService.currentUser().then(null, function() {
                $location.path('/login');
            });
        }
    }
    
    authCheck(null, populateNextSomehow).then(function () {
        // all of your controller code, probably in a separate function
    });
    
    $rootScope.$on("$routeChangeStart", authCheck);
    

    This will ensure that the controller code cannot be called until the authCheck is complete.

提交回复
热议问题