Ticket #18600: group_required_decorator.diff

File group_required_decorator.diff, 2.5 KB (added by daniel.walz@…, 12 years ago)
  • django/contrib/auth/decorators.py

     
    22from functools import wraps
    33from django.conf import settings
    44from django.contrib.auth import REDIRECT_FIELD_NAME
     5from django.contrib.auth.models import Group
    56from django.core.exceptions import PermissionDenied
    67from django.utils.decorators import available_attrs
    78
     
    6566        # As the last resort, show the login form
    6667        return False
    6768    return user_passes_test(check_perms, login_url=login_url)
     69
     70
     71def group_required(group, login_url=None, raise_exception=False):
     72    """
     73    Decorator for views that checks whether a user is member of a particular
     74    group, redirecting to the log-in page if neccesary.
     75    If the raise_exception parameter is given the PermissionDenied exception
     76    is raised.
     77    """
     78    def check_group(user):
     79        if user.is_in_group(group):
     80            return True
     81
     82        # In case the 403 handler should be called raise the exception
     83        if raise_exception:
     84            raise PermissionDenied
     85        # As the last resort, show the login form
     86        return False
     87    return user_passes_test(check_group, login_url=login_url)
  • django/contrib/auth/models.py

     
    310310    def has_usable_password(self):
    311311        return is_password_usable(self.password)
    312312
     313    def is_in_group(self, group):
     314        """
     315        Returns True if the user is member of the given group. The group
     316        can be given as the Group, the primary key id or the unique name
     317        of the group.
     318        """
     319        if isinstance(group, Group):
     320            return self.groups.filter(id=group.id).exists()
     321        elif isinstance(group, int):
     322            try:
     323                g = Group.objects.get(pk=group)
     324                return self.is_in_group(g)
     325            except Group.DoesNotExist:
     326                return False
     327        elif isinstance(group, str):
     328            try:
     329                g = Group.objects.get(name=group)
     330                return self.is_in_group(g)
     331            except Group.DoesNotExist:
     332                return False
     333        else:
     334            return False
     335       
    313336    def get_group_permissions(self, obj=None):
    314337        """
    315338        Returns a list of permission strings that this user has through his/her
Back to Top