~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/dispatch/request.py

  • Committer: William Grant
  • Date: 2010-07-20 04:52:31 UTC
  • mto: This revision was merged to the branch mainline in revision 1826.
  • Revision ID: grantw@unimelb.edu.au-20100720045231-8ia3uk8nao8zdq1i
Replace cjson with json, or simplejson if json is not available (Python <2.6)

Show diffs side-by-side

added added

removed removed

Lines of Context:
25
25
object.
26
26
"""
27
27
 
28
 
import mod_python
29
 
from mod_python import (util, Session, Cookie)
 
28
try:
 
29
    import mod_python.Session
 
30
    import mod_python.Cookie
 
31
    import mod_python.util
 
32
    import mod_python.apache
 
33
 
 
34
    class PotentiallySecureFileSession(mod_python.Session.FileSession):
 
35
        """A mod_python FileSession that sets secure cookie when appropriate.
 
36
 
 
37
        A secure cookie will be set if the request itself is over HTTPS, or if
 
38
        a proxy in front has set X-Forwarded-Proto: https. Otherwise the cookie
 
39
        will be insecure.
 
40
        """
 
41
        def make_cookie(self):
 
42
            cookie = super(PotentiallySecureFileSession, self).make_cookie()
 
43
            if (self._req.is_https() or
 
44
                self._req.headers_in.get('X-Forwarded-Proto') == 'https'):
 
45
                cookie.secure = True
 
46
            return cookie
 
47
except ImportError:
 
48
    # This needs to be importable from outside Apache.
 
49
    pass
 
50
 
 
51
import os.path
30
52
 
31
53
import ivle.util
32
 
import ivle.conf
33
54
import ivle.database
34
 
import plugins.console # XXX: Relies on www/ being in the Python path.
 
55
from ivle.webapp.base.plugins import CookiePlugin
 
56
import ivle.webapp.security
 
57
 
35
58
 
36
59
class Request:
37
60
    """An IVLE request object. This is presented to the IVLE apps as a way of
42
65
            String. The request method (eg. 'GET', 'POST', etc)
43
66
        uri (read)
44
67
            String. The path portion of the URI.
 
68
        unparsed_uri (read)
 
69
            String. The path portion of the URI, unparsed with query string.
45
70
        app (read)
46
71
            String. Name of the application specified in the URL, or None.
47
72
        path (read)
73
98
        location (write)
74
99
            String. Response "Location" header value. Used with HTTP redirect
75
100
            responses.
76
 
        title (write)
77
 
            String. HTML page title. Used if write_html_head_foot is True, in
78
 
            the HTML title element text.
79
 
        styles (write)
80
 
            List of strings. Write a list of URLs to CSS files here, and they
81
 
            will be incorporated as <link rel="stylesheet" type="text/css">
82
 
            elements in the head, if write_html_head_foot is True.
83
 
            URLs should be relative to the IVLE root; they will be fixed up
84
 
            to be site-relative.
85
 
        scripts (write)
86
 
            List of strings. Write a list of URLs to JS files here, and they
87
 
            will be incorporated as <script type="text/javascript"> elements
88
 
            in the head, if write_html_head_foot is True.
89
 
            URLs should be relative to the IVLE root; they will be fixed up
90
 
            to be site-relative.
91
 
        scripts_init (write)
92
 
            List of strings. Write a list of JS function names, and they
93
 
            will be added as window.addListener('load', ..., false); calls
94
 
            in the head, if write_html_head_foot is True.
95
 
            This is the propper way to specify functions that need to run at 
96
 
            page load time.
97
 
        write_html_head_foot (write)
98
 
            Boolean. If True, dispatch assumes that this is an XHTML page, and
99
 
            will immediately write a full HTML head, open the body element,
100
 
            and write heading contents to the page, before any bytes are
101
 
            written. It will then write footer contents and close the body and
102
 
            html elements at the end of execution.  
103
 
 
104
 
            This value should be set to true by all applications for all HTML
105
 
            output (unless there is a good reason, eg. exec). The
106
 
            applications should therefore output HTML content assuming that
107
 
            it will be written inside the body tag. Do not write opening or
108
 
            closing <html> or <body> tags.
