Skip to content

Instantly share code, notes, and snippets.

@darkpixel
Last active February 25, 2023 22:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save darkpixel/3473470 to your computer and use it in GitHub Desktop.
Save darkpixel/3473470 to your computer and use it in GitHub Desktop.
Don't lose model association with a Session object when logging in
def cycle_key(self):
#TODO: Errors here will tank the system, probably need some better handling...
old_session_key = self.session_key
old_session = Session.objects.get(session_key=old_session_key)
try:
cart = Cart.objects.get(session=old_session)
super(SessionStore, self).cycle_key()
new_session_key = self.session_key
new_session = Session.objects.get(session_key=new_session_key)
cart.session = new_session
cart.save()
logger.debug('Migrated cart from session %s to %s' %(old_session_key, new_session_key))
except Cart.DoesNotExist:
logger.debug('Session %s does not have a cart to migrate' %(old_session_key))
# @strogonoff points out that we don't care about losing the association between
# the session and cart when we encounter Cart.DoesNotExist. But we should probably be cycling
# key
super(SessionStore, self).cycle_key()
@strogonoff
Copy link

Apologies for necromancy—do you forget to call super().cycle_key() in your exception handler, or do you avoid that on purpose?

@darkpixel
Copy link
Author

We should totally be cycling the key there. While I don't think Django itself calls cycle_key anywhere, a developer might call it when they specifically want to end an old session and start a new one. If the session didn't have a shopping cart it could lead to cycle_key not actually being called which could potentially be a security issue. Nice catch @strogonoff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment