2

I've been working on a small project and I've started wondering how to keep some data after the user logs in or logs out.

For example let's say that the user is adding items to his shopping cart and he is not logged in. Django sessions by default generate new session_id after the user logs in or logs out. When the user adds 5 products to his cart when and he logs in afterwards then his cart will be cleared.

How to implement an element of persistence in user data? For example should I use some signals or some sort of middleware to bind the cart from old to new session?

My main goal is to keep it safe so I don't want to disable some security mechanisms.

Efrin
  • 2,153
  • 2
  • 20
  • 43
  • 1
    You can keep data using cookies or local storage http://stackoverflow.com/questions/3220660/local-storage-vs-cookies and send it via AJAX after user login – madzohan Oct 22 '14 at 11:13
  • That seems to be fine solution. Cookies are easy to modify, so for cookie value I should set generate for example UUID? So it will be harder to steal the basket :) – Efrin Oct 22 '14 at 11:18
  • Use can use ‘secure’ cookies. https://docs.djangoproject.com/en/dev/topics/security/ If a browser connects initially via HTTP, which is the default for most browsers, it is possible for existing cookies to be leaked. For this reason, you should set your SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE settings to True. This instructs the browser to only send these cookies over HTTPS connections. Note that this will mean that sessions will not work over HTTP, and the CSRF protection will prevent any POST data being accepted over HTTP. – madzohan Oct 22 '14 at 11:33

2 Answers2

1

You have to use the database-backed session. From the doc:

you need to add 'django.contrib.sessions' to your INSTALLED_APPS setting.

Once you have configured your installation, run manage.py migrate to install the single database table that stores session data.

Then you have to ensure that the session.flush() is not called in the logout/login process, witch implies avoid using the django.contrib.auth.logout() witch will call session.flush(), it is also called in django.contrib.login(). login and logout the user yourself to avoid losing the session data. source for login/logout.

e-nouri
  • 2,338
  • 1
  • 16
  • 30
1

The session is flushed at login/logout, as a security measure. If you want to retain some variables, you can use the solution at:

https://stackoverflow.com/a/41849076/146289

It basically involves backing up old values, and then restoring them in the new session.

Community
  • 1
  • 1
vdboor
  • 19,540
  • 11
  • 74
  • 91