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

« back to all changes in this revision

Viewing changes to ivle/dispatch/__init__.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:
22
22
Apache send all requests to be handled by the module 'dispatch'.
23
23
 
24
24
Top-level handler. Handles all requests to all pages in IVLE.
25
 
Handles authentication (not authorization).
26
 
Then passes the request along to the appropriate ivle app.
 
25
Handles authentication and delegates to views for authorization,
 
26
then passes the request along to the appropriate view.
27
27
"""
28
28
 
29
29
import sys
30
30
import os
31
31
import os.path
32
32
import urllib
 
33
import urlparse
33
34
import cgi
34
35
import traceback
35
36
import logging
37
38
import time
38
39
 
39
40
import mod_python
40
 
import routes
41
41
 
42
42
from ivle import util
43
 
import ivle.conf
44
 
import ivle.conf.apps
 
43
import ivle.config
45
44
from ivle.dispatch.request import Request
46
 
from ivle.dispatch import login
47
 
import apps
48
 
import html
49
 
import plugins.console # XXX: Relies on www/ being in the Python path.
50
 
 
51
 
# XXX List of plugins, which will eventually be read in from conf
52
 
plugins_HACK = [
53
 
    'ivle.webapp.admin.user#Plugin',
54
 
    'ivle.webapp.tutorial#Plugin',
55
 
    'ivle.webapp.admin.subject#Plugin',
56
 
    'ivle.webapp.browser#Plugin',
57
 
    'ivle.webapp.groups#Plugin',
58
 
    'ivle.webapp.console#Plugin',
59
 
    'ivle.webapp.security#Plugin',
60
 
]
61
 
 
62
 
def get_routes_mapper():
 
45
import ivle.webapp.security
 
46
from ivle.webapp.base.plugins import ViewPlugin, PublicViewPlugin
 
47
from ivle.webapp.base.xhtml import XHTMLView, XHTMLErrorView
 
48
from ivle.webapp.errors import BadRequest, HTTPError, NotFound, Unauthorized
 
49
from ivle.webapp.publisher import Publisher, PublishingError
 
50
from ivle.webapp import ApplicationRoot
 
51
 
 
52
config = ivle.config.Config()
 
53
 
 
54
class ObjectPermissionCheckingPublisher(Publisher):
 
55
    """A specialised publisher that checks object permissions.
 
56
 
 
57
    This publisher verifies that the user holds any permission at all
 
58
    on the model objects through which the resolution path passes. If
 
59
    no permission is held, resolution is aborted with an Unauthorized
 
60
    exception.
 
61
 
 
62
    IMPORTANT: This does NOT check view permissions. It only checks
 
63
    the objects in between the root and the view, exclusive!
 
64
    """
 
65
 
 
66
    def traversed_to_object(self, obj):
 
67
        """Check that the user has any permission at all over the object."""
 
68
        if (hasattr(obj, 'get_permissions') and
 
69
            len(obj.get_permissions(self.root.user, config)) == 0):
 
70
            # Indicate the forbidden object if this is an admin.
 
71
            if self.root.user and self.root.user.admin:
 
72
                raise Unauthorized('Unauthorized: %s' % obj)
 
73
            else:
 
74
                raise Unauthorized()
 
75
 
 
76
 
 
77
def generate_publisher(view_plugins, root, publicmode=False):
63
78
    """
64
79
    Build a Mapper object for doing URL matching using 'routes', based on the
65
 
    plugins config.
 
80
    given plugin registry.
66
81
    """
67
 
    m = routes.Mapper(explicit=True)
68
 
    for pluginstr in plugins_HACK:
69
 
        plugin_path, classname = pluginstr.split('#')
70
 
        # Load the plugin module from somewhere in the Python path
71
 
        # (Note that plugin_path is a fully-qualified Python module name).
72
 
        plugin = getattr(__import__(plugin_path, fromlist=[classname]),
73
 
            classname)
74
 
        # Establish a URL pattern for each element of plugin.urls
75
 
        for url in plugin.urls:
76
 
            routex = url[0]
77
 
            view_class = url[1]
78
 
            kwargs_dict = url[2] if len(url) >= 3 else {}
79
 
            m.connect(routex, view=view_class, **kwargs_dict)
80
 
    return m
81
 
 
82
 
def handler(req):
83
 
    """Handles a request which may be to anywhere in the site except media.
 