109
101
    """
110
102
 
111
103
    # Special code for an OK response.
115
107
 
116
108
    # HTTP status codes
117
109
 
118
 
    HTTP_CONTINUE                     = 100
119
 
    HTTP_SWITCHING_PROTOCOLS          = 101
120
 
    HTTP_PROCESSING                   = 102
121
110
    HTTP_OK                           = 200
122
 
    HTTP_CREATED                      = 201
123
 
    HTTP_ACCEPTED                     = 202
124
 
    HTTP_NON_AUTHORITATIVE            = 203
125
 
    HTTP_NO_CONTENT                   = 204
126
 
    HTTP_RESET_CONTENT                = 205
127
 
    HTTP_PARTIAL_CONTENT              = 206
128
 
    HTTP_MULTI_STATUS                 = 207
129
 
    HTTP_MULTIPLE_CHOICES             = 300
130
 
    HTTP_MOVED_PERMANENTLY            = 301
131
111
    HTTP_MOVED_TEMPORARILY            = 302
132
 
    HTTP_SEE_OTHER                    = 303
133
 
    HTTP_NOT_MODIFIED                 = 304
134
 
    HTTP_USE_PROXY                    = 305
135
 
    HTTP_TEMPORARY_REDIRECT           = 307
136
 
    HTTP_BAD_REQUEST                  = 400
137
 
    HTTP_UNAUTHORIZED                 = 401
138
 
    HTTP_PAYMENT_REQUIRED             = 402
139
112
    HTTP_FORBIDDEN                    = 403
140
113
    HTTP_NOT_FOUND                    = 404
141
 
    HTTP_METHOD_NOT_ALLOWED           = 405
142
 
    HTTP_NOT_ACCEPTABLE               = 406
143
 
    HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
144
 
    HTTP_REQUEST_TIME_OUT             = 408
145
 
    HTTP_CONFLICT                     = 409
146
 
    HTTP_GONE                         = 410
147
 
    HTTP_LENGTH_REQUIRED              = 411
148
 
    HTTP_PRECONDITION_FAILED          = 412
149
 
    HTTP_REQUEST_ENTITY_TOO_LARGE     = 413
150
 
    HTTP_REQUEST_URI_TOO_LARGE        = 414
151
 
    HTTP_UNSUPPORTED_MEDIA_TYPE       = 415
152
 
    HTTP_RANGE_NOT_SATISFIABLE        = 416
153
 
    HTTP_EXPECTATION_FAILED           = 417
154
 
    HTTP_UNPROCESSABLE_ENTITY         = 422
155
 
    HTTP_LOCKED                       = 423
156
 
    HTTP_FAILED_DEPENDENCY            = 424
157
114
    HTTP_INTERNAL_SERVER_ERROR        = 500
158
 
    HTTP_NOT_IMPLEMENTED              = 501
159
 
    HTTP_BAD_GATEWAY                  = 502
160
 
    HTTP_SERVICE_UNAVAILABLE          = 503
161
 
    HTTP_GATEWAY_TIME_OUT             = 504
162
 
    HTTP_VERSION_NOT_SUPPORTED        = 505
163
 
    HTTP_VARIANT_ALSO_VARIES          = 506
164
 
    HTTP_INSUFFICIENT_STORAGE         = 507
165
 
    HTTP_NOT_EXTENDED                 = 510
166
 
 
167
 
    def __init__(self, req, write_html_head):
168
 
        """Builds an IVLE request object from a mod_python request object.
169
 
        This results in an object with all of the necessary methods and
170
 
        additional fields.
171
 
 
172
 
        req: A mod_python request object.
173
 
        write_html_head: Function which is called when writing the automatic
174
 
            HTML header. Accepts a single argument, the IVLE request object.
 
115
 
 
116
    _store = None
 
117
 
 
118
    def __init__(self, req, config):
 
119
        """Create an IVLE request from a mod_python one.
 
120
 
 
121
        @param req: A mod_python request.
 
122
        @param config: An IVLE configuration.
175
123
        """
176
124
 
177
125
        # Methods are mostly wrappers around the Apache request object
178
126
        self.apache_req = req
179
 
        self.func_write_html_head = write_html_head
 
127
        self.config = config
180
128
        self.headers_written = False
181
129
 
182
130
        # Determine if the browser used the public host name to make the
183
131
        # request (in which case we are in "public mode")
184
 
        if req.hostname == ivle.conf.public_host:
 
132
        if req.hostname == config['urls']['public_host']:
185
133
            self.publicmode = True
186
134
        else:
187
135
            self.publicmode = False
189
137
        # Inherit values for the input members
190
138
        self.method = req.method
191
139
        self.uri = req.uri
 
140
        self.unparsed_uri = req.unparsed_uri
192
141
        # Split the given path into the app (top-level dir) and sub-path
193
142
        # (after first stripping away the root directory)
194
 
        path = ivle.util.unmake_path(req.uri)
195
 
        (self.app, self.path) = (ivle.util.split_path(path))
196
 
        self.user = None
 
143
        (self.app, self.path) = (ivle.util.split_path(req.uri))
197
144
        self.hostname = req.hostname
198
145
        self.headers_in = req.headers_in
