I am building an integration with Express Session and I am trying to authenticate the user in a separate webhook. So I need a way to update the user session outside of the request since it would be a different request.
What I did is I passed the session ID to the new request, and use MongoClient to update the session in the database. I remember Express Session only stores the ID on the client-side and the data is store on the database, so I assume updating the database would do it. But that doesn't seem to be the case. I can clearly see that the session on MongoDB is all updated but I kept getting the outdated data in req.session.data.
Here's what I've done
So the first thing I tried is to use the req.session.reload() method like these:
Updating express-session sessions
change and refresh session data in Node.js and express-session
But it is still giving me outdated data as if the function did nothing (it did print out logs so I assume it did run).
I tried using this that uses store.get() method from Express Session but it is giving me undefined session.
Express load Session from Mongo with session_id
So as a last resort I use MongoClient to get the session data directly and update the session with the data obtained. I use async for the route handler and await the MongoClient to get the data. It doesn't wait for the await and just kept throwing undefined. I thought it's my code that's wrong but I am able to get user data with the code and it did wait for the MongoClient to get the data, but somehow it is not working for session data.
Here's part of my code:
app.router.get('/login', async function (req, res, next) {
req.session.auth = await mongo.getCookie(req.session.id).auth;
req.session.user = await mongo.getCookie(req.session.id).user;
console.log('Login Action', req.session.id, req.session.auth, req.session.user);
}
module.exports.getCookie = async function getCookie(identifier) {
try {
let database = client.db('database');
let collection = await database.collection('sessions');
let result = await collection.findOne({ _id: identifier }, function(err, res) {
if (err) throw err;
return res;
});
return result;
}
catch (err) {
console.error(err);
return null;
}
}
Here's other answers that I've check
This one only update the expiration so I assume its not going to work for me, I did set the resave to false so that it doesn't try to save every single request, since its saving to the database I assume it has nothing to do with updating and I have tried setting it to true and nothing happened.
Renewing/Refreshing Express Session
And in this it uses socket.io and store.get() so it's not going to work as well.
How to access session in express, outside of the req?
Can someone guide me on how do I get Express Session to update from the database or is there a way to get the data from the database and update the session that way?
So I did eventually figured it out, turns out the session was not updated from the database. Looks like it has a local copy in the cache, but I was under the impression that the express session only uses the database.
I know for a fact that my data is indeed in the database but not in the cache or wherever the local copy of the express session is stored. So the easiest way to get pass this problem is to update the local copy with the data on the database.
And I created this function to update the session data
async function sessionUpdate(req) {
try {
// get the data on the database
let tempSession = await mongo.getCookie(req.session.id);
// if the data exist, we can copy that to our current session
if (tempSession) {
req.session.auth = tempSession.auth;
req.session.user = tempSession.user;
// you can do other stuff that you need to do with the data too
if (req.session.health == null || req.session.health == undefined || typeof req.session.health === 'undefined') {
req.session.health = 0;
}
// This update and save the data to the session
req.session.save( function(err) {
req.session.reload( function (err) {
//console.log('Session Updated');
});
});
}
else if (!tempSession) {
req.session.auth = false;
req.session.user = null;
req.session.ip = request.connection.remoteAddress;
}
}
catch (err) {
console.error(err);
}
}
Now that we have a function that can update the session data, we need to implement it everywhere. I use middleware to do that, you can use other methods too but this must be called before the route or the session logic.
// middleware with no mounted path so it is used for all requests
receiver.router.use(async function (req, res, next) {
try {
await sessionUpdate(req);
}
catch (err) {
console.error(err);
}
next();
});
It's not exactly a good/efficient way of doing it... that's a lot of things to run before even getting to the route so I would assume it would bring the performance down a bit... But this is how I get it to work and if anyone can come up with some better idea I would very much appreciate it š
Related
I am looking to use supertest to test API requests and responses. Following is what I have tried so far.
route.test.js
const testUtils = require('./setupTestUtils');
let authenticateUser = request.agent(app);
before(function(done){
testUtils.login(authenticateUser, userCredentials).then((res) => {
expect(res.statusCode).to.equal(200);
done();
}, (err) => {
console.log(err);
done(err);
});
});
setupTestUtils.js
function login (rest, testUserLogin) {
let defer = Q.defer();
rest.post('/login')
.send(testUserLogin)
.expect(200)
.end(function () {
rest.get('/loggedin')
.expect((res) => {
if (err) {
console.log('ERROR: ' + JSON.stringify(err));
defer.reject(err);
} else {
defer.resolve(res);
}
})
.end();
});
return defer.promise;
}
In my app.js, I use passport to authenticate. After authentication, I use the session.regenerate function to regenerate the session ID to avoid session fixation.
The initial post request to login passes without any failure. However, the subsequent GET request 'loggedIn' fails. This function internally uses the req.isAuthenticated() function from passport. This always returns false.
On investigation, I found that the session ID between the regenerated session and the request object (for req.isAuthenticated()) is different.
From my search, I understand that the cookies should be maintained automatically by the use of 'agent' from supertest. However that doesnt seem to be the case for me. I have also tried maintaining the cookies from the initial response. That doesnt seem to work for me either. " res.headers['set-cookie'] " comes in as undefined (not sure why that is happening either).
Can someone please help me understand what I am missing here.?
Am using versions - Supertest #v6.0.1 and passport #v0.4.1
I found the solution to my issue in an old github issue raised on supertest's page. Linking it here for reference.
Essentially, the supertest runs express in insecure port and I had configured my session otherwise. Ideally, we would have to check the environment before setting this variable to false - as represented here.
Hope this saves someone the time I spent!
Iām trying to pass data from my server app.js to my database file so that I can store it into MongoDB atlas.
I can see where the problem is I'm honestly just not sure how to go about fixing it. The problem seems to be two parts.
1.) I'm passing a function into .insertOne and not an object, this is resulting in a promise error. When I try to change things in the userDataFinal function I start running into scope errors and things not being defined. I'm not really sure how to fix this.
2.) my code is trying to create a new document as soon as it starts up because
db.collection('User').insertOne(userDataFinal);
is located in the .connect callback function.
I need this code to run only when a put request has been made on the client side.
relevant server code app.js
const base = require('./base.js');
app.post('/',(req, res)=>{
var userName = req.body;
base.userDataFinal(userName);
res.render('index');
});
Relevant database code base.js
var userDataFinal = function getUserName(user){
console.log(user);
}
module.exports = {userDataFinal};
////////////////////////////////////////////////////////////////////////
// connects to the database
MongoClient.connect(URL, {useNewUrlParser: true}, (error, client)=>{
if(error){
return console.log('Could not connect to the database');
}
// creates a new collection
const db = client.db(database);
// adds a document to the designated collection
db.collection('User').insertOne(userDataFinal);
console.log('Database is connected...')
});
First, you are passing a callback into your MongoClient.connect() function.
This callback is useful when you want to make sure that you are connected.
As you said it, you want your code to run only when the request has been made. You can remove your insertion from the connect, but you can still keep the error handling part as it is always useful to know why there was a db connection error.
Also, you are calling the mongo insertOne method, that expects an object. You are passing it a function.
EDIT: Create a db variable outside all your functions, then assign it from the Mongo connect callback once you have access to the client.
You will be able to use this db later in the routes.
var MongoClient = require('mongodb').MongoClient;
var db; // Will be set once connected
MongoClient.connect(URL, {useNewUrlParser: true}, (error, client)=>{
if(error){
return console.log('Could not connect to the database');
}
db = client.db(database);
console.log('Database is connected...')
});
app.post('/',(req, res)=>{
var userName = req.body.username;
db.collection('User').insertOne({ username: userName });
res.render('index');
});
Please note that you are probably passing the userName through the body, in this case you need to retrieve it that way: req.body.username (if you named the related body parameter username).
In my website, everything server-side is stored in sessions of express-session.
But I can't understand why, when I make an HTTP request with request module, the req.session parameter isn't within the request.
I mean, follow the comments :
app.get('/prefix', async function(req, res) {
console.log(req.session.login);
// There ^ the req.session.login is true, and so it works
if (req.session.login == false || req.session.login == null) return;
var options = {
url: 'https://bot-dreamsub.glitch.me/getPermission',
json: true,
jar: true,
withCredentials: true
}
request(options, async function(err, res, json) {
if (err) {
throw err;
}
console.log(json);
if (json == true) {
res.sendFile(__dirname + '/prefix/prefix.html');
} else {
return;
}
});
});
app.get('/getPermission', function(req, res) {
console.log(req.session.login);
// There ^ the req.session.login is undefined, and so it sends null to the user
try {
if (req.session.login == false || req.session.login == undefined) {
res.send(null);
} else {
// some other code
}
} catch(err) {
console.log(err);
};
});
I don't know why request doesn't send sessions within the HTTP request even with
withCredentials: true
What can I do to accomplish it?
An express-session works by setting a cookie in the client's browser that made the original request. Future requests with that same cookie will offer access to that same session. When you do request() yourself from your server, you aren't presenting the same cookie that came in with the original /prefix request so you won't have access to the same session.
Since it appears you are just trying to use request() to call your own server, I'd suggest you just use a function call and pass the original req.session to that function call so that you will have it available.
You then use normal code factoring to factor out some common code between your /getPermissions route and what you want to use in your /prefix route so that they can both use and share a common function that you pass the current req and res to. Then you don't need to solve this cookie issue because you'll already have the right req object and thus the correct req.session in this factored common function.
Alternatively, you could build the right cookie and send that with your request() so that it will appear to be coming from the original browser that has the cookie (and thus session) that you want, but that's kind of the long way to do things when you already have the req.session you want and you could just pass it in a function call rather than start all over and try to simulate a cookie that will get you to the right session.
I don't know why request doesn't send sessions within the HTTP request even with
First off, session aren't sent with a request. Cookies are. Your server then uses the cookie to find the right session object.
Your call to request() does not have the right cookie in the cookie jar you use so when that requests gets to your server, it isn't able to find the right session object. So, when the request is received by your server, it appears to be coming from a different client that does not yet have a session so a new cookie and a new session are probably created for it.
FYI, if also looks like you may be confusing two definitions of res in your request() call. There's a res defined as an argument in this app.get('/prefix', async function(req, res) { and then you have a separate res in request(options, async function(err, res, json) { that will override the previous one in that scope. It appears to me when you do res.sendFile(__dirname + '/prefix/prefix.html');, you are probably using the wrong res. Probably the best way to solve this is to not use request() at all as suggested above (using a function call to your own server). But, if you were going to still use request(), then you need to name the two res arguments differently so you can still access them both and can use the correct one for your situation.
I am using SailsJS and Socket.IO.
Currently I need to know if a user's session is expired or not.
Once user's session is expired I need to disconnect socket connection for that user.
One way to do it is using CRON for every 30 minutes and checking if user is still logged in.
Is there any way I can check if user's session still exists without using CRON.
Thanks in Advance
As luck would have it, Node is Javascript and Javascript makes this sort of thing very easy. You can just use setInterval like in a regular ol' front-end script. So, assuming you have a User model with an expiresOn field you can check do something like the following in your config/bootstrap.js:
module.exports = function(cb) {
// Schedule disconnectExpiredUsers to run once a minute
setInterval(disconnectExpiredUsers, 60000);
// Function to loop through all expired users and disconnect them
function disconnectExpiredUsers() {
var now = new Date();
User.find({expiresOn: {'<': now}}).exec(function(err, expiredUsers) {
// Handle errors somehow
if (err) {
return console.log(err);
}
// Loop through expired users (lodash is globalized by Sails)
_.each(expiredUsers, function(expiredUser) {
// Since you're using resourceful pubsub (right???),
// we can get all of the instance's sockets easily
var sockets = User.subscribers(expiredUser);
// And we can send them a message
User.publishMessage(expiredUser, "Session expired, buddy!");
// And disconnect them, but use nextTick to make sure the messages
// go out first
process.nextTick(function() {
_.each(sockets, function(socket) {socket.disconnect();});
});
});
});
}
};
This also assumes you're using Sails' resourceful pubsub to subscribe sockets to your User instances; otherwise you'll have to keep track of the IDs of connected sockets yourself.
You can do this by adding policy to all route
Simply add sessionAuth.js to policy folder
module.exports = function(req, res, next) {
// If you are not using passport then set your own logic
/*if (req.session.authenticated) {
return next();
}*/
// if you are using passport then
if(req.isAuthenticated()) {
return next();
}
//else
// Write your code for socket disconnect
// or send json res like this
return res.json({msg:'You are not loggedin, Please Login !'})
};
Now go to config/policies.js
And apply this policy to all routes
module.exports.policies = {
'*': 'sessionAuth'
}
On my website users need to login with database account. My question is, how to auth socket.io only if database login pass and create my variable in cookie ?
Express with auth function from here socket.io Auth works with sessionID, maybe i can prevent to give sessionID to moment when user log in to database ?
Use the authorization function:
io.set('authorization', function (handshakeData, callback) {
// findDatabyip is an async example function
findDatabyIP(handshakeData.address.address, function (err, data) {
if (err) return callback(err);
if (data.authorized) {
handshakeData.foo = 'bar';
for(var prop in data) handshakeData[prop] = data[prop];
callback(null, true);
} else {
callback(null, false);
}
})
});
Replace findDatabyIP with your database lookup.
Any attributes you set on handshakeData should be available in your "connection" handler via socket.handshake.sessionID.
Call callback when you're done, with an error message (if applicable), and true if the connection is authorized, false if it's not.
Parsing and reading the session's cookie may be difficult. This discussion (especially jugglinmike's post) may help.