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

« back to all changes in this revision

Viewing changes to ivle/dispatch/request.py

  • Committer: mattgiuca
  • Date: 2008-01-12 12:57:30 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:197
dispatch.html, ivle.css: Main IVLE header is now an h1/h2 pair, styled to the
    left with absolute positioning (one over the top of the other).

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# IVLE - Informatics Virtual Learning Environment
2
 
# Copyright (C) 2007-2009 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
 
# Author: Matt Giuca
19
 
 
20
 
"""
21
 
IVLE Request Object
22
 
 
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
25
 
object.
26
 
"""
27
 
 
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
52
 
 
53
 
import ivle.util
54
 
import ivle.database
55
 
from ivle.webapp.base.plugins import CookiePlugin
56
 
import ivle.webapp.security
57
 
 
58
 
 
59
 
class Request:
60
 
    """An IVLE request object. This is presented to the IVLE apps as a way of
61
 
    interacting with the web server and the dispatcher.
62
 
 
63
 
    Request object attributes:
64
 
        method (read)
65
 
            String. The request method (eg. 'GET', 'POST', etc)
66
 
        uri (read)
67
 
            String. The path portion of the URI.
68
 
        app (read)
69
 
            String. Name of the application specified in the URL, or None.
70
 
        path (read)
71
 
            String. The path specified in the URL *not including* the
72
 
            application or the IVLE location prefix. eg. a URL of
73
 
            "/ivle/files/joe/myfiles" has a path of "joe/myfiles".
74
 
        user (read)
75
 
            User object. Details of the user who is currently logged in, or
76
 
            None.
77
 
        store (read)
78
 
            storm.store.Store instance. Holds a database transaction open,
79
 
            which is available for the entire lifetime of the request.
80
 
        hostname (read)
81
 
            String. Hostname the server is running on.
82
 
        headers_in (read)
83
 
            Table object representing headers sent by the client.
84
 
        headers_out (read, can be written to)
85
 
            Table object representing headers to be sent to the client.
86
 
        publicmode (read)
87
 
            Bool. True if the request came for the "public host" as
88
 
            configured in conf.py. Note that public mode requests do not
89
 
            have an app (app is set to None).
90
 
 
91
 
        status (write)
92
 
            Int. Response status number. Use one of the status codes defined
93
 
            in class Request.
94
 
        content_type (write)
95
 
            String. The Content-Type (mime type) header value.
96
 
        location (write)
97
 
            String. Response "Location" header value. Used with HTTP redirect
98
 
            responses.
99
 
    """
100
 
 
101
 
    # Special code for an OK response.
102
 
    # Do not use HTTP_OK; for some reason Apache produces an "OK" error
103
 
    # message if you do that.
104
 
    OK  = 0
105
 
 
106
 
    # HTTP status codes
107
 
 
108
 
    HTTP_OK                           = 200
109
 
    HTTP_MOVED_TEMPORARILY            = 302
110
 
    HTTP_FORBIDDEN                    = 403
111
 
    HTTP_NOT_FOUND                    = 404
112
 
    HTTP_INTERNAL_SERVER_ERROR        = 500
113
 
 
114
 
    _store = None
115
 
 
116
 
    def __init__(self, req, config):
117
 
        """Create an IVLE request from a mod_python one.
118
 
 
119
 
        @param req: A mod_python request.
120
 
        @param config: An IVLE configuration.
121
 
        """
122
 
 
123
 
        # Methods are mostly wrappers around the Apache request object
124
 
        self.apache_req = req
125
 
        self.config = config
126
 
        self.headers_written = False
127
 
 
128
 
        # Determine if the browser used the public host name to make the
129
 
        # request (in which case we are in "public mode")
130
 
        if req.hostname == config['urls']['public_host']:
131
 
            self.publicmode = True
132
 
        else:
133
 
            self.publicmode = False
134
 
 
135
 
        # Inherit values for the input members
136
 
        self.method = req.method
137
 
        self.uri = req.uri
138
 
        # Split the given path into the app (top-level dir) and sub-path
139
 
        # (after first stripping away the root directory)
140
 
        (self.app, self.path) = (ivle.util.split_path(req.uri))
141
 
        self.hostname = req.hostname
142
 
        self.headers_in = req.headers_in
143
 
        self.headers_out = req.headers_out
144
 
 
145
 
        # Default values for the output members
146
 
        self.status = Request.HTTP_OK
147
 
        self.content_type = None        # Use Apache's default
148
 
        self.location = None
149
 
        # In some cases we don't want the template JS (such as the username
150
 
        # and public FQDN) in the output HTML. In that case, set this to 0.
151
 
        self.write_javascript_settings = True
152
 
        self.got_common_vars = False
153
 
 
154
 
    def __del__(self):
155
 
        self.cleanup()
156
 
 
157
 
    def cleanup(self):
158
 
        """Cleanup."""
159
 
        if self._store is not None:
160
 
            self._store.close()
161
 
            self._store = None
162
 
 
163
 
    def commit(self):
164
 
        """Cleanup."""
165
 
        if self._store is not None:
166
 
            self._store.commit()
167
 
 
168
 
    def __writeheaders(self):
169
 
        """Writes out the HTTP and HTML headers before any real data is
170
 
        written."""
171
 
        self.headers_written = True
172
 
 
173
 
        # Prepare the HTTP and HTML headers before the first write is made
174
 
        if self.content_type != None:
175
 
            self.apache_req.content_type = self.content_type
176
 
        self.apache_req.status = self.status
177
 
        if self.location != None:
178
 
            self.apache_req.headers_out['Location'] = self.location
179
 
 
180
 
    def ensure_headers_written(self):
181
 
        """Writes out the HTTP and HTML headers if they haven't already been
182
 
        written."""
183
 
        if not self.headers_written:
184
 
            self.__writeheaders()
185
 
 
186
 
    def write(self, string, flush=1):
187
 
        """Writes string directly to the client, then flushes the buffer,
188
 
        unless flush is 0."""
189
 
 
190
 
        if not self.headers_written:
191
 
            self.__writeheaders()
192
 
        if isinstance(string, unicode):
193
 
            # Encode unicode strings as UTF-8
194
 
            # (Otherwise cannot handle being written to a bytestream)
195
 
            self.apache_req.write(string.encode('utf8'), flush)
196
 
        else:
197
 
            # 8-bit clean strings just get written directly.
198
 
            # This includes binary strings.
199
 
            self.apache_req.write(string, flush)
200
 
 
201
 
    def logout(self):
202
 
        """Log out the current user by destroying the session state.
203
 
        Then redirect to the top-level IVLE page."""
204
 
        if hasattr(self, 'session'):
205
 
            self.session.invalidate()
206
 
            self.session.delete()
207
 
            # Invalidates all IVLE cookies
208
 
            all_cookies = mod_python.Cookie.get_cookies(self)
209
 
 
210
 
            # Create cookies for plugins that might request them.
211
 
            for plugin in self.config.plugin_index[CookiePlugin]:
212
 
                for cookie in plugin.cookies:
213
 
                    self.add_cookie(mod_python.Cookie.Cookie(cookie, '',
214
 
                                                    expires=1, path='/'))
215
 
        self.throw_redirect(self.make_path(''))
216
 
 
217
 
 
218
 
    def flush(self):
219
 
        """Flushes the output buffer."""
220
 
        self.apache_req.flush()
221
 
 
222
 
    def sendfile(self, filename):
223
 
        """Sends the named file directly to the client."""
224
 
        if not self.headers_written:
225
 
            self.__writeheaders()
226
 
        self.apache_req.sendfile(filename)
227
 
 
228
 
    def read(self, len=None):
229
 
        """Reads at most len bytes directly from the client. (See mod_python
230
 
        Request.read)."""
231
 
        if len is None:
232
 
            return self.apache_req.read()
233
 
        else:
234
 
            return self.apache_req.read(len)
235
 
 
236
 
    def throw_redirect(self, location):
237
 
        """Writes out an HTTP redirect to the specified URL. Raises an
238
 
        exception which is caught by the dispatch or web server, so any
239
 
        code following this call will not be executed.
240
 
 
241
 
        httpcode: An HTTP response status code. Pass a constant from the
242
 
        Request class.
243
 
        """
244
 
        # Note: location may be a unicode, but it MUST only have ASCII
245
 
        # characters (non-ascii characters should be URL-encoded).
246
 
        mod_python.util.redirect(self.apache_req, location.encode("ascii"))
247
 
 
248
 
    def add_cookie(self, cookie, value=None, **attributes):
249
 
        """Inserts a cookie into this request object's headers."""
250
 
        if value is None:
251
 
            mod_python.Cookie.add_cookie(self.apache_req, cookie)
252
 
        else:
253
 
            mod_python.Cookie.add_cookie(self.apache_req, cookie, value, **attributes)
254
 
 
255
 
    def make_path(self, path):
256
 
        """Prepend the IVLE URL prefix to the given path.
257
 
 
258
 
        This is used when generating URLs to send to the client.
259
 
 
260
 
        This method is DEPRECATED. We no longer support use of a prefix.
261
 
        """
262
 
        return os.path.join(self.config['urls']['root'], path)
263
 
 
264
 
    def get_session(self):
265
 
        """Returns a mod_python Session object for this request.
266
 
        Note that this is dependent on mod_python and may need to change
267
 
        interface if porting away from mod_python.
268
 
 
269
 
        IMPORTANT: Call unlock() on the session as soon as you are done with
270
 
                   it! If you don't, all other requests will block!
271
 
        """
272
 
        # Cache the session object and set the timeout to 24 hours.
273
 
        if not hasattr(self, 'session'):
274
 
            self.session = PotentiallySecureFileSession(
275
 
                self.apache_req, timeout = 60 * 60 * 24)
276
 
        return self.session
277
 
 
278
 
    def get_fieldstorage(self):
279
 
        """Returns a mod_python FieldStorage object for this request.
280
 
        Note that this is dependent on mod_python and may need to change
281
 
        interface if porting away from mod_python."""
282
 
        # Cache the fieldstorage object
283
 
        if not hasattr(self, 'fields'):
284
 
            self.fields = mod_python.util.FieldStorage(self.apache_req)
285
 
        return self.fields
286
 
 
287
 
    def get_cgi_environ(self):
288
 
        """Returns the CGI environment emulation for this request. (Calls
289
 
        add_common_vars). The environment is returned as a mapping
290
 
        compatible with os.environ."""
291
 
        if not self.got_common_vars:
292
 
            self.apache_req.add_common_vars()
293
 
            self.got_common_vars = True
294
 
        return self.apache_req.subprocess_env
295
 
 
296
 
    @property
297
 
    def store(self):
298
 
        # Open a database connection and transaction, keep it around for users
299
 
        # of the Request object to use.
300
 
        if self._store is None:
301
 
            self._store = ivle.database.get_store(self.config)
302
 
        return self._store
303
 
 
304
 
    @property
305
 
    def user(self):
306
 
        # Get and cache the request user, or None if it's not valid.
307
 
        # This is a property so that we don't create a store unless
308
 
        # some code actually requests the user.
309
 
        try:
310
 
            return self._user
311
 
        except AttributeError:
312
 
            if self.publicmode:
313
 
                self._user = None
314
 
            else:
315
 
                temp_user = ivle.webapp.security.get_user_details(self)
316
 
                if temp_user and temp_user.valid:
317
 
                    self._user = temp_user
318
 
                else:
319
 
                    self._user = None
320
 
            return self._user
321