82
    r = ObjectPermissionCheckingPublisher(root=root)
 
83
 
 
84
    r.add_set_switch('api', 'api')
 
85
 
 
86
    if publicmode:
 
87
        view_attr = 'public_views'
 
88
        forward_route_attr = 'public_forward_routes'
 
89
        reverse_route_attr = 'public_reverse_routes'
 
90
    else:
 
91
        view_attr = 'views'
 
92
        forward_route_attr = 'forward_routes'
 
93
        reverse_route_attr = 'reverse_routes'
 
94
 
 
95
 
 
96
    for plugin in view_plugins:
 
97
        if hasattr(plugin, forward_route_attr):
 
98
            for fr in getattr(plugin, forward_route_attr):
 
99
                # An annotated function can also be passed in directly.
 
100
                if hasattr(fr, '_forward_route_meta'):
 
101
                    r.add_forward_func(fr)
 
102
                else:
 
103
                    r.add_forward(*fr)
 
104
 
 
105
        if hasattr(plugin, reverse_route_attr):
 
106
            for rr in getattr(plugin, reverse_route_attr):
 
107
                # An annotated function can also be passed in directly.
 
108
                if hasattr(rr, '_reverse_route_src'):
 
109
                    r.add_reverse_func(rr)
 
110
                else:
 
111
                    r.add_reverse(*rr)
 
112
 
 
113
        if hasattr(plugin, view_attr):
 
114
            for v in getattr(plugin, view_attr):
 
115
                r.add_view(*v)
 
116
 
 
117
    return r
 
118
 
 
119
def handler(apachereq):
 
120
    """Handles an HTTP request.
 
121
 
84
122
    Intended to be called by mod_python, as a handler.
85
123
 
86
 
    req: An Apache request object.
87
 
    """
88
 
    # Make the request object into an IVLE request which can be passed to apps
89
 
    apachereq = req
90
 
    try:
91
 
        req = Request(req, html.write_html_head)
92
 
    except Exception:
93
 
        # Pass the apachereq to error reporter, since ivle req isn't created
94
 
        # yet.
95
 
        handle_unknown_exception(apachereq, *sys.exc_info())
96
 
        # Tell Apache not to generate its own errors as well
97
 
        return mod_python.apache.OK
98
 
 
99
 
    # Run the main handler, and catch all exceptions
100
 
    try:
101
 
        return handler_(req, apachereq)
102
 
    except mod_python.apache.SERVER_RETURN:
103
 
        # An apache error. We discourage these, but they might still happen.
104
 
        # Just raise up.
105
 
        raise
106
 
    except Exception:
107
 
        handle_unknown_exception(req, *sys.exc_info())
108
 
        # Tell Apache not to generate its own errors as well
109
 
        return mod_python.apache.OK
110
 
 
111
 
def handler_(req, apachereq):
112
 
    """
113
 
    Nested handler function. May raise exceptions. The top-level handler is
114
 
    just used to catch exceptions.
115
 
    Takes both an IVLE request and an Apache req.
116
 
    """
117
 
    # Hack? Try and get the user login early just in case we throw an error
118
 
    # (most likely 404) to stop us seeing not logged in even when we are.
119
 
    if not req.publicmode:
120
 
        req.user = login.get_user_details(req)
121
 
 
122
 
    ### BEGIN New plugins framework ###
123
 
    # XXX This should be done ONCE per Python process, not per request.
124
 
    # (Wait till WSGI)
125
 
    # XXX No authentication is done here
126
 
    req.mapper = get_routes_mapper()
127
 
    matchdict = req.mapper.match(req.uri)
128
 
    if matchdict is not None:
129
 
        viewcls = matchdict['view']
130
 
        # Get the remaining arguments, less 'view', 'action' and 'controller'
131
 
        # (The latter two seem to be built-in, and we don't want them).
132
 
        kwargs = matchdict.copy()
133
 
        del kwargs['view']
