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

« back to all changes in this revision

Viewing changes to ivle/webapp/base/rest.py

  • Committer: William Grant
  • Date: 2009-12-06 10:18:20 UTC
  • mto: This revision was merged to the branch mainline in revision 1353.
  • Revision ID: grantw@unimelb.edu.au-20091206101820-d1oogsihfruowjfq
Unbreak project(set) traversals.

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, Will Grant, Nick Chadwick
 
19
 
 
20
import os
 
21
import cgi
 
22
import urlparse
 
23
import inspect
 
24
 
 
25
import cjson
 
26
import genshi.template
 
27
 
 
28
from ivle.webapp.base.views import BaseView
 
29
from ivle.webapp.errors import BadRequest, MethodNotAllowed, Unauthorized
 
30
 
 
31
class RESTView(BaseView):
 
32
    """
 
33
    A view which provides a RESTful interface. The content type is
 
34
    unspecified (see JSONRESTView for a specific content type).
 
35
    """
 
36
    content_type = "application/octet-stream"
 
37
 
 
38
    def render(self, req):
 
39
        raise NotImplementedError()
 
40
 
 
41
class JSONRESTView(RESTView):
 
42
    """
 
43
    A special case of RESTView which deals entirely in JSON.
 
44
    """
 
45
    content_type = "application/json"
 
46
 
 
47
    _allowed_methods = property(
 
48
        lambda self: [m for m in ('GET', 'PUT', 'PATCH')
 
49
                      if hasattr(self, m)] + ['POST'])
 
50
 
 
51
    def authorize(self, req):
 
52
        return True # Real authz performed in render().
 
53
 
 
54
    def authorize_method(self, req, op):
 
55
        if not hasattr(op, '_rest_api_permission'):
 
56
            raise Unauthorized()
 
57
 
 
58
        if op._rest_api_permission not in self.get_permissions(req.user):
 
59
            raise Unauthorized()
 
60
    
 
61
    def convert_bool(self, value):
 
62
        if value in ('True', 'true', True):
 
63
            return True
 
64
        elif value in ('False', 'false', False):
 
65
            return False
 
66
        else:
 
67
            raise BadRequest()
 
68
 
 
69
    def render(self, req):
 
70
        if req.method not in self._allowed_methods:
 
71
            raise MethodNotAllowed(allowed=self._allowed_methods)
 
72
 
 
73
        if req.method == 'GET':
 
74
            self.authorize_method(req, self.GET)
 
75
            outjson = self.GET(req)
 
76
        # Since PATCH isn't yet an official HTTP method, we allow users to
 
77
        # turn a PUT into a PATCH by supplying a special header.
 
78
        elif req.method == 'PATCH' or (req.method == 'PUT' and
 
79
              'X-IVLE-Patch-Semantics' in req.headers_in and
 
80
              req.headers_in['X-IVLE-Patch-Semantics'].lower() == 'yes'):
 
81
            self.authorize_method(req, self.PATCH)
 
82
            try:
 
83
                input = cjson.decode(req.read())
 
84
            except cjson.DecodeError:
 
85
                raise BadRequest('Invalid JSON data')
 
86
            outjson = self.PATCH(req, input)
 
87
        elif req.method == 'PUT':
 
88
            self.authorize_method(req, self.PUT)
 
89
            try:
 
90
                input = cjson.decode(req.read())
 
91
            except cjson.DecodeError:
 
92
                raise BadRequest('Invalid JSON data')
 
93
            outjson = self.PUT(req, input)
 
94
        # POST implies named operation.
 
95
        elif req.method == 'POST':
 
96
            # TODO: Check Content-Type and implement multipart/form-data.
 
97
            data = req.read()
 
98
            opargs = dict(cgi.parse_qsl(data, keep_blank_values=1))
 
99
            try:
 
100
                opname = opargs['ivle.op']
 
101
                del opargs['ivle.op']
 
102
            except KeyError:
 
103
                raise BadRequest('No named operation specified.')
 
104
 
 
105
            try:
 
106
                op = getattr(self, opname)
 
107
            except AttributeError:
 
108
                raise BadRequest('Invalid named operation.')
 
109
 
 
110
            if not hasattr(op, '_rest_api_callable') or \
 
111
               not op._rest_api_callable:
 
112
                raise BadRequest('Invalid named operation.')
 
113
 
 
114
            self.authorize_method(req, op)
 
115
 
 
116
            # Find any missing arguments, except for the first two (self, req)
 
117
            (args, vaargs, varkw, defaults) = inspect.getargspec(op)
 
118
            args = args[2:]
 
119
 
 
120
            # To find missing arguments, we eliminate the provided arguments
 
121
            # from the set of remaining function signature arguments. If the
 
122
            # remaining signature arguments are in the args[-len(defaults):],
 
123
            # we are OK.
 
124
            unspec = set(args) - set(opargs.keys())
 
125
            if unspec and not defaults:
 
126
                raise BadRequest('Missing arguments: ' + ', '.join(unspec))
 
127
 
 
128
            unspec = [k for k in unspec if k not in args[-len(defaults):]]
 
129
 
 
130
            if unspec:
 
131
                raise BadRequest('Missing arguments: ' + ', '.join(unspec))
 
132
 
 
133
            # We have extra arguments if the are no match args in the function
 
134
            # signature, AND there is no **.
 
135
            extra = set(opargs.keys()) - set(args)
 
136
            if extra and not varkw:
 
137
                raise BadRequest('Extra arguments: ' + ', '.join(extra))
 
138
 
 
139
            outjson = op(req, **opargs)
 
140
 
 
141
        req.content_type = self.content_type
 
142
        self.write_json(req, outjson)
 
143
 
 
144
    #This is a separate function to allow additional data to be passed through
 
145
    def write_json(self, req, outjson):
 
146
        if outjson is not None:
 
147
            req.write(cjson.encode(outjson))
 
148
            req.write("\n")
 
149
 
 
150
 
 
151
class XHTMLRESTView(JSONRESTView):
 
152
    """A special type of RESTView which takes enhances the standard JSON
 
153
    with genshi XHTML functions.
 
154
    
 
155
    XHTMLRESTViews should have a template, which is rendered using their
 
156
    context. This is returned in the JSON as 'html'"""
 
157
    template = None
 
158
    ctx = genshi.template.Context()
 
159
 
 
160
    def render_fragment(self):
 
161
        if self.template is None:
 
162
            raise NotImplementedError()
 
163
 
 
164
        rest_template = os.path.join(os.path.dirname(
 
165
                inspect.getmodule(self).__file__), self.template)
 
166
        loader = genshi.template.TemplateLoader(".", auto_reload=True)
 
167
        tmpl = loader.load(rest_template)
 
168
 
 
169
        return tmpl.generate(self.ctx).render('xhtml', doctype='xhtml')
 
170
    
 
171
    # This renders the template and adds it to the json
 
172
    def write_json(self, req, outjson):
 
173
        outjson["html"] = self.render_fragment()
 
174
        req.write(cjson.encode(outjson))
 
175
        req.write("\n")
 
176
 
 
177
class named_operation(object):
 
178
    '''Declare a function to be accessible to HTTP users via the REST API.
 
179
    '''
 
180
    def __init__(self, permission):
 
181
        self.permission = permission
 
182
 
 
183
    def __call__(self, func):
 
184
        func._rest_api_callable = True
 
185
        func._rest_api_permission = self.permission
 
186
        return func
 
187
 
 
188
class require_permission(object):
 
189
    '''Declare the permission required for use of a method via the REST API.
 
190
    '''
 
191
    def __init__(self, permission):
 
192
        self.permission = permission
 
193
 
 
194
    def __call__(self, func):
 
195
        func._rest_api_permission = self.permission
 
196
        return func