4

I upgraded from angular 1.2 (original code) more recently to 1.3 (which broke the cookies) to 1.4 as of today ($cookieStore is now deprecated infavor of $cookies)

I added a line $cookies.putObject('user', user); but it isn't saved to cookies (i verified in chrome resources tab)

        /**
         * Authenticate user
         *
         * @param  {Object}   user     - login info
         * @param  {Function} callback - optional
         * @return {Promise}
         */
        login: function (user, callback) {
            var cb = callback || angular.noop;

            return Session.save({
                email: user.email,
                password: user.password
            }, function (user) {
                $rootScope.currentUser = user;
                $cookies.putObject('user', user); //does not save

                return cb();
            }, function (err) {
                return cb(err);
            }).$promise;
        },

I put a breakpoint right after the $cookies.putObject and I get undefined when I try $cookies.getObject('user') in chrome console.

This is an issue because now whenever I refresh the page, I lose the logged in user. The Auth.js service has this line up front:

    // Get currentUser from cookie
    $rootScope.currentUser = $cookies.getObject('user') || null;
chovy
  • 72,281
  • 52
  • 227
  • 295
  • 1
    Maybe a silly question, but you've verified that Session.save is passing back the user properly and not passing back undefined? function (user) { $rootScope.currentUser = user; $cookies.putObject('user', user); //does not save return cb(); } – mofojed Jul 26 '15 at 06:09
  • yup. i definitely have a user object. But I think I figured out my problem...I see that my object is too big to fit in a cookie. – chovy Jul 26 '15 at 06:46

1 Answers1

2

I noticed angular puts a warning in console...which I missed. My object is over the cookie size limit of 4093. Mine was 4207.

So what I did was instead save the userId to the cookie...which allows all my checks for a logged in user to work, and update the code to fetch the logged in user object from the server.

I was originally putting the user object in localStorage but that became a management nightmare -- whenever a user is updated (which can happen in multiple places across the app)... I would have to refresh the localStorage.

Instead I do this on every page refresh:

    // Get currentUser from cookie
    $rootScope.currentUser = $cookies.get('userId');

    User.get().$promise
        .then(function(user){
            $rootScope.currentUser = user._id && user || null;
        });
chovy
  • 72,281
  • 52
  • 227
  • 295