134
 
        # Instantiate the view, which should be a BaseView class
135
 
        view = viewcls(req, **kwargs)
136
 
        # Render the output
137
 
        view.render(req)
138
 
        req.store.commit()
139
 
        return req.OK
140
 
    ### END New plugins framework ###
141
 
 
142
 
    # Check req.app to see if it is valid. 404 if not.
143
 
    if req.app is not None and req.app not in ivle.conf.apps.app_url:
144
 
        req.throw_error(Request.HTTP_NOT_FOUND,
145
 
            "There is no application called %s." % repr(req.app))
146
 
 
147
 
    # Special handling for public mode - only allow the public app, call it
148
 
    # and get out.
149
 
    # NOTE: This will not behave correctly if the public app uses
150
 
    # write_html_head_foot, but "serve" does not.
151
 
    if req.publicmode:
152
 
        if req.app != ivle.conf.apps.public_app:
153
 
            req.throw_error(Request.HTTP_FORBIDDEN,
154
 
                "This application is not available on the public site.")
155
 
        app = ivle.conf.apps.app_url[ivle.conf.apps.public_app]
156
 
        apps.call_app(app.dir, req)
157
 
        return req.OK
158
 
 
159
 
    # app is the App object for the chosen app
160
 
    if req.app is None:
161
 
        app = ivle.conf.apps.app_url[ivle.conf.apps.default_app]
162
 
    else:
163
 
        app = ivle.conf.apps.app_url[req.app]
164
 
 
165
 
    # Check if app requires auth. If so, perform authentication and login.
166
 
    # This will either return a User object, None, or perform a redirect
167
 
    # which we will not catch here.
168
 
    if app.requireauth:
169
 
        req.user = login.login(req)
170
 
        logged_in = req.user is not None
171
 
    else:
172
 
        req.user = login.get_user_details(req)
173
 
        logged_in = True
174
 
 
175
 
    if logged_in:
176
 
        # Keep the user's session alive by writing to the session object.
177
 
        # req.get_session().save()
178
 
        # Well, it's a fine idea, but it creates considerable grief in the
179
 
        # concurrent update department, so instead, we'll just make the
180
 
        # sessions not time out.
181
 
        req.get_session().unlock()
182
 
 
183
 
        # If user did not specify an app, HTTP redirect to default app and
184
 
        # exit.
185
 
        if req.app is None:
186
 
            req.throw_redirect(util.make_path(ivle.conf.apps.default_app))
187
 
 
188
 
        # Set the default title to the app's tab name, if any. Otherwise URL
189
 
        # name.
190
 
        if app.name is not None:
191
 
            req.title = app.name
192
 
        else:
193
 
            req.title = req.app
194
 
 
195
 
        # Call the specified app with the request object
196
 
        apps.call_app(app.dir, req)
197
 
 
198
 
    # if not logged in, login.login will have written the login box.
199
 
    # Just clean up and exit.
200
 
 
201
 
    # MAKE SURE we write the HTTP (and possibly HTML) header. This
202
 
    # wouldn't happen if nothing else ever got written, so we have to make
203
 
    # sure.
204
 
    req.ensure_headers_written()
205
 
 
206
 
    # When done, write out the HTML footer if the app has requested it
207
 
    if req.write_html_head_foot:
208
 
        # Show the console if required
209
 
        if logged_in and app.useconsole:
210
 
            plugins.console.present(req, windowpane=True)
211
 
        html.write_html_foot(req)
212
 
 
213
 
    # Note: Apache will not write custom HTML error messages here.
214
 
    # Use req.throw_error to do that.
215
 
    return req.OK
 
124
    @param apachereq: An Apache request object.
 