199
146
        self.headers_out = req.headers_out
200
147
 
201
 
        # Open a database connection and transaction, keep it around for users
202
 
        # of the Request object to use
203
 
        self.store = ivle.database.get_store()
204
 
 
205
148
        # Default values for the output members
206
149
        self.status = Request.HTTP_OK
207
150
        self.content_type = None        # Use Apache's default
208
151
        self.location = None
209
 
        self.title = None     # Will be set by dispatch before passing to app
210
 
        self.styles = []
211
 
        self.scripts = []
212
 
        self.scripts_init = []
213
 
        self.write_html_head_foot = False
214
152
        # In some cases we don't want the template JS (such as the username
215
153
        # and public FQDN) in the output HTML. In that case, set this to 0.
216
154
        self.write_javascript_settings = True
217
155
        self.got_common_vars = False
218
156
 
219
157
    def __del__(self):
220
 
        """Cleanup."""
221
 
        self.store.close()
 
158
        self.cleanup()
 
159
 
 
160
    def cleanup(self):
 
161
        """Cleanup."""
 
162
        if self._store is not None:
 
163
            self._store.close()
 
164
            self._store = None
 
165
 
 
166
    def commit(self):
 
167
        """Cleanup."""
 
168
        if self._store is not None:
 
169
            self._store.commit()
222
170
 
223
171
    def __writeheaders(self):
224
172
        """Writes out the HTTP and HTML headers before any real data is
225
173
        written."""
226
174
        self.headers_written = True
227
 
        
228
 
        # app is the App object for the chosen app
229
 
        try:
230
 
            app = ivle.conf.apps.app_url[self.app]
231
 
        except KeyError:
232
 
            app = None
233
 
 
234
 
        # Write any final modifications to header content
235
 
        if app and app.useconsole and self.user:
236
 
            plugins.console.insert_scripts_styles(self.scripts, self.styles, \
237
 
                self.scripts_init)
238
175
 
239
176
        # Prepare the HTTP and HTML headers before the first write is made
240
177
        if self.content_type != None:
242
179
        self.apache_req.status = self.status
243
180
        if self.location != None:
244
181
            self.apache_req.headers_out['Location'] = self.location
245
 
        if self.write_html_head_foot:
246
 
            # Write the HTML header, pass "self" (request object)
247
 
            self.func_write_html_head(self)
248
182
 
249
183
    def ensure_headers_written(self):
250
184
        """Writes out the HTTP and HTML headers if they haven't already been
267
201
            # This includes binary strings.
268
202
            self.apache_req.write(string, flush)
269
203
 
 
204
    def logout(self):
 
205
        """Log out the current user by destroying the session state.
 
206
        Then redirect to the top-level IVLE page."""
 
207
        if hasattr(self, 'session'):
 
208
            self.session.invalidate()
 
209
            self.session.delete()
 
210
            # Invalidates all IVLE cookies
 
211
            all_cookies = mod_python.Cookie.get_cookies(self)
 
212
 
 
213
            # Create cookies for plugins that might request them.
 
214
            for plugin in self.config.plugin_index[CookiePlugin]:
 
215
                for cookie in plugin.cookies:
 
216
                    self.add_cookie(mod_python.Cookie.Cookie(cookie, '',
 
217
                                                    expires=1, path='/'))
 
218
        self.throw_redirect(self.make_path(''))
 
219
 
 
220
 
270
221
    def flush(self):
271
222
        """Flushes the output buffer."""
272
223
        self.apache_req.flush()
285
236
        else:
286
237
            return self.apache_req.read(len)
287
238
 
288
 
    def throw_error(self, httpcode, message=None):
289
 
        """Writes out an HTTP error of the specified code. Raises an exception
290
 
        which is caught by the dispatch or web server, so any code following
291
 
        this call will not be executed.
292
 
 
293
 
        httpcode: An HTTP response status code. Pass a constant from the
294
 
        Request class.
295
 
        """
296
 
        raise ivle.util.IVLEError(httpcode, message)
297
 
 
298
239
    def throw_redirect(self, location):
299
240
        """Writes out an HTTP redirect to the specified URL. Raises an
300
241
        exception which is caught by the dispatch or web server, so any
310
251
    def add_cookie(self, cookie, value=None, **attributes):
311
252
        """Inserts a cookie into this request object's headers."""
312
253
        if value is None:
313
 
            Cookie.add_cookie(self.apache_req, cookie)
 
254
            mod_python.Cookie.add_cookie(self.apache_req, cookie)
314
255
        else:
315
 
            Cookie.add_cookie(self.apache_req, cookie, value, **attributes)
 
256
            mod_python.Cookie.add_cookie(self.apache_req, cookie, value, **attributes)
 
