Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep Django session data after sign-in?

I recently wrote shopping cart code that depends on the Session object. It seemed the reasonable way to store data for anonymous users.

While doing a bunch of testing, I ran into an annoying problem--when users sign in part way through the checkout process (or simply while browsing for other products), Django issues a new session_key and I lose access to my session data.

Is there a way to keep the old session data? Or is my design approach wrong?

like image 670
Aaron C. de Bruyn Avatar asked Aug 22 '12 03:08

Aaron C. de Bruyn


People also ask

How does Django keep track of a session?

Django uses a cookie containing a special session id to identify each browser and its associated session with the site. The actual session data is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users).

How long do sessions last Django?

What is the default session timeout in Django? The setting you are looking for is SESSION_COOKIE_AGE , the default value is 1209600 which is two weeks, in seconds.

What is session variable in Django?

Django allows you to easily create session variables and manipulate them accordingly. The request object in Django has a session attribute, which creates, access and edits the session variables. This attribute acts like a dictionary, i.e., you can define the session names as keys and their value as values.


2 Answers

Try writing your own SessionBackend that inherits from existing one and overrides the cycle_key method.

1 In your settings.py:

SESSION_ENGINE = 'my_app.session_backend'

2 my_app.session_backend.py:

from django.contrib.sessions.backends.db import SessionStore as DbSessionStore

class SessionStore(DbSessionStore):
    def cycle_key(self):
        pass

cycle_key is beeing called in login view after authentication.

Let me now if it works ;)

like image 68
rafek Avatar answered Nov 15 '22 09:11

rafek


Instead of disabling the cycle_key() (which is a security measure to avoid session fixation vulnerabilities), you could consider restoring the values through a decorator at the login and logout views. See:

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

like image 27
vdboor Avatar answered Nov 15 '22 07:11

vdboor