Ticket #18600: group_required_decorator.diff
File group_required_decorator.diff, 2.5 KB (added by , 12 years ago) |
---|
-
django/contrib/auth/decorators.py
2 2 from functools import wraps 3 3 from django.conf import settings 4 4 from django.contrib.auth import REDIRECT_FIELD_NAME 5 from django.contrib.auth.models import Group 5 6 from django.core.exceptions import PermissionDenied 6 7 from django.utils.decorators import available_attrs 7 8 … … 65 66 # As the last resort, show the login form 66 67 return False 67 68 return user_passes_test(check_perms, login_url=login_url) 69 70 71 def 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
310 310 def has_usable_password(self): 311 311 return is_password_usable(self.password) 312 312 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 313 336 def get_group_permissions(self, obj=None): 314 337 """ 315 338 Returns a list of permission strings that this user has through his/her