Reputation: 739
Have been working through the sails cast tutorials and am confused about the way that sessions work.
In the tutorial, the user is marked as authenticated in the session controller by:
req.session.authenticated = true;
req.session.User = user;
res.redirect('/');
Why is the session being saved in the request?! My understanding is that the 'req' object in express.js is the information the browser sends to the server.
Shouldn't the server save this information elsewhere (won't the request object be deleted when theres another request?)
Furthermore, somehow the application retrieves the authentication status from another object session when templating a page with ejs:
<% if (session.authenticated) { %>
why isn't this variable set directly?
Probably a silly question but I am confused at how the logic works and online articles/tutorials aren't helping me understand...
Upvotes: 1
Views: 1271
Reputation: 2096
It is common practice for express middleware (remember, Sails is built on express) to attach properties to the req
object so it may be accessed in later middleware, and eventually your controllers. What happens behind the scenes is your req
object comes in with a cookie containing the session ID, and then the session middleware uses that to retrieve the actual session data from some datastore (by default, and in-memory store is used. Super fast and easy for development, but not recommended for deployment), and then attaches that to the req
object.
Regarding the value of session.authenticated
in your EJS, by default Sails includes req.session
in res.locals
(accessible in views), so that value will be whatever is stored in the session via your controller.
Upvotes: 2
Reputation: 2706
The browser sends over the session id which is stored on a cookie. The session object is referenced by that session id which is stored server side. The session is attached to the request (for convenience I suppose). You can read more here https://github.com/expressjs/session#compatible-session-stores
I wouldn't know what is setting session.authenticated
without seeing more code.
Upvotes: 2