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

« back to all changes in this revision

Viewing changes to www/dispatch/__init__.py

  • Committer: mattgiuca
  • Date: 2008-02-24 22:09:16 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:553
Added new app: Settings (UI for userservice).
    (Added app dir, media dir with empty JS file, icon).
apps/__init__.py: Added error message.
dispatch/__init__.py: Added error message.
dispatch/html.py: Added link to Settings at the top
    (a special app).
    Fixed HTML icons (correct size link).
    Catch keyerror on icon which would otherwise be thrown all
    the way up on certain errors.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE
 
2
# Copyright (C) 2007-2008 The University of Melbourne
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
17
 
 
18
# Module: dispatch
 
19
# Author: Matt Giuca
 
20
# Date: 11/12/2007
 
21
 
 
22
# This is a mod_python handler program. The correct way to call it is to have
 
23
# Apache send all requests to be handled by the module 'dispatch'.
 
24
 
 
25
# Top-level handler. Handles all requests to all pages in IVLE.
 
26
# Handles authentication (not authorization).
 
27
# Then passes the request along to the appropriate ivle app.
 
28
 
 
29
import mod_python
 
30
from mod_python import apache
 
31
 
 
32
import sys
 
33
import os
 
34
import os.path
 
35
import conf
 
36
import conf.apps
 
37
import apps
 
38
 
 
39
from request import Request
 
40
import html
 
41
import login
 
42
from common import (util, forumutil)
 
43
import traceback
 
44
import cStringIO
 
45
 
 
46
def handler(req):
 
47
    """Handles a request which may be to anywhere in the site except media.
 
48
    Intended to be called by mod_python, as a handler.
 
49
 
 
50
    req: An Apache request object.
 
51
    """
 
52
    # Make the request object into an IVLE request which can be passed to apps
 
53
    apachereq = req
 
54
    try:
 
55
        req = Request(req, html.write_html_head)
 
56
    except Exception:
 
57
        # Pass the apachereq to error reporter, since ivle req isn't created
 
58
        # yet.
 
59
        handle_unknown_exception(apachereq, *sys.exc_info())
 
60
        # Tell Apache not to generate its own errors as well
 
61
        return apache.OK
 
62
 
 
63
    # Run the main handler, and catch all exceptions
 
64
    try:
 
65
        return handler_(req, apachereq)
 
66
    except mod_python.apache.SERVER_RETURN:
 
67
        # An apache error. We discourage these, but they might still happen.
 
68
        # Just raise up.
 
69
        raise
 
70
    except Exception:
 
71
        handle_unknown_exception(req, *sys.exc_info())
 
72
        # Tell Apache not to generate its own errors as well
 
73
        return apache.OK
 
74
 
 
75
def handler_(req, apachereq):
 
76
    """
 
77
    Nested handler function. May raise exceptions. The top-level handler is
 
78
    just used to catch exceptions.
 
79
    Takes both an IVLE request and an Apache req.
 
80
    """
 
81
    # Check req.app to see if it is valid. 404 if not.
 
82
    if req.app is not None and req.app not in conf.apps.app_url:
 
83
        # Maybe it is a special app!
 
84
        if req.app == 'logout':
 
85
            logout(req)
 
86
        else:
 
87
            req.throw_error(Request.HTTP_NOT_FOUND,
 
88
                "There is no application called %s." % repr(req.app))
 
89
 
 
90
    # Special handling for public mode - just call public app and get out
 
91
    # NOTE: This will not behave correctly if the public app uses
 
92
    # write_html_head_foot, but "serve" does not.
 
93
    if req.publicmode:
 
94
        app = conf.apps.app_url[conf.apps.public_app]
 
95
        apps.call_app(app.dir, req)
 
96
        return req.OK
 
97
 
 
98
    # app is the App object for the chosen app
 
99
    if req.app is None:
 
100
        app = conf.apps.app_url[conf.apps.default_app]
 
101
    else:
 
102
        app = conf.apps.app_url[req.app]
 
103
 
 
104
    # Check if app requires auth. If so, perform authentication and login.
 
105
    # This will either return a User object, None, or perform a redirect
 
106
    # which we will not catch here.
 
107
    if app.requireauth:
 
108
        req.user = login.login(req)
 
109
        logged_in = req.user is not None
 
110
    else:
 
111
        req.user = login.get_user_details(req)
 
112
        logged_in = True
 
113
 
 
114
    if logged_in:
 
115
        # Keep the user's session alive by writing to the session object.
 
116
        # req.get_session().save()
 
117
        # Well, it's a fine idea, but it creates considerable grief in the
 
118
        # concurrent update department, so instead, we'll just make the
 
119
        # sessions not time out.
 
120
        
 
121
        # If user did not specify an app, HTTP redirect to default app and
 
122
        # exit.
 
123
        if req.app is None:
 
124
            req.throw_redirect(util.make_path(conf.apps.default_app))
 
125
 
 
126
        # Set the default title to the app's tab name, if any. Otherwise URL
 
127
        # name.
 
128
        if app.name is not None:
 
129
            req.title = app.name
 
130
        else:
 
131
            req.title = req.app
 
132
 
 
133
        # Call the specified app with the request object
 
134
        apps.call_app(app.dir, req)
 
135
 
 
136
    # if not logged in, login.login will have written the login box.
 
137
    # Just clean up and exit.
 
138
 
 
139
    # MAKE SURE we write the HTTP (and possibly HTML) header. This
 
