summaryrefslogtreecommitdiff
path: root/paste/session.py
blob: 3219fab89969c31b25d1561799ad5e2e82f87c90 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

"""
Creates a session object in your WSGI environment.

Use like:

..code-block:: Python

    environ['paste.session.factory']()

This will return a dictionary.  The contents of this dictionary will
be saved to disk when the request is completed.  The session will be
created when you first fetch the session dictionary, and a cookie will
be sent in that case.  There's current no way to use sessions without
cookies, and there's no way to delete a session except to clear its
data.

@@: This doesn't do any locking, and may cause problems when a single
session is accessed concurrently.  Also, it loads and saves the
session for each request, with no caching.  Also, sessions aren't
expired.
"""

from Cookie import SimpleCookie
import time
import random
import os
import md5
import datetime
import threading

try:
    import cPickle
except ImportError:
    import pickle as cPickle
import wsgilib
import request

class SessionMiddleware(object):

    def __init__(self, application, global_conf=None, **factory_kw):
        self.application = application
        self.factory_kw = factory_kw

    def __call__(self, environ, start_response):
        session_factory = SessionFactory(environ, **self.factory_kw)
        environ['paste.session.factory'] = session_factory
        remember_headers = []

        def session_start_response(status, headers, exc_info=None):
            if not session_factory.created:
                remember_headers[:] = [status, headers]
                return start_response(status, headers)
            headers.append(session_factory.set_cookie_header())
            return start_response(status, headers, exc_info)

        app_iter = self.application(environ, session_start_response)
        def start():
            if session_factory.created and remember_headers:
                # Tricky bastard used the session after start_response
                status, headers = remember_headers
                headers.append(session_factory.set_cookie_header())
                exc = ValueError(
                    "You cannot get the session after content from the "
                    "app_iter has been returned")
                start_response(status, headers, (exc.__class__, exc, None))
        def close():
            if session_factory.used:
                session_factory.close()
        return wsgilib.add_start_close(app_iter, start, close)


class SessionFactory(object):


    def __init__(self, environ, cookie_name='_SID_',
                 session_class=None,
                 expiration=60*12, # in minutes
                 **session_class_kw):
        
        self.created = False
        self.used = False
        self.environ = environ
        self.cookie_name = cookie_name
        self.session = None
        self.session_class = session_class or FileSession
        self.session_class_kw = session_class_kw

        self.expiration = expiration
        self.session_class_kw['expiration'] = self.expiration

    def __call__(self):
        self.used = True
        if self.session is not None:
            return self.session.data()
        cookies = request.get_cookies(self.environ)
        session = None
        if cookies.has_key(self.cookie_name):
            self.sid = cookies[self.cookie_name].value
            try:
                session = self.session_class(self.sid, create=False,
                                             **self.session_class_kw)
            except KeyError:
                # Invalid SID
                pass
        if session is None:
            self.created = True
            self.sid = self.make_sid()
            session = self.session_class(self.sid, create=True,
                                         **self.session_class_kw)
        session.clean_up()
        self.session = session
        return session.data()

    def has_session(self):
        if self.session is not None:
            return True
        cookies = request.get_cookies(self.environ)
        if cookies.has_key(self.cookie_name):
            return True
        return False

    def make_sid(self):
        # @@: need better algorithm
        return (''.join(['%02d' % x for x in time.localtime(time.time())[:6]])
                + '-' + self.unique_id())

    def unique_id(self, for_object=None):
        """
        Generates an opaque, identifier string that is practically
        guaranteed to be unique.  If an object is passed, then its
        id() is incorporated into the generation.  Relies on md5 and
        returns a 32 character long string.
        """
        r = [time.time(), random.random(), os.times()]
        if for_object is not None:
            r.append(id(for_object))
        md5_hash = md5.new(str(r))
        try:
            return md5_hash.hexdigest()
        except AttributeError:
            # Older versions of Python didn't have hexdigest, so we'll
            # do it manually
            hexdigest = []
            for char in md5_hash.digest():
                hexdigest.append('%02x' % ord(char))
            return ''.join(hexdigest)

    def set_cookie_header(self):
        c = SimpleCookie()
        c[self.cookie_name] = self.sid
        c[self.cookie_name]['path'] = '/'

        gmt_expiration_time = time.gmtime(time.time() + (self.expiration * 60))
        c[self.cookie_name]['expires'] = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", gmt_expiration_time)

        name, value = str(c).split(': ', 1)
        return (name, value)

    def close(self):
        if self.session is not None:
            self.session.close()


last_cleanup = None
cleaning_up = False
cleanup_cycle = datetime.timedelta(seconds=15*60) #15 min

class FileSession(object):

    def __init__(self, sid, create=False, session_file_path='/tmp',
                 chmod=None,
                 expiration=2880, # in minutes: 48 hours
                 ):
        if chmod and isinstance(chmod, basestring):
            chmod = int(chmod, 8)
        self.chmod = chmod
        if not sid:
            # Invalid...
            raise KeyError
        self.session_file_path = session_file_path
        self.sid = sid
        if not create:
            if not os.path.exists(self.filename()):
                raise KeyError
        self._data = None

        self.expiration = expiration


    def filename(self):
        return os.path.join(self.session_file_path, self.sid)

    def data(self):
        if self._data is not None:
            return self._data
        if os.path.exists(self.filename()):
            f = open(self.filename(), 'rb')
            self._data = cPickle.load(f)
            f.close()
        else:
            self._data = {}
        return self._data

    def close(self):
        if self._data is not None:
            filename = self.filename()
            exists = os.path.exists(filename)
            if not self._data:
                if exists:
                    os.unlink(filename)
            else:
                f = open(filename, 'wb')
                cPickle.dump(self._data, f)
                f.close()
                if not exists and self.chmod:
                    os.chmod(filename, self.chmod)

    def _clean_up(self):
        global cleaning_up
        try:
            exp_time = datetime.timedelta(seconds=self.expiration*60)
            now = datetime.datetime.now()

            #Open every session and check that it isn't too old
            for root, dirs, files in os.walk(self.session_file_path):
                for f in files:
                    self._clean_up_file(f)
        finally:
            cleaning_up = False

    def _clean_up_file(self, f):
        t = f.split("-")
        if len(t) != 2:
            return
        t = t[0]
        sess_time = datetime.datetime(
                int(t[0:4]),
                int(t[4:6]),
                int(t[6:8]),
                int(t[8:10]),
                int(t[10:12]),
                int(t[12:14]))

        if sess_time + exp_time < now:
            os.remove(os.path.join(self.session_file_path, f))

    def clean_up(self):
        global last_cleanup, cleanup_cycle, cleaning_up
        now = datetime.datetime.now()

        if cleaning_up:
            return

        if not last_cleanup or last_cleanup + cleanup_cycle < now:
            if not cleaning_up:
                cleaning_up = True
                try:
                    last_cleanup = now
                    t = threading.Thread(target=self._clean_up)
                    t.start()
                except:
                    # Normally _clean_up should set cleaning_up
                    # to false, but if something goes wrong starting
                    # it...
                    cleaning_up = False
                    raise