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?
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).
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.
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.
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 ;)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With