257
 
 
258
    def make_path(self, path):
 
259
        """Prepend the IVLE URL prefix to the given path.
 
260
 
 
261
        This is used when generating URLs to send to the client.
 
262
 
 
263
        This method is DEPRECATED. We no longer support use of a prefix.
 
264
        """
 
265
        return os.path.join(self.config['urls']['root'], path)
316
266
 
317
267
    def get_session(self):
318
268
        """Returns a mod_python Session object for this request.
319
269
        Note that this is dependent on mod_python and may need to change
320
 
        interface if porting away from mod_python."""
 
270
        interface if porting away from mod_python.
 
271
 
 
272
        IMPORTANT: Call unlock() on the session as soon as you are done with
 
273
                   it! If you don't, all other requests will block!
 
274
        """
321
275
        # Cache the session object and set the timeout to 24 hours.
322
276
        if not hasattr(self, 'session'):
323
 
            self.session = Session.FileSession(self.apache_req,
324
 
                                               timeout = 60 * 60 * 24)
 
277
            self.session = PotentiallySecureFileSession(
 
278
                self.apache_req, timeout = 60 * 60 * 24)
325
279
        return self.session
326
280
 
327
281
    def get_fieldstorage(self):
330
284
        interface if porting away from mod_python."""
331
285
        # Cache the fieldstorage object
332
286
        if not hasattr(self, 'fields'):
333
 
            self.fields = util.FieldStorage(self.apache_req)
 
287
            self.fields = mod_python.util.FieldStorage(self.apache_req)
334
288
        return self.fields
335
289
 
336
290
    def get_cgi_environ(self):
342
296
            self.got_common_vars = True
343
297
        return self.apache_req.subprocess_env
344
298
 
345
 
    @staticmethod
346
 
    def get_http_codename(code):
347
 
        """Given a HTTP error code int, returns a (name, description)
348
 
        pair, suitable for displaying to the user.
349
 
        May return (None,None) if code is unknown.
350
 
        Only lists common 4xx and 5xx codes (since this is just used
351
 
        to display throw_error error messages).
352
 
        """
 
299
    @property
 
300
    def store(self):
 
301
        # Open a database connection and transaction, keep it around for users
 
302
        # of the Request object to use.
 
303
        if self._store is None:
 
304
            self._store = ivle.database.get_store(self.config)
 
305
        return self._store
 
306
 
 
307
    @property
 
308
    def user(self):
 
309
        # Get and cache the request user, or None if it's not valid.
 
310
        # This is a property so that we don't create a store unless
 
311
        # some code actually requests the user.
353
312
        try:
354
 
            return http_codenames[code]
355
 
        except KeyError:
356
 
            return None, None
 
313
            return self._user
 
314
        except AttributeError:
 
315
            if self.publicmode:
 
316
                self._user = None
 
317
            else:
 
318
                temp_user = ivle.webapp.security.get_user_details(self)
 
319
                if temp_user and temp_user.valid:
 
320
                    self._user = temp_user
 
321
                else:
 
322
                    self._user = None
 
323
            return self._user
357
324
 
358
 
# Human strings for HTTP response codes
359
 
http_codenames = {
360
 
    Request.HTTP_BAD_REQUEST:
361
 
        ("Bad Request",
362
 
        "Your browser sent a request IVLE did not understand."),
363
 
    Request.HTTP_UNAUTHORIZED:
364
 
        ("Unauthorized",
365
 
        "You are not allowed to view this part of IVLE."),
366
 
    Request.HTTP_FORBIDDEN:
367
 
        ("Forbidden",
368
 
        "You are not allowed to view this part of IVLE."),
369
 
    Request.HTTP_NOT_FOUND:
370
 
        ("Not Found",
371
 
        "The application or file you requested does not exist."),
372
 
    Request.HTTP_METHOD_NOT_ALLOWED:
373
 
        ("Method Not Allowed",
374
 
        "Your browser is interacting with IVLE in the wrong way."
375
 
        "This is probably a bug in IVLE. "
376
 
        "Please report it to the administrators."),
377
 
    Request.HTTP_INTERNAL_SERVER_ERROR:
378
 
        ("Internal Server Error",
379
 
        "An unknown error occured in IVLE."),
380
 
    Request.HTTP_NOT_IMPLEMENTED:
381
 
        ("Not Implemented",
382
 
        "The application or file you requested has not been implemented "
383
 
        "in IVLE."),
384
 
    Request.HTTP_SERVICE_UNAVAILABLE:
385
 
        ("Service Unavailable",
386
 
        "IVLE is currently experiencing technical difficulties. "
387
 
        "Please try again later."),
388
 
}