Mhd Wael Jazmati
Mhd Wael Jazmati

Reputation: 667

cookie removed when refresh page

i'm developing a website using angularjs and nodeJS, my issue is that when is store an object in cookie, this object will still in cookie until i reload page and this is my code

.service("Auth", function ($cookies, $rootScope) {
        var currentUser = null;
        return {
            set: function (data) {
                currentUser = data;
                $cookies.putObject("user", data, {
                    secure: true,
                    expires: (new Date(new Date().setMinutes(new Date().getMinutes() + 30))).toString()
                });
                $rootScope.currentUser = currentUser;

            }
            ,
            get: function () {
                return currentUser;
            }
            ,
            isLoggedIn: function () {
                if (currentUser) {
                    return true;
                } else {
                    return false;
                }
            }
            ,
            logOut: function () {
                $cookies.remove('user');
                // currentUser = null;
                $rootScope.currentUser = null;
            }
        }
    }
)

Upvotes: 1

Views: 4934

Answers (1)

chubbsondubs
chubbsondubs

Reputation: 38749

The cookies aren't getting erased it's your currentUser local variable that is disappearing. When you refresh the page all of the objects you have stored in memory are going to go away, and the Auth service will be rebuilt. You need to properly re-initialize yourself from the cookies and set the currentUser again. Something like this:

.service("Auth", function ($cookies) {
    // re-read the user from the $cookies
    var currentUser = $cookies.getObject("user") || null;
    return {
        set: function (data) {
            currentUser = data;
            $cookies.putObject("user", data, {
                secure: true,
                expires: (new Date(new Date().getTime() + 30 * 60 * 1000).toString()
            });
        }
        ,
        get: function () {
            return currentUser;
        }
        ,
        isLoggedIn: function () {
            if (currentUser) {
                return true;
            } else {
                return false;
            }
        }
        ,
        logOut: function () {
            $cookies.remove('user');
            currentUser = null;
        }
    }
})

Personally I think it would be better to talk to your server and have it return the user object. The cookies will be sent to the server, but it gives your server a chance to validate the authenticated user. It provides much better security against someone stealing cookies, having them expire, etc.

And stop storing the currentUser on the $rootScope. Just keep it in your local variable, and if someone wants the currentUser they can inject the Auth service.

Upvotes: 1

Related Questions