Ticket #3716: newsessions.patch

File newsessions.patch, 7.6 KB (added by Anton Khalikov <anton@…>, 18 years ago)

newsessions module

  • django/contrib/newsessions/middleware.py

     
     1from django.conf import settings
     2from django.contrib.newsessions.models import Session
     3from django.core.exceptions import SuspiciousOperation
     4from django.utils.cache import patch_vary_headers
     5import datetime
     6
     7TEST_COOKIE_NAME = 'testcookie'
     8TEST_COOKIE_VALUE = 'worked'
     9
     10class SessionWrapper(object):
     11    def __init__(self, session_key, remote_addr):
     12        self.session_key = session_key
     13        self._pk = None
     14        self.modified = False
     15        self.remote_addr = remote_addr
     16
     17    def __contains__(self, key):
     18        return key in self._session
     19
     20    def __getitem__(self, key):
     21        return self._session[key]
     22
     23    def __setitem__(self, key, value):
     24        self._session[key] = value
     25        self.modified = True
     26
     27    def __delitem__(self, key):
     28        del self._session[key]
     29        self.modified = True
     30
     31    def keys(self):
     32        return self._session.keys()
     33
     34    def items(self):
     35        return self._session.items()
     36
     37    def get(self, key, default=None):
     38        return self._session.get(key, default)
     39
     40    def set_test_cookie(self):
     41        self[TEST_COOKIE_NAME] = TEST_COOKIE_VALUE
     42
     43    def test_cookie_worked(self):
     44        return self.get(TEST_COOKIE_NAME) == TEST_COOKIE_VALUE
     45
     46    def delete_test_cookie(self):
     47        del self[TEST_COOKIE_NAME]
     48
     49    def _get_session(self):
     50        # Lazily loads session from storage.
     51        try:
     52            return self._session_cache
     53        except AttributeError:
     54            if self.session_key is None:
     55                s = Session.objects.get_new_session(self.remote_addr)
     56            else:
     57                try:
     58                    s = Session.objects.get(session_key=self.session_key, expire_date__gt=datetime.datetime.now(), remote_addr=self.remote_addr)
     59                except (Session.DoesNotExist, SuspiciousOperation):
     60                    s = Session.objects.get_new_session(self.remote_addr)
     61            self.session_key = s.session_key
     62            self._session_cache = s.get_decoded()
     63            self._pk = s.id
     64            return self._session_cache
     65
     66    _session = property(_get_session)
     67
     68class SessionMiddleware(object):
     69    def process_request(self, request):
     70        request.session = SessionWrapper(request.COOKIES.get(settings.SESSION_COOKIE_NAME, None), request.META['REMOTE_ADDR'])
     71
     72    def process_response(self, request, response):
     73        # If request.session was modified, or if response.session was set, save
     74        # those changes and set a session cookie.
     75        patch_vary_headers(response, ('Cookie',))
     76        try:
     77            modified = request.session.modified
     78        except AttributeError:
     79            pass
     80        else:
     81            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
     82                if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE:
     83                    max_age = None
     84                    expires = None
     85                else:
     86                    max_age = settings.SESSION_COOKIE_AGE
     87                    expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT")
     88                if not request.session._pk:
     89                    request.session._session
     90                new_session = Session.objects.save(request.session._pk, request.session.session_key, request.session._session,
     91                    datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), request.META['REMOTE_ADDR'])
     92                response.set_cookie(settings.SESSION_COOKIE_NAME, request.session.session_key,
     93                    max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
     94                    secure=settings.SESSION_COOKIE_SECURE or None)
     95        return response
  • django/contrib/newsessions/models.py

     
     1import base64, md5, random, sys
     2import cPickle as pickle
     3from django.db import models
     4from django.utils.translation import gettext_lazy as _
     5from django.conf import settings
     6import datetime
     7
     8class SessionManager(models.Manager):
     9    def encode(self, session_dict):
     10        "Returns the given session dictionary pickled and encoded as a string."
     11        pickled = pickle.dumps(session_dict)
     12        pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest()
     13        return base64.encodestring(pickled + pickled_md5)
     14
     15    def get_new_session(self, remote_addr):
     16        "Returns session key that isn't being used."
     17        # The random module is seeded when this Apache child is created.
     18        # Use person_id and SECRET_KEY as added salt.
     19        while 1:
     20            session_key = md5.new(str(random.randint(0, sys.maxint - 1)) + str(random.randint(0, sys.maxint - 1)) + settings.SECRET_KEY).hexdigest()
     21            try:
     22                return self.save(None, session_key, {}, datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE), remote_addr)
     23            except:
     24                pass
     25
     26    def save(self, id, session_key, session_dict, expire_date, remote_addr):
     27        s = self.model(id, session_key, self.encode(session_dict), expire_date, remote_addr)
     28        if session_dict or not id:
     29            s.save()
     30        else:
     31            s.delete() # Clear sessions with no data.
     32        return s
     33
     34class Session(models.Model):
     35    """
     36    Django provides full support for anonymous sessions. The session
     37    framework lets you store and retrieve arbitrary data on a
     38    per-site-visitor basis. It stores data on the server side and
     39    abstracts the sending and receiving of cookies. Cookies contain a
     40    session ID -- not the data itself.
     41
     42    The Django sessions framework is entirely cookie-based. It does
     43    not fall back to putting session IDs in URLs. This is an intentional
     44    design decision. Not only does that behavior make URLs ugly, it makes
     45    your site vulnerable to session-ID theft via the "Referer" header.
     46
     47    For complete documentation on using Sessions in your code, consult
     48    the sessions documentation that is shipped with Django (also available
     49    on the Django website).
     50    """
     51    session_key = models.CharField(_('session key'), maxlength=40, unique=True)
     52    session_data = models.TextField(_('session data'))
     53    expire_date = models.DateTimeField(_('expire date'))
     54    remote_addr = models.IPAddressField(_('ip address'))
     55    objects = SessionManager()
     56    class Meta:
     57        db_table = 'django_newsession'
     58        verbose_name = _('session')
     59        verbose_name_plural = _('sessions')
     60
     61    def get_decoded(self):
     62        encoded_data = base64.decodestring(self.session_data)
     63        pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
     64        if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
     65            from django.core.exceptions import SuspiciousOperation
     66            raise SuspiciousOperation, "User tampered with session cookie."
     67        try:
     68            return pickle.loads(pickled)
     69        # Unpickling can cause a variety of exceptions. If something happens,
     70        # just return an empty dictionary (an empty session).
     71        except:
     72            return {}
Back to Top