Session management in sails js framework - node.js

I'm new to sail's and node, I'm trying to create/maintain a session without user login. The user sends request to server and i'm trying to store the session by req.session.uid="some uniqueid", and when again the same user tries for another request i'm unable to get the session. For every request a new session id is coming(session is not persisting).
please help by posting the code or by referring to already existing code.

You should call req.session.save(); at the end to persist the data.

Related

how to using session in NodeJS/ExpressJS - postgreSQL

I'm using express-session / connect-pg-simple modules.
Why they doesn't save session information? And they every changed sid
How can I do That. enter image description here
Anyway.
Im tried server memory store session, No save session way.
They Never saved.
I want to GET /auth/login this session userInfo -> GET / this session must has userInfo.

ExpressJS - How to force update session (eli5)?

I am kind of new to Express and Node (I come from the front-end development world), so this might be a really stupid question.
Currently, I work on an Express JS app that uses express-session, sessionstore + memcache and cookie-parser for managing sessions.
I have a particular use case wherein I have one session variable (age) that is passed on to every view through a middleware that someone in the team who created the app had written:
response.locals.age = request.session.age
The request.session.age is populated from a UserAccount model that is fetched during login.
Now, this middleware is called before the the request reaches the controller, so by the time I get this in my view, the response.locals.age has already been set, which is displayed in the template as is.
My question is this: The age variable can be reset separately through an Admin interface. But because the session is set only upon login, the change doesn't reflect until I logout and login again. I do get the new age value by fetching the UserAccount model again, but I don't know how to refresh the session with the new value without having to logout and login again. I tried doing this:
req.session.age = res.locals.age = < UserAccountResponse >.age;
But this doesn't seem to work. What is the ideal way to 'force refresh' the session in this scenario in Express along with the mentioned middlewares? Thanks in advance!

SailsJS CSRF mismatch after logout AND getting new /csrfToken

I'm creating Single Page Application. I've created login-logout actions and they work fine. But if user logs out and will not refresh page in browser, he couldn't log in again because of "CSRF mismatch" error.
Steps:
1. At first page load, csrf is view local:
<div class="app" id="app" data-csrf="<%= _csrf %>"></div>
2. User logs in with this token successfully:
420["post",{"method":"post","headers":{},"data":{"_csrf":"VHcT2F44-KhZMJmhcAVB1H69BgTMWMZji9_8","login":"alex","password":"123"},"url":"http://127.0.0.1:1337/login"}]
430[{"body":{"id":"560e5756cd01633407eea8be"},"headers":{cut headers},"statusCode":200}]
3. Then, user logs out with this token:
421["post",{"method":"post","headers":{},"data":{"_csrf":"VHcT2F44-KhZMJmhcAVB1H69BgTMWMZji9_8"},"url":"http://127.0.0.1:1337/logout"}]
431[{"body":"ok","headers":{cut headers},"statusCode":200}]
4. And if he try to log in again, he will catch "CSRF mismatch" error and I expected that:
422["post",{"method":"post","headers":{},"data":{"_csrf":"VHcT2F44-KhZMJmhcAVB1H69BgTMWMZji9_8","login":"alex","password":"123"},"url":"http://127.0.0.1:1337/login"}]
432[{"body":"CSRF mismatch","headers":{},"statusCode":403}]
5. I'm catching this error and doing /csrfToken request as said in docs
423["get",{"method":"get","headers":{},"data":{},"url":"/csrfToken"}]
433[{"body":{"_csrf":"49C5OVUZ-6SIL_zW3g1NGI87ux6Mlp-UJj_w"},"headers":{cut headers},"statusCode":200}]
6. Trying to log in again with new token:
424["post",{"method":"post","headers":{},"data":{"_csrf":"49C5OVUZ-6SIL_zW3g1NGI87ux6Mlp-UJj_w","login":"alex","password":"123"},"url":"http://127.0.0.1:1337/login"}]
434[{"body":"CSRF mismatch","headers":{},"statusCode":403}]
I could repeat steps 5 and 6 with same result.
If I refresh page, I can log in without errors.
Question is, what's going on? Why token mismatch at step 6?
Edit: logout method:
req.session.destroy();
return res.send("ok");
Edit 2: sending request:
import socketIOClient from 'socket.io-client';
import sailsIOClient from 'sails.io.js';
var io = sailsIOClient(socketIOClient);
io.socket.post(form.action, serialize(form, {hash: true}), function (data, jwres){
...
});
TL;DR: Use req.session.csrfSecret = null instead of req.session.destroy() if you're doing everything over sockets.
The issue here is with the way Express sessions work. When you call .destroy() on one, it removes the entry for the current session ID (SID) in the sessions object that Express MemoryStore maintains. Normally that's fine because it will be regenerated on the next request, but that's only the next request that runs all of the Express middleware--and Socket requests to a Sails app don't do that, as anyone trying to use Passport with Sails out-of-the-box will tell you. So the next time you make a socket request (to generate a new CSRF secret and get a new token), you're not actually connected to a session and the new info doesn't get saved.
If instead of destroying the whole session, you just destroy the csrfSecret which is used to generate CSRF tokens, then the next socket request will still be attached to a session and the new secret will be saved. You'll also want to blank out any other session variables that were keeping the user logged in.

Authentication & Sessions in express.js/sails.js

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...
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.
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.

Expressjs session only persists on localhost

I've got a simple web-page created in node/express which has a simple login system. The way i'm testing if a user has logged in, is basically a check to see if req.session.user exist, which is created at login, and the session is destroyed on logout.
This works great as long as the client connects to http://localhost:8000, however, if i connect to http://10.0.1.6:8000 a new session object is created on every request, which means i can never check if the user actually has logged in.
Why is this? I need to connect to http://10.0.1.6:8000 as I'm testing my client from android (where localhost is the android device, not my server/computer).
Silly me, gotta stop programming when tired. I was running the index.html file locally, instead of from the server (cross-domain cookies? i laugh in your face!)
You can try to set up a session with your app.
var app = express.createServer();
app.use(express.cookieParser(...));
app.use(express.session(...));
According to the docs you also have to use cookieParser() before you set up your session.
http://expressjs.com/guide.html
http://www.senchalabs.org/connect/middleware-session.html

Resources