javascriptangularjsangularjs-authentication

AngularJS - after logging in and close tab, it is not redirecting to home


I have created a angularJS application with yeoman, grunt and bower. I have tried a simple login example. After loggin in, it will goto home page. And for any route changes it will check for whether the user is logged in or not. If logged in, it will redirect to home or the particular route, otherwise re-route to login page. This all working fine for me.

Here is app.js

'use strict';
//Define Routing for app
angular.module('mainApp', []).config(['$routeProvider', '$locationProvider',
  function($routeProvider,$locationProvider) {
    $routeProvider
    .when('/login', {
        templateUrl: 'login.html',
        controller: 'LoginController'
    })
    .when('/register', {
        templateUrl: 'register.html',
        controller: 'RegisterController'
      })
    .when('/home', {
       templateUrl: 'views/home.html',
       controller: 'homeController'
    })
    .otherwise({
       redirectTo: '/home'
    });
}])
.run( function($rootScope, $location) {
    // register listener to watch route changes
    $rootScope.$on( "$routeChangeStart", function() {
        var url=$location.path();
        var location=url.replace("/","");
        var authnotallowed=false;
        if(location.indexOf("login")!=-1||location.indexOf("register")!=-1){
            authnotallowed=true
        }
        if ( $rootScope.loggedUser == null ) {
            // not logged user, should be going to #login
            if(authnotallowed){
                $location.path(url);
            } else{
                $location.path( "/login" );
            }
        } else {
            // not going to #login, should redirect now
            if(authnotallowed){
                $location.path("/home");
            } else{
                $location.path(url);
            }

        }
    });
});

angular.module('mainApp').factory("page", function($rootScope){
    var page={};
    var user={};
    page.setUser=function(user){
        $rootScope.loggedUser=user;
    }
    return page;
});

Here is my loginControler.js

'use strict';

angular.module('mainApp').controller('LoginController', function($scope, $location, page) {
    $scope.user = {};
    $scope.loginUser=function(){
        var name=$scope.user.name;
        var pwd=$scope.user.password;
        if(name=="1234" && pwd=="1234"){
            page.setUser($scope.user);
            $location.path( "/home" );
        } else {
            alert("Invalid credentials");
        }
    }
});

All are working fine for me.

Since I am using grunt, the url is like http://localhost:9000/#/login After logging in it is going to home page, if I put like http://localhost:9000/#/login or http://localhost:9000/#/register or any other url. And if I logout and try any page, it goes to login.

The problem is,after logging in when I try just http://localhost:9000/ or I close tab and open the url again, it is going to login page (means the loggedUser is null).

Why it is happening? And how can I solve it?

Do I need to set some cookies or something? If so, how?


Solution

  • Well, after you reloading your page, you reloading your application. $rootScope.loggedUser becomes null. And yes, you may use coockies to store session. Here is angularjs docs for cookies

    And don't forget to include angular-cookies.js

    First add module dependency:

    angular.module('mainApp', ['ngCookies'])
    

    Second: inject $cookieStore service

    angular.module('mainApp', ['ngCookies']).controller('LoginController', function($scope, $location, page, $cookieStore)
    

    Third: use cookies:

     $scope.loginUser=function(){
            var isLoggedIn = $cookieStore.get('isLoggedIn');
    
            var name=$scope.user.name;
            var pwd=$scope.user.password;
            if(name=="1234" && pwd=="1234" || isLoggedIn){
                page.setUser($scope.user);
                $location.path( "/home" );
                $cookieStore.put('isLoggedIn', true);
            } else {
                $cookieStore.remove('isLoggedIn');
                alert("Invalid credentials");
            }
        }
    

    But be adviced, this is a very basic, simple and unsecure way to maintain session!