PageRenderTime 154ms CodeModel.GetById 72ms app.highlight 5ms RepoModel.GetById 76ms app.codeStats 0ms

/kai/lib/decorators.py

https://bitbucket.org/bbangert/kai/
Python | 44 lines | 35 code | 5 blank | 4 comment | 5 complexity | a11c3a94da17112a809e518beb1ec03f MD5 | raw file
 1"""Solon decorators"""
 2import logging
 3
 4import pylons
 5from decorator import decorator
 6from pylons.controllers.util import abort
 7from tw2.core import ValidationError
 8
 9log = logging.getLogger(__name__)
10
11def in_group(group):
12    """Requires a user to be logged in, and the group specified"""
13    def wrapper(func, *args, **kwargs):
14        user = pylons.tmpl_context.user
15        if not user:
16            log.debug("No user logged in for permission restricted function")
17            abort(401, "Not Authorized")
18        if user.in_group(group):
19            log.debug("User %s verified in group %s", user, group)
20            return func(*args, **kwargs)
21        else:
22            log.debug("User %s not in group %s", user, group)
23            abort(401, "Not Authorized")
24    return decorator(wrapper)
25
26@decorator
27def logged_in(func, *args, **kwargs):
28    if not pylons.tmpl_context.user:
29        abort(401, "Not Authorized")
30    else:
31        return func(*args, **kwargs)
32
33def validate(form, error_handler):
34    """Validate a form with tw2"""
35    @decorator
36    def wrapper(func, self, *args, **kwargs):
37        try:
38            self.form_result=form.validate(pylons.request.params.mixed())
39        except ValidationError, e:
40            #Don't bother saving the widget, it's saved by tw2 on the request object anyway
41            pylons.request.method = 'GET'
42            return getattr(self, error_handler)(*args, **kwargs)
43        return func(self, *args, **kwargs)
44    return wrapper