page refresh causing user to get log out automatically in angular js

shreyansh picture shreyansh · Feb 2, 2016 · Viewed 11.7k times · Source

I have a Login API which I am using it in my service

function logInToService(callback, errback, login, password, rememberLogin) {
            var url = "User/Login";

            var authorizationHeader = {'Authorization': "Basic " + login + ":" + password};
            httpWrapperService.post(url, {login: login, password: password}, authorizationHeader).then(
                function success(loginToken) {
                    // transform data here

                    self.currentUser.emailAddress = login;
                    self.currentUser.password = password;
                    // store token in a cookie
                    self.currentUser.token = loginToken;
                    $rootScope.currentUser = self.currentUser;


                    if (rememberLogin) {

                        localStorage.userName=login;
                        localStorage.password=password;
                    }

                    httpWrapperService.setAuthenticationToken(loginToken);
                    callback(loginToken);
                },
                function error(errorObject) {
                    errback(errorObject);
                }
            );
        }

And in my header html I am displaying the user name on top when he gets logged in Header.html

 <div class="header-user-menu">
        <div ng-show="isUserLoggedIn() == false ">
            <a href="" ng-click="$state.go('app.sr.login')" class="">{{'HEADER.LOGIN' | translate}}</a>
            <!--<a ui-sref="app.sr.login" class="">{{'HEADER.LOGIN' | translate}}</a>-->
        </div>
        <div ng-show="isUserLoggedIn()" class="userName">{{'HEADER.WELCOME' | translate}} {{currentUser.emailAddress}}</div>

    </div>

and js file is here

(function() {
    'use strict';

    angular
        .module('safe-repository')
        .controller('AppLayoutCtrl', appLayoutCtrl);

    // Implementation of controller 
    appLayoutCtrl.$inject = ['$rootScope', '$scope'];

    function appLayoutCtrl($rootScope, $scope) {


        $scope.isUserLoggedIn = isUserLoggedIn;

        function isUserLoggedIn() {
            if ($rootScope.currentUser
                && $rootScope.currentUser.emailAddress != null
                && $rootScope.currentUser.emailAddress != '') {
                return true;
            }
            return false;
        }

    }
})();

and here I have one registration service where I have defined logInToService method

function registrationService($rootScope, httpWrapperService, $modal, $state, $cookieStore) {
        var self = this;
        // expose functions
        self.hasUserAccessToLevel = hasUserAccessToLevel;
        self.logInToService = logInToService;
        self.getCurrentUserToken = getCurrentUserToken;
        self.showRegistrationViewForLevel = showRegistrationViewForLevel;
        self.currentUser = {
            //emailAddress: '',
            //password: '',
            //token: ''
        }

        $rootScope.currentUser = null;
        self.currentUserToken = null;

 function logInToservice (------){----}})();

The problem is that every time when user presses page refresh F5 , user gets logged out. Even though I am trying to store the data in localstorage , but actually I am not getting the flow of control.

Answer

Boris Serebrov picture Boris Serebrov · Feb 2, 2016

You are trying to save the data into localStorage, but you are not reading it. The currentUser variable you have the user data in is a regular javascript variable which gets reset when you reload the page.

You need to do something like this:

// ...
// user logs in, remember it into the local storage
// Note: is is better to use it via $window.localStorage
$window.localStorage.setItem('user', JSON.stringify(user));
this.currentUser = user;

//...
// function to get the user, if this.currentUser is not set,
// try to load from the local storage
getUser: function() {
  if (this.currentUser) {
      return this.currentUser;
  }
  var storageUser = $window.localStorage.getItem('user');
  if (storageUser) {
    try {
      this.user = JSON.parse(storageUser);
    } catch (e) {
      $window.localStorage.removeItem('user');
    }
  }
  return this.currentUser;
}

// you may also want to remove the user data from storage when he logs out
logout: function() {
    $window.localStorage.removeItem('user');
    this.currentUser = null;
},