how to using session in NodeJS/ExpressJS - postgreSQL - node.js

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.

Related

Express session, how do I get the session after posting? I see the session ID in browser under cookies, but it's undefined in request object?

Sorry guys, I'm really new to sessions and cookies and I'm trying to understand the mechanism behind it. I wanted to add register/login to my simple website and in order to do I need to understand web authentication and I really think I will have tons of questions regarding this topic.
Initially, I have register page that sends info after clicking submit button to a node server using express.
I'm trying to see what happens, so I've created a session in post route, it's created in the browser (connect.sid), then I commented out the part that creates that session and just tries to redisplay the session object, but it's undefined, but I still can see the session in the browser's cookies section, so what's going on? Thanks
app.use(session({
secret:"my test secret",
cookie:{},
resave:false,
saveUninitialized:false
}))
app.post("/register", (req, res) => {
req.session.usertest = "testsession_hardcodedvaluefornow";
console.log(req.session.usertest); // -> this is okay when above line to create is uncommented
//but when I comment the session assignment, it becomes undefined?
res.send("In register...");
})
I can see the session cookie even after commenting out the create session and posting over and over.
connect.sid s%3A_TahsTv0xhY-iHIdjDRblYJ_aZZ5oiSd.do7JcOGR1FaXPcFFIQ6hg5AW%2B0XVsYwIRO8vndyjDzs
req.session.id produces a different value (not undefined) even if I delete my session in the browser, so not sure where that comes from.
There is no "usertest" key in the session object, therefore it is undefined. The reason it's not undefined when you uncomment that line is because you create that key yourself in that instant with that line.
You can get the whole session object by using req.session, the session id by using req.session.id and the session cookie by using req.session.cookie.
Edit
To further clarify: a session will be made for every connected client. That is why you can see the cookie in the browser. That has no meaning however, it's just a way to uniquely identify that client (without actually telling you who that client is). Any information about that session (whether they're logged in, user id,...) needs to be stored in a session store. Express-session will use memory store by default, if the server restarts all that information will be lost, which is why that key doesn't exist. In order to preserve that information it has to be stored in a persistent session store. More information on session store implementations for express-session and how to use them can be found here: https://www.npmjs.com/package/express-session
As for the cookie values you get, those are the default ones set by express-session since you haven't set any yourself. You can change the maxAge to let it expire (or set it so 10 years or more for a more persistent session), you can specify a domain to which that cookie belongs, you can set it to secure (to only allow it over secure connections, e.g. https) and httpOpnly is by default true. httpOnly cookies cannot be accessed/altered by the client (although you can see them in the browser), do not set this to false.

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!

share user sessions between Node.js and Clojure

I am using Clojure / Friend, and I would like to hijack a session from a neighbouring node.js server :)
What I mean is that there is a node.js + Express 3 server that stores sessions into a redis database, using connect-redis.
I have access to the node.js source code, and therefore to the secret passed to the express session used to generate the sid. I modified the connection section to look like this (the built-in in-memory store was used previously) :
var session = require('express-session')
, RedisStore = require('connect-redis')(session)
, redis = require('redis')
, client = redis.createClient();
...
app.use(session({
secret: "super-secret-key",
store: new RedisStore({client : client,
ttl : 60*60*24,
prefix : 'sess:'})
}));
I can see the sessions stored in Redis :
// using redis-cli
KEYS *
1) "sess:yNV3MQOOTZSEgzl0RH2lyWVW"
The login page is situated on the node.js side of the app. But the routes of the API are shared (via nginx) between Node.js and Clojure, so I receive the cookies in the incoming requests in my Compojure / Friend app.
I am struggling to get the Friend custom-credential function right :
(defn custom-credential [{:keys [username password] :as trial}]
(let [cookie (...)
redis-session (...)
is-signature-valid (...)]
;; I can get all the above bindings just fine
;; ie. I extract the cookie from the request
;; I read the cookie ID and fetch the cookie content from Redis
;; I extract the signature of the cookie and check it (I replicated [node-cookie-signature][8])
(when is-signature-valid
{:identity "cookie-id"})))
(defn secured-routes [unsecured-routes]
(friend/authenticate
unsecured-routes
{:allow-anon? true
:credential-fn custom-credential
:workflows [(workflows/http-basic)]}))
I have several problems :
I am redirected to the login page even when my authentication function returns an {:identity ..} map
But I cannot figure out how to plug it into Friend so that the cookies work as well. Using the default memory-store then the cookie is replaced by a default ring-cookie (obviously not what I want). I tried writing a custom cookie-store using Redis as a backend, but I need to write JSON to keep the node compatibility, and I loose the ::user information.
Note : I am quite flexible at this point so if I should use something else than Friend or Compojure I would also accept that.
Sorry for the long post, I really hope someone can help.
How do I get the cookie contents on my validating function ?
The ring request will contain any cookies that the client sent, however it may not send those cookies if your Clojure server is on a different domain.
how do I validate the user from the content of the cookie ? Ie. how can I make sure the cookie has not been altered (ie. replicate what the connect-redis is doing with the secret) ?
Best practice is for the cookie to be a random number, and to store session details in redis. If that's how your Node server works then you can just lookup the details in Redis. Alternatively if the client provided an encrypted session cookie, then you will need to decrypt it in the same manner as Node does.
Alternatively, you might want to look at JWT auth tokens, which are designed to be shared and authenticated by many different servers.

Session management in sails js framework

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.

Session resets after every app restart in Node/Express

Whenever I make changes to my app, nodemon restarts the whole app, but every time this happens, my session gets destroyed. This is getting annoying since I have to sign in every time I make changes to my app. How do I avoid this from happening?
I'm using cookie based sessions since I only store the userid. My setup looks like this (in coffeescript):
app.use express.cookieParser()
app.use express.session
secret: 'mysecretkey'
app.use express.csrf()
And I save my session by doing this:
req.session.userid = user._id.toHexString() # it's a mongoDB ObjectID
req.session.save()
By default expresssJS uses in-memory storage for sessions, so when your app is reset so are the in-memory session.
Since you are using mongoDB I would recommend using mongoDB for your session storage, or redis (which I haven't tried with node).
You can see this question on how to set up session support with express and mongo:
How to store session values with Node.js and mongodb?

Resources