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'
Related
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
})
In my app I want to save the user session_id in local storage. My app is written with React and Redux ( With server side rendering ). I fetch user session_id from Api. I want to save session_id while user is logged in to my app ?
How is the best solution for this ?
Can you share the code you currently have to understand your question a little better. From what I understood you want to maybe try the code below. In the else statement make the api request for the session id and then setItem with the session id that came from the api request. You will then have access to it with a variable called currentSessionId.
var currentSessionId;
if(localStorage.getItem('session_id')){
currentSessionId = localStorage.getItem('session_id');
} else {
localStorage.setItem('session_id','<session id>');
currentSessionId = localStorage.getItem('session_id');
}
Hope this helps!
Just save the session_id to local storage when you receive it from the server. Then in your application initialization file check if the local storage contains any session_id. If so, use that id to fetch user data.
As local storage is client side (browser) feature, you can't use it in backend.
Another option could be to save your session_id into cookie and read that cookie in server side. That way you could authenticate the user already in server side.
Using sails.js, is there a way to run a function when a user session expires or is finished? Some configuration to do in config/session.js?
I know exists session.destroy, which you can set a function to execute when the session is destroyed, but I need it to be a global unique function for the application.
The idea would be writing in db table the state of a user as offline, when it's session ends.
Thanks.
If you're asking if there is a way to see if a user's session has expired -
Yes! It depends on how you're storing the server-side component of the session. Remember, traditional sessions require 2 pieces to work correctly - something on the client side (a cookie for example) and something on the server side to remember the user. In Sails the server-side piece is stored in the data store specified in the adapter portion of the Session Config File. You can query this data-store (even if it's the default Memory Store) and look for all users that have expired sessions.
Going deeper...
If you're asking if there is a specific method that gets called when a user session expires, then no, that's not the way sessions work. Sessions are a "hack" to make HTTP stateful. They aren't an active/live thing in the way that if they die we are notified. A session is just a record (likely a database) with a long code and a date. When the user visits your site, they give you a code from their cookie and you verify against the record in your session database. If the record matches and hasn't expired, HURRAY! you know who they are and they continue with their request. If the record doesn't match or has expired, BOO!, prompt them to log in again.
Really jumping to conclusions now...
I presume from the last sentence that you're looking to try to monitor whether someone is logged in to track "active" users. I would suggest that sessions are a poor metric of that. With sessions I can log in to your site and then leave. Depending on the length of your session expiration (24 hours or 30 days are typical values) I would be shown as logged in for that entire time. Is that a really helpful metric? I'm not using using your site but you're showing me as "logged in". Furthermore I could come back on another device (phone or another browser) and I would be forced to log back in. Now I have 2 or more sessions. Which one is correct?
If you're trying to gauge active usage I would either use Websockets (they would tell you exactly when someone is connected/disconnected to one of your pages - read more here) or just have a "heartbeat" - Each time a user visits one of your pages that visit is recorded as last seen at. This gives you a rough gauge as to who is actively on the site and who hasn't done anything in, say, over an hour.
You can do this by adding policy to all route
for example 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();
}
//make your logic if session ends here
//** do some thing /
};
add this lines to config/policies.js :
module.exports.policies = {
'*': 'sessionAuth'
}
Here is my problem :
I'm creating a web app with loopback (great framework :) ) with an AngularJS client, everything works well but impossible to reload the page without being disconnected. This behaviour is normal, however I would like to persist the session with a "Remember me" checkbox and just avoid to be disconnect on page reload. The access token is stored in localStorage, I think I have to create a cookie on myself but the main point, how do I avoid disconnection ? And redirection to forbidden page. Then should I do this on server-side or client-side both ? I'm lost actually...
I did start from this application on github if you wish to have a better idea of the project:
https://github.com/strongloop/loopback-getting-started-intermediate
You shouldn't need to create a separate cookie to store the authToken if it's already in localStorage. The part you will need to modify is inside app.js, the .run() block, which checks for the existence of $rootScope.currentUser to determine if you're logged in, which will not be persisted across browser reloads.
The code creates $rootScope.currentUser in Auth.js. The .run() block of app.js simply checks for the existence of $rootScope.currentUser to determine if you are logged in.
So you'll need to change how you detect logged out state from simply checking for $rootScope.currentUser to attempting an actual call to User.getCurrent() or something. If you are logged in, the call will include the auth token in the headers, if not, you'll get a 401 status code response and you can redirect to the login page in that case.
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