Find the Current Session Id in Meteor.js - javascript

How do you find the current Session Id on the client?
I am able to get what seems like the last session id, not the current session id.
console.log(Meteor.default_connection._lastSessionId)

The wording for this is a bit confusing, but _lastSessionId is the current session id.
It is only called this because if the client is disconnected and seeks to reconnect it wants to re-establish the session with the last session id.
The client would reconnect with a message like this :
{"msg": "connect ", "session": "ERoZSR3R3f8zBQ6Ry", "version": "pre1","support":["pre1"]}
The session uses the lastSessionId value. This is then used to re-establish the previous connection.
This is the only case where a new session id would be assigned on a reconnection. That or the session is expired off the server.
If the server restarts it's cache is refreshed and it wouldn't recognize the session anymore, and a new session id would be assigned.

The Meteor login token by default is stored in local storage (not in cookie).
On the client you could access
token = Meteor._localStorage.getItem('Meteor.loginToken')
On the server, once token is received, use the Accounts api to hash using
Accounts._hashLoginToken(res.req.body.token)
Then, you could validate hashed value against users collection for services.resume.loginTokens.hashedToken field
This hack can be used to build meteor - express integration

Related

How to find and delete a session by id in MemoryStore in express-session in node js

I am using Node.js express and express-session.
I have saved sessions in default MemoryStore.
I want to find a session by sessionID in express-session.
I need to delete that session from the memory.
Its basically login out a user form existing device.
Please help
From official documentation:
Session.destroy(callback)
Destroys the session and will unset the req.session property. Once complete, the callback will be invoked.
req.session.destroy(function(err) {
// cannot access session here
})

How to send data to a users socket id after they have refreshed - socket.io

To give an example, let's say a user sends some json to a server containing his socket id, and the server takes 5 seconds to respond. When it's ready to respond, it extracts the socket.id from the json object, and emits some data only to that socket.
If the user where to refresh (therefore changing the socket he is connecting via ) between sending the message and the server responding, how would I go about ensuring they still receives the data?
Server:
io.on("connection", function(socket) {
socket.on("data", function(data) {
var id = data.socket_id;
io.sockets.connected[id].emit("response", "sup");
// I know I could just do -> socket.emit("response", "sup") <- but im simply trying it out for learning purposes
})
})
Client:
socket.emit("data", {
username: "chris",
socket_id: socket.id,
});
socket.on("response", function(res) {
console.log(res);
})
If the user refreshes their page, that will make a new socket.io connection that will have a new and different socket.id. So, if you want to be able to identify a particular browser session across refreshes, then you need an identifier that survives a page refresh. That is not the socket.id.
Most likely, you would use some sort of long lasting userID in a cookie. If you don't already have any sort of authentication happening that gives you a userID in a cookie, then you can simply coin a unique ID in a cookie if there isn't already one anytime a user makes a request to your server. That will give you a unique userID in a cookie for every incoming socket.io connection (as long as cookies aren't disabled). When your socket.io connection connects, you can add it to a Map object you keep where the userID is the key and the current socket.id is the data and you can add the userID as a property on the socket. When the socket disconnects, you would then remove it from the Map object.
Then, when you want to save a reference to the user, you save the userID, not the socket.id and that reference stays the same across a page refresh. When you want to send to the userID, you can look it up in the Map object to get the current socket.id (which will be automatically kept current by your connect and disconnect event handlers as described above) and then use that to send to it.

Saving OAuth2 access tokens for sessionless authentication

I set up a sessionless app that uses OAuth2 password grant authentication. When a user logs into my app with a username and password I save the access token in sessionStorage which is valid for 30 minutes. I also save a refresh token in sessionStorage in case I need to extend the session longer than 30 minutes. The refresh token is valid for 30 days.
If the 'remember me' checkbox is selected on login I save the access and refresh tokens in localStorage so they will persist as long as the refresh token is valid.
Both of these seem to work fine except for a couple of issues:
If the browser is left open and the user doesn't log out the session could potentially last for 30 days.
sessionsStorage doesn't persist between windows/tabs so if the user opens a new window they need to log in again. This is not an issue when the 'remember me' checkbox is selected since localStorage does persist between windows.
I think using refresh tokens is not safe for JavaScript applications - you need to access the /token endpoint and authenticate using the application's secret. But the secret gets public in such applications.
I would prefer the OAuth2 implicit flow and getting new token from the /auth endpoint with prompt=none parameter (from OpenID Connect). But with the implicit flow, you would either need to get a longer living ID token (and ask for an access token with the ID token later) or to implement the "remember me" at the OAuth2 (better option - can be used by any application). That would also solve the problem #2 with passing tokens between tabs.
By the "session" you mean using the refresh token to generate access tokens for 30 days? If that's a problem, you can implement some activity detector which would log the user out if there is no activity for e.g. 30 minutes.
It's possible to use the localStorage as a kind of message passing service, so you can keep the tokens in the sessionStorage, but a new tab can use the localStorage to request the token from existing tabs. For more info see http://www.codediesel.com/javascript/sharing-messages-and-data-across-windows-using-localstorage/
Code example from the linked article:
function eventListener(e) {
if (e.key == 'storage-event') {
output.innerHTML = e.newValue;
}
}
function triggerEvent() {
localStorage.setItem('storage-event', this.value);
}
window.addEventListener("storage", eventListener, true);
data.addEventListener("keyup", triggerEvent, true);
The workflow would be like this:
New tab is opened and writes an arbitrary value to the localStorage with a key indicating that it needs a token. The key can be "newTabOpened". The new tab starts listening to changes of another key "oauth2token".
The existing tab listens to the changes of the "newTabOpened" key and as a reaction, it writes its token value under the "oauth2token" key.
The new tab reads the token and removes it from the localStorage.

Update Express session for multiple users, not in the request context

I save some data belonging to the authenticated user in the session and I want that when the user object is updated in the database users collection, to set somehow the updated data in the session of the user. This may not happen in the request - response workflow. Maybe it's a random script updating user data in the database.
How to update a specific session data with the new data that is set in the database?
Currently to set the data I do:
req.session.userId = 7;
req.session.foo = 42;
Let's assume that I want to turn 42 into 43 for the session data which has userId === 7. How to do that?
I'm using the express-session module.
I know that one solution is to reload from the database the user on each request, but that would not be performant, since it would create queries that can be avoided.
What's the best way to update the session data of the user, knowing a field that was set in the session (such as the userId)?
I use the connect-mongo store.

Checking whether Express Session is expired

Say node express sessions are saved in an application (meaning they are not necessarily accessed from incoming req), how to check whether any of these sessions is expired? What is the proper test?
let's say you have saved User name in session. req.session.name='pankti' when you try to get it and if it is undefined then it is expired.req.session.name == 'undefined'

Categories