0

When logged in with specific user (i.e. user 1), I can save my data in form of cookie with following code snippet :

import Cookies from 'universal-cookie';

const cookie = new Cookies()
cookie.set('cookie','user1value', { path:'/'})

But when I login with user 2, I don't want my user 2 to be able to access the cookie that was saved while I was logged in from user 1 i.e. I don't want my user 2 be able to see user1value cookie given in the code above. The given code allows all the user to access the cookie while being on the same site. Is there a way to map a certain user to specific cookie value? If so, can someone give me a general idea how I can achieve that?

fmatt
  • 464
  • 1
  • 5
  • 15
infoo
  • 1
  • 1
  • Why don't you destroy the previous cookie once another user log in ? Or once user 1 log out ? – jossefaz Apr 11 '21 at 06:40
  • If two users use the same computer and browser to log in to your page, and you store user-specific data in cookies (that are distinguished by cookie name since otherwise the cookies would overwrite each other), then they will both be able to see these cookies. One way to solve it could be to store the data encrypted in the cookie and decrypt the cookie serverside (with every user mapped to a key) upon successful login. – fast-reflexes Apr 11 '21 at 06:42
  • i want the data to be saved for the user1 if they want to log back in. – infoo Apr 11 '21 at 06:42
  • @fast-reflexes Yes i was encountering issue of cookie being overwritten. Will look into your suggestion . thank you! – infoo Apr 11 '21 at 06:52
  • if you running that kind of sensitive data... I would make the cookies expire on logout (or even on session). if you, somehow, need to... one idea you could explore is to generate some kind of variable to distinguish user cookies and then encrypt them (it would difficult access to data, but wouldnt be 100% safe proof) – Noriller Jun 18 '21 at 19:10

1 Answers1

1

Typically you don't want to store user related info in the cookies after user logs out. You can get user related info after user logges in again, and set it as cookie. Some options that I can think of:

  1. As said in the comments, by using same cookie name, you can overwrite the previous cookie in user's browser. That way, old cookie value will be lost.

  2. On logout, you can set cookie value to empty string(or any other unused value) and set "expires" value as described in this post.

  3. If you don't want your user info to be readable in cookie value, you can use a session id as cookie value. Then, in a data storage in server side, you can relate this session id with the logged in user info. Once user logs out, you can delete the session in database as well as the cookie.

srknzl
  • 776
  • 5
  • 13