Ticket #2548: session_middleware.3.diff

File session_middleware.3.diff, 2.3 KB (added by upadhyay@…, 8 years ago)

In the last patch tere still is some problem, if session is modified after the cookie is set, django will revert the cookie to expire when browser closes. The only solution seems to be to put the expires_time itself in the session so it can get preserved.

  • contrib/sessions/middleware.py

     
    4848    def delete_test_cookie(self):
    4949        del self[TEST_COOKIE_NAME]
    5050
     51    def set_expires(self, val):
     52        self["_expires_on"] = datetime.datetime.now() + datetime.timedelta(seconds=val)
     53
     54    def get_expires(self):
     55        return self.get("_expires_on", None)
     56
     57
    5158    def _get_session(self):
    5259        # Lazily loads session from storage.
    5360        self.accessed = True
     
    6976            return self._session_cache
    7077
    7178    _session = property(_get_session)
     79    expires = property(get_expires, set_expires)
    7280
    7381class SessionMiddleware(object):
    7482    def process_request(self, request):
     
    92100                    obj = Session.objects.get_new_session_object()
    93101                    session_key = obj.session_key
    94102
    95                 if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE:
     103                now = datetime.datetime.now()
     104                delta_yield = now + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE)
     105                if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE and not request.session.expires:
    96106                    max_age = None
    97107                    expires = None
    98108                else:
    99                     max_age = settings.SESSION_COOKIE_AGE
    100                     expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT")
     109                    delta_yield = request.session.expires or delta_yield
     110                    max_age_timedelta = delta_yield - now
     111                    max_age = max_age_timedelta.days * 24 * 60 * 60 + max_age_timedelta.seconds
     112                    expires = datetime.datetime.strftime(delta_yield, "%a, %d-%b-%Y %H:%M:%S GMT")
    101113                new_session = Session.objects.save(session_key, request.session._session,
    102                     datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE))
     114                    delta_yield)
    103115                response.set_cookie(settings.SESSION_COOKIE_NAME, session_key,
    104116                    max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
    105117                    secure=settings.SESSION_COOKIE_SECURE or None)
Back to Top