1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2009 The University of Melbourne
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.
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.
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
23
Builds an IVLE request object from a mod_python request object.
24
See design notes/apps/dispatch.txt for a full specification of this request
29
import mod_python.Session
30
import mod_python.Cookie
31
import mod_python.util
32
import mod_python.apache
34
# This needs to be importable from outside Apache.
41
from ivle.webapp.base.plugins import CookiePlugin
42
import ivle.webapp.security
45
class PotentiallySecureFileSession(mod_python.Session.FileSession):
46
"""A mod_python FileSession that sets secure cookie when appropriate.
48
A secure cookie will be set if the request itself is over HTTPS, or if
49
a proxy in front has set X-Forwarded-Proto: https. Otherwise the cookie
52
def make_cookie(self):
53
cookie = super(PotentiallySecureFileSession, self).make_cookie()
54
if (self._req.is_https() or
55
self._req.headers_in.get('X-Forwarded-Proto') == 'https'):
61
"""An IVLE request object. This is presented to the IVLE apps as a way of
62
interacting with the web server and the dispatcher.
64
Request object attributes:
66
String. The request method (eg. 'GET', 'POST', etc)
68
String. The path portion of the URI.
70
String. Name of the application specified in the URL, or None.
72
String. The path specified in the URL *not including* the
73
application or the IVLE location prefix. eg. a URL of
74
"/ivle/files/joe/myfiles" has a path of "joe/myfiles".
76
User object. Details of the user who is currently logged in, or
79
storm.store.Store instance. Holds a database transaction open,
80
which is available for the entire lifetime of the request.
82
String. Hostname the server is running on.
84
Table object representing headers sent by the client.
85
headers_out (read, can be written to)
86
Table object representing headers to be sent to the client.
88
Bool. True if the request came for the "public host" as
89
configured in conf.py. Note that public mode requests do not
90
have an app (app is set to None).
93
Int. Response status number. Use one of the status codes defined
96
String. The Content-Type (mime type) header value.
98
String. Response "Location" header value. Used with HTTP redirect
102
# Special code for an OK response.
103
# Do not use HTTP_OK; for some reason Apache produces an "OK" error
104
# message if you do that.
110
HTTP_MOVED_TEMPORARILY = 302
113
HTTP_INTERNAL_SERVER_ERROR = 500
117
def __init__(self, req, config):
118
"""Create an IVLE request from a mod_python one.
120
@param req: A mod_python request.
121
@param config: An IVLE configuration.
124
# Methods are mostly wrappers around the Apache request object
125
self.apache_req = req
127
self.headers_written = False
129
# Determine if the browser used the public host name to make the
130
# request (in which case we are in "public mode")
131
if req.hostname == config['urls']['public_host']:
132
self.publicmode = True
134
self.publicmode = False
136
# Inherit values for the input members
137
self.method = req.method
139
# Split the given path into the app (top-level dir) and sub-path
140
# (after first stripping away the root directory)
141
(self.app, self.path) = (ivle.util.split_path(req.uri))
142
self.hostname = req.hostname
143
self.headers_in = req.headers_in
144
self.headers_out = req.headers_out
146
# Default values for the output members
147
self.status = Request.HTTP_OK
148
self.content_type = None # Use Apache's default
150
# In some cases we don't want the template JS (such as the username
151
# and public FQDN) in the output HTML. In that case, set this to 0.
152
self.write_javascript_settings = True
153
self.got_common_vars = False
160
if self._store is not None:
166
if self._store is not None:
169
def __writeheaders(self):
170
"""Writes out the HTTP and HTML headers before any real data is
172
self.headers_written = True
174
# Prepare the HTTP and HTML headers before the first write is made
175
if self.content_type != None:
176
self.apache_req.content_type = self.content_type
177
self.apache_req.status = self.status
178
if self.location != None:
179
self.apache_req.headers_out['Location'] = self.location
181
def ensure_headers_written(self):
182
"""Writes out the HTTP and HTML headers if they haven't already been
184
if not self.headers_written:
185
self.__writeheaders()
187
def write(self, string, flush=1):
188
"""Writes string directly to the client, then flushes the buffer,
189
unless flush is 0."""
191
if not self.headers_written:
192
self.__writeheaders()
193
if isinstance(string, unicode):
194
# Encode unicode strings as UTF-8
195
# (Otherwise cannot handle being written to a bytestream)
196
self.apache_req.write(string.encode('utf8'), flush)
198
# 8-bit clean strings just get written directly.
199
# This includes binary strings.
200
self.apache_req.write(string, flush)
203
"""Log out the current user by destroying the session state.
204
Then redirect to the top-level IVLE page."""
205
if hasattr(self, 'session'):
206
self.session.invalidate()
207
self.session.delete()
208
# Invalidates all IVLE cookies
209
all_cookies = mod_python.Cookie.get_cookies(self)
211
# Create cookies for plugins that might request them.
212
for plugin in self.config.plugin_index[CookiePlugin]:
213
for cookie in plugin.cookies:
214
self.add_cookie(mod_python.Cookie.Cookie(cookie, '',
215
expires=1, path='/'))
216
self.throw_redirect(self.make_path(''))
220
"""Flushes the output buffer."""
221
self.apache_req.flush()
223
def sendfile(self, filename):
224
"""Sends the named file directly to the client."""
225
if not self.headers_written:
226
self.__writeheaders()
227
self.apache_req.sendfile(filename)
229
def read(self, len=None):
230
"""Reads at most len bytes directly from the client. (See mod_python
233
return self.apache_req.read()
235
return self.apache_req.read(len)
237
def throw_redirect(self, location):
238
"""Writes out an HTTP redirect to the specified URL. Raises an
239
exception which is caught by the dispatch or web server, so any
240
code following this call will not be executed.
242
httpcode: An HTTP response status code. Pass a constant from the
245
# Note: location may be a unicode, but it MUST only have ASCII
246
# characters (non-ascii characters should be URL-encoded).
247
mod_python.util.redirect(self.apache_req, location.encode("ascii"))
249
def add_cookie(self, cookie, value=None, **attributes):
250
"""Inserts a cookie into this request object's headers."""
252
mod_python.Cookie.add_cookie(self.apache_req, cookie)
254
mod_python.Cookie.add_cookie(self.apache_req, cookie, value, **attributes)
256
def make_path(self, path):
257
"""Prepend the IVLE URL prefix to the given path.
259
This is used when generating URLs to send to the client.
261
This method is DEPRECATED. We no longer support use of a prefix.
263
return os.path.join(self.config['urls']['root'], path)
265
def get_session(self):
266
"""Returns a mod_python Session object for this request.
267
Note that this is dependent on mod_python and may need to change
268
interface if porting away from mod_python.
270
IMPORTANT: Call unlock() on the session as soon as you are done with
271
it! If you don't, all other requests will block!
273
# Cache the session object and set the timeout to 24 hours.
274
if not hasattr(self, 'session'):
275
self.session = PotentiallySecureFileSession(
276
self.apache_req, timeout = 60 * 60 * 24)
279
def get_fieldstorage(self):
280
"""Returns a mod_python FieldStorage object for this request.
281
Note that this is dependent on mod_python and may need to change
282
interface if porting away from mod_python."""
283
# Cache the fieldstorage object
284
if not hasattr(self, 'fields'):
285
self.fields = mod_python.util.FieldStorage(self.apache_req)
288
def get_cgi_environ(self):
289
"""Returns the CGI environment emulation for this request. (Calls
290
add_common_vars). The environment is returned as a mapping
291
compatible with os.environ."""
292
if not self.got_common_vars:
293
self.apache_req.add_common_vars()
294
self.got_common_vars = True
295
return self.apache_req.subprocess_env
299
# Open a database connection and transaction, keep it around for users
300
# of the Request object to use.
301
if self._store is None:
302
self._store = ivle.database.get_store(self.config)
307
# Get and cache the request user, or None if it's not valid.
308
# This is a property so that we don't create a store unless
309
# some code actually requests the user.
312
except AttributeError:
316
temp_user = ivle.webapp.security.get_user_details(self)
317
if temp_user and temp_user.valid:
318
self._user = temp_user