urls_utils.py 1.64 KB
Newer Older
1
from django.contrib.auth.decorators import user_passes_test
2
from django.core.urlresolvers import RegexURLPattern, RegexURLResolver
3 4
from django.core.exceptions import PermissionDenied

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

class DecoratedURLPattern(RegexURLPattern):
    def resolve(self, *args, **kwargs):
        result = super(DecoratedURLPattern, self).resolve(*args, **kwargs)
        if result:
            result.func = self._decorate_with(result.func)
        return result

class DecoratedRegexURLResolver(RegexURLResolver):
    def resolve(self, *args, **kwargs):
        result = super(DecoratedRegexURLResolver, self).resolve(*args, **kwargs)
        if result:
            result.func = self._decorate_with(result.func)
        return result

def decorated_includes(func, includes, *args, **kwargs):
    urlconf_module, app_name, namespace = includes

    for item in urlconf_module:
        if isinstance(item, RegexURLPattern):
            item.__class__ = DecoratedURLPattern
            item._decorate_with = func

        elif isinstance(item, RegexURLResolver):
            item.__class__ = DecoratedRegexURLResolver
            item._decorate_with = func

    return urlconf_module, app_name, namespace

34 35 36

def cms_permission_required(function=None, login_url=None):
    def check_cms_permission(user):
37
        if user and user.has_perm('data.add_page'):
38 39 40 41 42 43 44 45 46
            return True
        if user and not user.is_anonymous():
            raise PermissionDenied()
        # As the last resort, show the login form
        return False
    actual_decorator = user_passes_test(check_cms_permission, login_url=login_url)
    if function:
        return actual_decorator(function)
    return actual_decorator