Ticket #6056: contrib_auth_decorators.py.2.diff

File contrib_auth_decorators.py.2.diff, 1.9 KB (added by yong27@…, 17 years ago)

sorry, some typo fixed

  • django/contrib/auth/decorators.py

     
    3232    """
    3333    return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url)
    3434
     35def permission_required_or_message(perm):
     36    """
     37    Decorator for views that checks whether a user has a particular permission
     38    enabled, if user is authenticated, show message and redirect to refer,
     39    else, redirecting to the log-in page.
     40    """
     41    def decorate(view_func):
     42        return _CheckLoginOrMessage(view_func, lambda u: u.has_perm(perm))
     43    return decorate
     44
    3545class _CheckLogin(object):
    3646    """
    3747    Class that checks that the user passes the given test, redirecting to
     
    6070    def __call__(self, request, *args, **kwargs):
    6171        if self.test_func(request.user):
    6272            return self.view_func(request, *args, **kwargs)
     73        return self.redirect_to_login(request)
     74
     75    def redirect_to_login(self, request):
    6376        path = urlquote(request.get_full_path())
    6477        tup = self.login_url, self.redirect_field_name, path
    6578        return HttpResponseRedirect('%s?%s=%s' % tup)
     79
     80class _CheckLoginOrMessage(_CheckLogin):
     81    """
     82    If user is authenticated, show message and redirect to refer.
     83    """
     84    def __call__(self, request, *args, **kwargs):
     85        if self.test_func(request.user):
     86            return self.view_func(request, *args, **kwargs)
     87        refer = request.META.get('HTTP_REFERER')
     88        if not refer or not request.user.is_authenticated():
     89            return self.redirect_to_login(request)
     90        request.user.message_set.create(
     91            message=_("%s has no %s permission" % (
     92                request.user.username, self.__name__)))
     93        return HttpResponseRedirect(refer)
     94
Back to Top