0

I have a single page angularjs app in which whenever there is a change in route I check the login status of the user by a variable stored in a service(after submitting the login form to server) as per this solution AngularJS- Login and Authentication in each route and controller:

app.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
    $rootScope.$on('$routeChangeStart', function (event) {
    if (!Auth.isLoggedIn()) {
        console.log('DENY');
        event.preventDefault();
        $location.path('/login');
    }
    else {
        console.log('ALLOW');
        $location.path('/home');
    }
});}]);

//service

 .factory('Auth', function(){
var user;

return{
    setUser : function(aUser){
        user = aUser;
    },
    isLoggedIn : function(){
        return(user)? user : false;
    }
  }
})

The problem is when I reload the whole page(by the refresh button) the variable in the service is lost and user gets redirected to login page even when the user session is still on at the backend.

How can I still manage the variable in the service? I thought of using sessionStorage but does not sound secure enough.

Community
  • 1
  • 1
me_digvijay
  • 5,174
  • 7
  • 43
  • 81
  • You can check the login status of the user on initialization of your angular App and can set that in Root Scope of your app. So, it can be accessed anywhere in the App. – WpTricks24 Apr 28 '15 at 06:25
  • You can bootstrap your user session(not really the session, but user details if is authenticated or undefined else) and inject it in the main view as `javascript`, from your backend server. On front end read that variable from `javascript` and you have a persistent session even after refresh. – AndreiC Apr 28 '15 at 06:26

3 Answers3

0

Im my opinion you can choose from 2 ways:

  • Persist the Data on the server-side via session
  • Store your data in the localStorage or even better in the window.sessionStorage so a page reload doesn't affect your applicant
0

Maybe angular-cookies can solve your problem

王如锵
  • 861
  • 7
  • 16
0

Try to store your data in $window.localStorage ( angular abstraction over javascript window.localStorage)

for example :

(function () {
angular.module('app').factory('UserIdentity', ['$window', function ($window) {

    this.UserName = function () {
        return $window.localStorage.getItem("username");
    };

    this.Token = function () {
        return $window.localStorage.getItem("token");
    };

    this.create = function (token, userName) {
        $window.localStorage.setItem("token", token);
        $window.localStorage.setItem("username", userName);
    };
    this.destroy = function () {
        $window.localStorage.removeItem("token");
        $window.localStorage.removeItem("username");
    };
    this.isAuthenticated = function () {
        var token = $window.localStorage.getItem("token");
        return !!token;
    }
    return this;
}]);

})();

Maciej Wojsław
  • 403
  • 2
  • 10