125
    """
 
126
    # Make the request object into an IVLE request which can be given to views
 
127
    req = Request(apachereq, config)
 
128
 
 
129
    req.publisher = generate_publisher(
 
130
        config.plugin_index[ViewPlugin], ApplicationRoot(req),
 
131
        publicmode=req.publicmode)
 
132
 
 
133
    try:
 
134
        obj, viewcls, subpath = req.publisher.resolve(req.uri.decode('utf-8'))
 
135
        try:
 
136
            # We 404 if we have a subpath but the view forbids it.
 
137
            if not viewcls.subpath_allowed and subpath:
 
138
                raise NotFound()
 
139
 
 
140
            # Instantiate the view, which should be a BaseView class
 
141
            view = viewcls(req, obj, subpath)
 
142
 
 
143
            # Check that the request (mainly the user) is permitted to access
 
144
            # the view.
 
145
            if not view.authorize(req):
 
146
                # Indicate the forbidden object if this is an admin.
 
147
                if req.user and req.user.admin:
 
148
                    raise Unauthorized('Unauthorized: %s' % view)
 
149
                else:
 
150
                    raise Unauthorized()
 
151
 
 
152
            # Non-GET requests from other sites leave us vulnerable to
 
153
            # CSRFs. Block them.
 
154
            referer = req.headers_in.get('Referer')
 
155
            if (referer is None or
 
156
                urlparse.urlparse(req.headers_in.get('Referer')).netloc !=
 
157
                    req.hostname):
 
158
                if req.method != 'GET' and not view.offsite_posts_allowed:
 
159
                    raise BadRequest(
 
160
                        "Non-GET requests from external sites are forbidden "
 
161
                        "for security reasons.")
 
162
 
 
163
            # Render the output
 
164
            view.render(req)
 
165
        except HTTPError, e:
 
166
            # A view explicitly raised an HTTP error. Respect it.
 
167
            req.status = e.code
 
168
 
 
169
            # Try to find a custom error view.
 
170
            if hasattr(viewcls, 'get_error_view'):
 
171
                errviewcls = viewcls.get_error_view(e)
 
172
            else:
 
173
                errviewcls = XHTMLView.get_error_view(e)
 
174
 
 
175
            if errviewcls:
 
176
                errview = errviewcls(req, e, obj)
 
177
                errview.render(req)
 
178
                return req.OK
 
179
            elif e.message:
 
180
                req.write(e.message)
 
181
                return req.OK
 
182
            else:
 
183
                return e.code
 
184
        except mod_python.apache.SERVER_RETURN:
 
185
            # A mod_python-specific Apache error.
 
186
            # XXX: We need to raise these because req.throw_error() uses them.
 
187
            # Remove this after Google Code issue 117 is fixed.
 
188
            raise
 
189
        except Exception, e:
 
190
            # A non-HTTPError appeared. We have an unknown exception. Panic.
 
191
            handle_unknown_exception(req, *sys.exc_info())
 
192
            return req.OK
 
193
        else:
 
194
            # Commit the transaction if we have a store open.
 
195
            req.commit()
 
196
            return req.OK
 
197
    except Unauthorized, e:
 
198
        # Resolution failed due to a permission check. Display a pretty
 
199
        # error, or maybe a login page.
 
200
        XHTMLView.get_error_view(e)(req, e, req.publisher.root).render(req)
 
201
        return req.OK
 
202
    except PublishingError, e:
 
203
        req.status = 404
 
204
 
 
205
        if req.user and req.user.admin:
 
206
            XHTMLErrorView(req, NotFound('Not found: ' +
 
207
                                         str(e.args)), e[0]).render(req)
 
208
        else:
 
209
            XHTMLErrorView(req, NotFound(), e[0]).render(req)
 
210
 
 
211
        return req.OK
 
212
    finally:
 
213
        # Make sure we close the store.
 
214
        req.cleanup()
216
215
 
217
216
def handle_unknown_exception(req, exc_type, exc_value, exc_traceback):
218
217
    """
221
220
    This is a full handler. It assumes nothing has been written, and writes a
222
221
    complete HTML page.
223
222
    req: May be EITHER an IVLE req or an Apache req.
224
 
    IVLE reqs may have the HTML head/foot written (on a 400 error), but
225
 
    the handler code may pass an apache req if an exception occurs before
 
223
    The handler code may pass an apache req if an exception occurs before
226
224
    the IVLE request is created.
227
225
    """
228
226
    req.content_type = "text/html"
229
 
    logfile = os.path.join(ivle.conf.log_path, 'ivle_error.log')
 
227
    logfile = os.path.join(config['paths']['logs'], 'ivle_error.log')
230
228
    logfail = False
231
 
    # For some reason, some versions of mod_python have "_server" instead of
232
 
    # "main_server". So we check for both.
233
 
    try:
234
 
        admin_email = mod_python.apache.main_server.server_admin
235
 
    except AttributeError:
236
 
        try:
237
 
            admin_email = mod_python.apache._server.server_admin
238
 
        except AttributeError:
239
 
            admin_email = ""
240
 
    try:
241
 
        httpcode = exc_value.httpcode
242
 
        req.status = httpcode
243
 
    except AttributeError:
244
 
        httpcode = None
245
 
        req.status = mod_python.apache.HTTP_INTERNAL_SERVER_ERROR
 
229
 
 
230
    req.status = mod_python.apache.HTTP_INTERNAL_SERVER_ERROR
 
231
 
246
232
    try:
247
233
        publicmode = req.publicmode
248
234
    except AttributeError:
251
237
        login = req.user.login
252
238
    except AttributeError:
253
239
        login = None
254
 
    try:
255
 
        role = req.user.role
256
 
    except AttributeError:
257
 
        role = None
258
240
 
259
241
    # Log File
260
242
    try:
270
252
            filemode='a')
271
253
    except IOError:
272
254
        logfail = True
273
 
    logging.debug('Logging Unhandled Exception')
274
 
 
275
 
    # We handle 3 types of error.
276
 
    # IVLEErrors with 4xx response codes (client error).
277
 
    # IVLEErrors with 5xx response codes (handled server error).
278
 
    # Other exceptions (unhandled server error).
279
 
    # IVLEErrors should not have other response codes than 4xx or 5xx
280
 
    # (eg. throw_redirect should have been used for 3xx codes).
281
 
    # Therefore, that is treated as an unhandled error.
282
 
 
283
 
    if (exc_type == util.IVLEError and httpcode >= 400
284
 
        and httpcode <= 499):
285
 
        # IVLEErrors with 4xx response codes are client errors.
286
 
        # Therefore, these have a "nice" response (we even coat it in the IVLE
287
 
        # HTML wrappers).
288
 
        
289
 
        req.write_html_head_foot = True
290
 
        req.write_javascript_settings = False
291
 
        req.write('<div id="ivle_padding">\n')
292
 
        try:
293
 
            codename, msg = req.get_http_codename(httpcode)
294
 
        except AttributeError:
295
 
            codename, msg = None, None
296
 
        # Override the default message with the supplied one,
297
 
        # if available.
298
 
        if exc_value.message is not None:
299
 
            msg = exc_value.message
300
 
        if codename is not None:
301
 
            req.write("<h1>Error: %s</h1>\n" % cgi.escape(codename))
302
 
        else:
303
 
            req.write("<h1>Error</h1>\n")
304
 
        if msg is not None:
305
 
            req.write("<p>%s</p>\n" % cgi.escape(msg))
306
 
        else:
307
 
            req.write("<p>An unknown error occured.</p>\n")
308
 
        
309
 
        # Logging
310
 
        logging.info(str(msg))
311
 
        
312
 
        req.write("<p>(HTTP error code %d)</p>\n" % httpcode)
313
 
        if logfail:
314
 
            req.write("<p>Warning: Could not open Error Log: '%s'</p>\n"
315
 
                %cgi.escape(logfile))
316
 
        req.write('</div>\n')
317
 
        html.write_html_foot(req)
 
255
 
 
256
    # A "bad" error message. We shouldn't get here unless IVLE
 
257
    # misbehaves (which is currently very easy, if things aren't set up
 
258
    # correctly).
 
259
    # Write the traceback.
 
260
 
 
261
    # We need to special-case IVLEJailError, as we can get another
 
262
    # almost-exception out of it.
 
263
    if exc_type is util.IVLEJailError:
 
264
        tb = 'Exception information extracted from IVLEJailError:\n'
 
265
        tb += urllib.unquote(exc_value.info)
318
266
    else:
319
 
        # A "bad" error message. We shouldn't get here unless IVLE
320
 
        # misbehaves (which is currently very easy, if things aren't set up
321
 
        # correctly).
322
 
        # Write the traceback.
323
 
        # If this is a non-4xx IVLEError, get the message and httpcode and
324
 
        # make the error message a bit nicer (but still include the
325
 
        # traceback).
326
 
        # We also need to special-case IVLEJailError, as we can get another
327
 
        # almost-exception out of it.
328
 
 
329
 
        codename, msg = None, None
330
 
 
331
 
        if exc_type is util.IVLEJailError:
332
 
            msg = exc_value.type_str + ": " + exc_value.message
333
 
            tb = 'Exception information extracted from IVLEJailError:\n'
334
 
            tb += urllib.unquote(exc_value.info)
335
 
        else:
336
 
            try:
337
 
                codename, msg = req.get_http_codename(httpcode)
338
 
            except AttributeError:
339
 
                pass
340
 
            # Override the default message with the supplied one,
341
 
            # if available.
342
 
            if hasattr(exc_value, 'message') and exc_value.message is not None:
343
 
                msg = exc_value.message
344
 
                # Prepend the exception type
345
 
                if exc_type != util.IVLEError:
346
 
                    msg = exc_type.__name__ + ": " + msg
347
 
 
348
 
            tb = ''.join(traceback.format_exception(exc_type, exc_value,
349
 
                                                    exc_traceback))
350
 
 
351
 
        # Logging
352
 
        logging.error('%s\n%s'%(str(msg), tb))
353
 
        # Error messages are only displayed is the user is NOT a student,
354
 
        # or if there has been a problem logging the error message
355
 
        show_errors = (not publicmode) and ((login and \
356
 
                            str(role) != "student") or logfail)
357
 
        req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"                 
 
267
        tb = ''.join(traceback.format_exception(exc_type, exc_value,
 
268
                                                exc_traceback))
 
269
 
 
270
    logging.error('\n' + tb)
 
271
 
 
272
    # Error messages are only displayed is the user is NOT a student,
 
273
    # or if there has been a problem logging the error message
 
274
    show_errors = (not publicmode) and ((login and req.user.admin) or logfail)
 
275
    req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"                 
358
276
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">                                      
359
277
<html xmlns="http://www.w3.org/1999/xhtml">
360
278
<head><title>IVLE Internal Server Error</title></head>
361
279
<body>
362
 
<h1>IVLE Internal Server Error""")
363
 
        if (show_errors):
364
 
            if (codename is not None
365
 
                        and httpcode != mod_python.apache.HTTP_INTERNAL_SERVER_ERROR):
366
 
                req.write(": %s" % cgi.escape(codename))
367
 
        
368
 
        req.write("""</h1>
 
280
<h1>IVLE Internal Server Error</h1>
369
281
<p>An error has occured which is the fault of the IVLE developers or
370
 
administration. The developers have been notified.</p>
371
 
""")
372
 
        if (show_errors):
373
 
            if msg is not None:
374
 
                req.write("<p>%s</p>\n" % cgi.escape(msg))
375
 
            if httpcode is not None:
376
 
                req.write("<p>(HTTP error code %d)</p>\n" % httpcode)
377
 
            req.write("""
378
 
    <p>Please report this to <a href="mailto:%s">%s</a> (the system
379
 
    administrator). Include the following information:</p>
380
 
    """ % (cgi.escape(admin_email), cgi.escape(admin_email)))
381
 
 
382
 
            req.write("<pre>\n%s\n</pre>\n"%cgi.escape(tb))
383
 
            if logfail:
384
 
                req.write("<p>Warning: Could not open Error Log: '%s'</p>\n"
385
 
                    %cgi.escape(logfile))
386
 
        req.write("</body></html>")
 
282
administrators. """)
 
283
 
 
284
    if logfail:
 
285
        req.write("Please report this issue to the server administrators, "
 
286
                  "along with the following information.")
 
287
    else:
 
288
        req.write("Details have been logged for further examination.")
 
289
    req.write("</p>")
 
290
 
 
291
    if show_errors:
 
292
        req.write("<h2>Debugging information</h2>")
 
293
        req.write("<pre>\n%s\n</pre>\n"%cgi.escape(tb))
 
294
    req.write("</body></html>")