Cheese Puffs
Cheese Puffs

Reputation: 985

Handling session/cookie with Sails.JS and AngularJS

I'm doing a simple SPA where I am using Sails.JS for a REST API and AngularJS for my frontend. I'm currently having some struggles with figuring out how I should handle the sessions when combining these two.

Feel free to give me some pointers if I'm going about this the wrong way.

--

Here is part of my login function. When a successfull login happens I return the user object along with a session to my client.

User.js

 if(user) {
            bcrypt.compare(userObj.password, user.encryptedPassword, function(err, match) {
                if(err) {
                    res.json({rspMessage: 'Server error'}, 500);
                }

                if(match) {
                    req.session.user = user;
                    res.json(req.session.user); // return user data and session.
                    /* This returns something like this 
                     { cookie: 
                        { path: '/',
                          _expires: null,
                          originalMaxAge: null,
                          httpOnly: true },
                       user: { 
                         username: 'admin',
                         id: '549f2ad213c64d3b2f3b9777'} 
                    }
                    */
                }
            });
        }

loginService

Here is my loginService which doesn't really do much right now. I figured this is the place to keep track of the session. I'm just not sure how to go about this... There aren't many tutorials about combining Sails + AngularJS.

MyApp.factory('loginService', ['$cookieStore', '$http', '$rootScope', function($cookieStore, $http, $rootScope){

var _user = {};

return {
    login: function(credentials) {
        return $http.post('/user/login', credentials)
        .then(function(result) {
            return result.data;
        });
    }
}
}])

I want to check the session against my backend somehow and see if its valid or if it has expired. If the session is still valid, the user will be kept logged in even if the user closes his browser/refresh.

Suggestions, links.. anything helpful is appreciated.

Upvotes: 1

Views: 1673

Answers (1)

Yann Bertrand
Yann Bertrand

Reputation: 3114

Here's some tips I can give you :

  1. Since Sails v0.10, you can use custom responses (doc page) which is a better practice than using

    res.status(...);
    res.json(...);
    
  2. The session cookie you are creating with Sails is saved server-side. Maybe you can create a url (e.g. GET /me) to know if this session is still valid. Your Angular app would make a request to this url each time the page is loaded (in a run block I would suggest) to know if the user is still logged in server-side.

Do not hesitate if you need more precision.

Upvotes: 1

Related Questions