140
    # wouldn't happen if nothing else ever got written, so we have to make
 
141
    # sure.
 
142
    req.ensure_headers_written()
 
143
 
 
144
    # When done, write out the HTML footer if the app has requested it
 
145
    if req.write_html_head_foot:
 
146
        html.write_html_foot(req)
 
147
 
 
148
    # Note: Apache will not write custom HTML error messages here.
 
149
    # Use req.throw_error to do that.
 
150
    return req.OK
 
151
 
 
152
def logout(req):
 
153
    """Log out the current user (if any) by destroying the session state.
 
154
    Then redirect to the top-level IVLE page."""
 
155
    session = req.get_session()
 
156
    session.invalidate()
 
157
    session.delete()
 
158
    req.add_cookie(forumutil.invalidated_forum_cookie())
 
159
    req.throw_redirect(util.make_path(''))
 
160
 
 
161
def handle_unknown_exception(req, exc_type, exc_value, exc_traceback):
 
162
    """
 
163
    Given an exception that has just been thrown from IVLE, print its details
 
164
    to the request.
 
165
    This is a full handler. It assumes nothing has been written, and writes a
 
166
    complete HTML page.
 
167
    req: May be EITHER an IVLE req or an Apache req.
 
168
    IVLE reqs may have the HTML head/foot written (on a 400 error), but
 
169
    the handler code may pass an apache req if an exception occurs before
 
170
    the IVLE request is created.
 
171
    """
 
172
    req.content_type = "text/html"
 
173
    admin_email = apache._server.server_admin
 
174
    try:
 
175
        httpcode = exc_value.httpcode
 
176
        req.status = httpcode
 
177
    except AttributeError:
 
178
        httpcode = None
 
179
        req.status = apache.HTTP_INTERNAL_SERVER_ERROR
 
180
    # We handle 3 types of error.
 
181
    # IVLEErrors with 4xx response codes (client error).
 
182
    # IVLEErrors with 5xx response codes (handled server error).
 
183
    # Other exceptions (unhandled server error).
 
184
    # IVLEErrors should not have other response codes than 4xx or 5xx
 
185
    # (eg. throw_redirect should have been used for 3xx codes).
 
186
    # Therefore, that is treated as an unhandled error.
 
187
 
 
188
    if (exc_type == util.IVLEError and httpcode >= 400
 
189
        and httpcode <= 499):
 
190
        # IVLEErrors with 4xx response codes are client errors.
 
191
        # Therefore, these have a "nice" response (we even coat it in the IVLE
 
192
        # HTML wrappers).
 
193
        req.write_html_head_foot = True
 
194
        req.write('<div id="ivle_padding">\n')
 
195
        try:
 
196
            codename, msg = req.get_http_codename(httpcode)
 
197
        except AttributeError:
 
198
            codename, msg = None, None
 
199
        # Override the default message with the supplied one,
 
200
        # if available.
 
201
        if exc_value.message is not None:
 
202
            msg = exc_value.message
 
203
        if codename is not None:
 
204
            req.write("<h1>Error: %s</h1>\n" % codename)
 
205
        else:
 
206
            req.write("<h1>Error</h1>\n")
 
207
        if msg is not None:
 
208
            req.write("<p>%s</p>\n" % msg)
 
209
        else:
 
210
            req.write("<p>An unknown error occured.</p>\n")
 
211
        req.write("<p>(HTTP error code %d)</p>\n" % httpcode)
 
212
        req.write('</div>\n')
 
213
    else:
 
214
        # A "bad" error message. We shouldn't get here unless IVLE
 
215
        # misbehaves (which is currently very easy, if things aren't set up
 
216
        # correctly).
 
217
        # Write the traceback.
 
218
        # If this is a non-4xx IVLEError, get the message and httpcode and
 
219
        # make the error message a bit nicer (but still include the
 
220
        # traceback).
 
221
        try:
 
222
            codename, msg = req.get_http_codename(httpcode)
 
223
        except AttributeError:
 
224
            codename, msg = None, None
 
225
        # Override the default message with the supplied one,
 
226
        # if available.
 
227
        if hasattr(exc_value, 'message') and exc_value.message is not None:
 
228
            msg = exc_value.message
 
229
 
 
230
        req.write("""<html>
 
231
<head><title>IVLE Internal Server Error</title></head>
 
232
<body>
 
233
<h1>IVLE Internal Server Error""")
 
234
        if (codename is not None
 
235
            and httpcode != apache.HTTP_INTERNAL_SERVER_ERROR):
 
236
            req.write(": %s" % codename)
 
237
        req.write("""</h1>
 
238
<p>An error has occured which is the fault of the IVLE developers or
 
239
administration.</p>
 
240
""")
 
241
        if msg is not None:
 
242
            req.write("<p>%s</p>\n" % msg)
 
243
        if httpcode is not None:
 
244
            req.write("<p>(HTTP error code %d)</p>\n" % httpcode)
 
245
        req.write("""
 
246
<p>Please report this to <a href="mailto:%s">%s</a> (the system
 
247
administrator). Include the following information:</p>
 
248
""" % (admin_email, admin_email))
 
249
 
 
250
        tb_print = cStringIO.StringIO()
 
251
        traceback.print_exception(exc_type, exc_value, exc_traceback,
 
252
            file=tb_print)
 
253
        req.write("<pre>\n")
 
254
        req.write(tb_print.getvalue())
 
255
        req.write("</pre>\n</body>\n")