简体   繁体   中英

if user is logged in, how to restrict the back button, or accessing the login page directly in angularjs

I am trying to implement basic login, logout functionality using angular JS, On successfull login then only My header has to be appeared. once the user is logged in. until he is logged out, if he try to access the login route directly it should redirect to the dash board.

How to achieve this..? i need help in this matter. I have access token stored in the cookie. which will let us know if the user is logged in or not.. if logged in.. my route should not be leading to login route.

for the reference i am adding the code of route.

app.config(["$routeProvider",function($routeProvider){
$routeProvider
    .when("/",{
        templateUrl : 'views/home/login.html',
        controller : 'homeCtrl'
    })

    .when("/dashboard",{
        templateUrl : 'views/home/dashboard.html',
        controller : 'dashboardCtrl',
        authenticated : true
    })

    .otherwise('/',{
        templateUrl : 'views/home/login.html',
        controller : 'homeCtrl'
    })

}]);

app.run(["$rootScope","$location","authFactory",function($rootScope,$location,authFactory){

$rootScope.$auth = authFactory;
$rootScope.$on('$routeChangeStart',function(event,next,current){

    if(next.$$route.authenticated){
        var userAuth = authFactory.getAccessToken();

        if(!userAuth){

            $location.path('/');

        }
    }
});
}]);

I want to restrict the route access to login page if the user is currently logged in..

please help me out

You can handle both conditions separately like below.

var userAuth = authFactory.getAccessToken();

// Redirect to login if auth token is not available
if(next.$$route.authenticated && !userAuth) {
     $location.path('/');
}

// Redirect to dashboard if valid auth token is available and user is in an unauthenticated page (login may be)
if(!next.$$route.authenticated && userAuth) {
     $location.path('/dashboard');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM