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

1080.1.90 by William Grant
ivle.rpc.decorators: Add (new package, too). Has a couple of decorators to
1
'''Decorators useful for actions in the IVLE AJAX API.
2
3
The first argument to any method wrapped by these needs to be a request.
4
'''
5
1099.1.133 by William Grant
Update ivle.rpc.decorators to use new exceptions.
6
from ivle.webapp.errors import MethodNotAllowed, Unauthorized
7
1080.1.90 by William Grant
ivle.rpc.decorators: Add (new package, too). Has a couple of decorators to
8
class require_method(object):
9
    '''Require that the request has been made with the specified HTTP method.
10
    '''
11
    def __init__(self, method):
12
        self.method = method
13
14
    def __call__(self, func):
15
        def method_or_die(req, *args, **kwargs):
16
           if req.method != self.method:
1099.1.133 by William Grant
Update ivle.rpc.decorators to use new exceptions.
17
                raise MethodNotAllowed(allowed=[self.method])
1080.1.90 by William Grant
ivle.rpc.decorators: Add (new package, too). Has a couple of decorators to
18
           func(req, *args, **kwargs)
19
        return method_or_die
20
1101 by William Grant
Privileges (apart from admin) are now offering-local, not global.
21
def require_admin(func):
22
    '''Require that the logged in user is an admin.'''
23
    def admin_or_die(req, *args, **kwargs):
24
       if not req.user or not req.user.admin:
25
            raise Unauthorized()
26
       func(req, *args, **kwargs)
27
    return admin_or_die
28
29
class require_role_anywhere(object):
30
    '''Require that the logged in user has a role in any offering.'''
31
    def __init__(self, *roles):
32
        self.roles = roles
1080.1.90 by William Grant
ivle.rpc.decorators: Add (new package, too). Has a couple of decorators to
33
34
    def __call__(self, func):
1101 by William Grant
Privileges (apart from admin) are now offering-local, not global.
35
        def role_or_die(req, *args, **kwargs):
36
            if not req.user:
1099.1.133 by William Grant
Update ivle.rpc.decorators to use new exceptions.
37
                raise Unauthorized()
1101 by William Grant
Privileges (apart from admin) are now offering-local, not global.
38
39
            if req.user.admin:
40
                return func(req, *args, **kwargs)
41
42
            roles = set((e.role for e in req.user.active_enrolments))
43
44
            for role in self.roles:
45
                if role in roles:
46
                    return func(req, *args, **kwargs)
47
            raise Unauthorized()
48
        return role_or_die