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.
Related
I'm building an application whereby if a user wishes to add an item to a personal watchlist, they must be logged in. I use localStorage to store this personal watchlist data and to retrieve it. The problem I am having is that if account 'A' adds an item to their watchlist and then logs out and account 'B' then logs in, the previous stored data is returned from account 'A'.
How can I prevent this from happening so that the data is only saved/returned for each particular user account? Should I be using something instead of localStorage like sessionStorage? Any help is appreciated.
I've solved this personally by including an identifier for the user in the local storage key. You'll have an entry per user and do the lookup based on the identifier. Something like:
localStorage.setItem(`watchlist:${user.id}`, data) // set
const watchlist = localStorage.getItem(`watchlist:${user.id}`) // get
As noted by #AlexB in the comments, be aware that multiple users on the same device will have the local data of any other users in their localStorage, so be sure to consider privacy.
Save your data with userId as key(unique for all user) and corresponding watchlist as data
localStorage.setItem('userId', data);
and then fetch it with the login user Id
localStorage.getItem('loginUserId');
After a user enters credentials on the login page, a post request is sent to the web server, which sends a cookie (if successful). On the client side, simultaneously, write the user details to my global redux store. On successful authentication from the server, I call window.location.href = 'newURL'. This call reloads my app. Now the user info I stored to the global store is lost, and I am not able to display username which was enetred by the user. How can I access the user credentials?
Thanks in advance :)
As mentioned in comments.
You need to use either localStorage or sessionStorage to keep the data alive.
For eg
localStorage.setItem("user", {"name": "abc"});
Now, though you logged out your data will be there in localStorage and you get the data using
localStorage.getItem("user");
If you want to remove then
localStorage.removeItem("user") or window.localStorage.removeItem('user');
Same applies to sessionStorage as well
I need save data of user when user login with token.
How i can save data of user for example her user id , her name , her x data , i think save data in local storage but is it insecure because this data any person can change on the console
Use cookies to store user information but it's storage size is less compared to local storage
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'
}
I'm developing nodejs application with users registration using sails.
I have an /signup method, which is looking for existing user, if user not found, it will create new user in db.
As you know in sails model (waterline) available few methods : beforeCreate, afterCreate. In beforeCreate I need also register user in a few other services(it takes +-2 seconds), after that I can set received data to user object.
The problem is if user clicks few times on "register" button (or just send the same request 2+ times in a row), it will create 2 objects in db ( or another services ). I have a similar with some other methods like this.
I was trying to set unique field in user model. Also maybe is good idea to implement police, witch can check user + reqest url and put this data into redis. If the second request arrives , check if it exists in Redis. Any other ideas?