django - Using login() loses the session data -
when sessions created , destroyed? in application have
def app_login(request): request.session.set_expiry(0) if 'current_day' not in request.session: request.session['current_day'] = utilities.default_day()
then further down use :
login(request, user)
if login in user, works fine , 'current_day' retained in session. if log out user , log in another, 'current_day' lost , not available after calling login().
i assume that
logout(request)
does not clear session, , when second user tries login data 'current_'day' still available in session calling login(user) presumably creates new session.
is assumption correct , how best correct this?
def login(request, user): """ persist user id , backend in request. way user doesn't have reauthenticate on every request. note data set during anonymous session retained when user logs in. """ if user none: user = request.user # todo: nice support different login methods, signed cookies. if session_key in request.session: if request.session[session_key] != user.pk: # avoid reusing user's session, create new, empty # session if existing session corresponds different # authenticated user. request.session.flush() else: request.session.cycle_key() request.session[session_key] = user.pk request.session[backend_session_key] = user.backend if hasattr(request, 'user'): request.user = user user_logged_in.send(sender=user.__class__, request=request, user=user)
anonymous sessions retained (they don't have session_key
), relogin different user flushes session.
logout flushes session:
def logout(request): """ removes authenticated user's id request , flushes session data. """ # dispatch signal before user logged out receivers have # chance find out *who* logged out. user = getattr(request, 'user', none) if hasattr(user, 'is_authenticated') , not user.is_authenticated(): user = none user_logged_out.send(sender=user.__class__, request=request, user=user) request.session.flush() if hasattr(request, 'user'): django.contrib.auth.models import anonymoususer request.user = anonymoususer()
these 2 cases when session flushed.
you should set current_day
after logging in (or check existence on every request custom middleware).
Comments
Post a Comment