Debian Codegraph @

guardian/shortcuts.py

raw
1 """Convenient shortcuts to manage or check object permissions."""
2
3 from collections import defaultdict
4 from functools import lru_cache, partial
5 from itertools import groupby
6 from operator import itemgetter
7 from typing import Any, TypeVar
8 import warnings
9
10 from django.apps import apps
11 from django.contrib.auth import get_user_model
12 from django.contrib.auth.models import Group, Permission
13 from django.contrib.contenttypes.models import ContentType
14 from django.db import connection
15 from django.db.models import (
16 BigIntegerField,
17 CharField,
18 Count,
19 ForeignKey,
20 IntegerField,
21 Manager,
22 Model,
23 Q,
24 QuerySet,
25 UUIDField,
26 )
27 from django.db.models.expressions import Value
28 from django.db.models.functions import Cast, Replace
29 from django.shortcuts import _get_queryset
30
31 from guardian.core import ObjectPermissionChecker
32 from guardian.ctypes import get_content_type
33 from guardian.exceptions import (
34 MixedContentTypeError,
35 MultipleIdentityAndObjectError,
36 WrongAppError,
37 )
38 from guardian.utils import (
39 get_anonymous_user,
40 get_group_obj_perms_model,
41 get_identity,
42 get_user_obj_perms_model,
43 )
44
45
46 @lru_cache(None)
47 def _get_ct_cached(app_label: str, codename: str) -> ContentType:
48 """Caches `ContentType` instances like its `QuerySet` does."""
49 return ContentType.objects.get(app_label=app_label, permission__codename=codename)
50
51
52 # kwargs are required to be connected to a django signal
53 def clear_ct_cache(**kwargs) -> None:
54 """Helper to clear cache of `_get_ct_cached`"""
55 _get_ct_cached.cache_clear()
56
57
58 # Allow sorting/grouping by pk by returning first in result tuple
59 _get_first = itemgetter(0)
60
61
62 def _ensure_permission(perm: Permission | str) -> Permission:
63 """Converts string permission to the corresponding django model, if required."""
64 if isinstance(perm, str):
65 try:
66 app_label, codename = perm.split(".", 1)
67 except ValueError:
68 raise ValueError(
69 f"For global permissions, first argument must be in format: 'app_label.codename' (is {perm!r})"
70 )
71 perm = Permission.objects.get(content_type__app_label=app_label, codename=codename)
72 return perm
73
74
75 def _normalize_perm(perm: Permission | str) -> Permission | str:
76 """Normalizes permission codename, if it is a string."""
77 if isinstance(perm, str) and "." in perm:
78 _, perm = perm.split(".", 1)
79
80 return perm
81
82
83 def assign_perm(
84 perm: str | Permission,
85 user_or_group: Any,
86 obj: Model | None = None,
87 ) -> str | Permission | None:
88 """Assigns permission to user/group and object pair.
89
90 Parameters:
91 perm (str | Permission): permission to assign for the given `obj`,
92 in format: `app_label.codename` or `codename` or `Permission` instance.
93 If `obj` is not given, must be in format `app_label.codename` or `Permission` instance.
94 user_or_group (User | AnaonymousUser | Group | list | QuerySet):
95 instance of `User`, `AnonymousUser`, `Group`,
96 list of `User` or `Group`, or queryset of `User` or `Group`;
97 passing any other object would raise a`guardian.exceptions.NotUserNorGroup` exception
98 obj (Model | QuerySet): Django's `Model` instance or QuerySet or
99 a list of Django `Model` instances or `None` if assigning global permission.
100 *Default* is `None`.
101
102 Example:
103 ```shell
104 >>> from django.contrib.sites.models import Site
105 >>> from django.contrib.auth.models import User
106 >>> from guardian.shortcuts import assign_perm
107 >>> site = Site.objects.get_current()
108 >>> user = User.objects.create(username='joe')
109 >>> assign_perm("change_site", user, site)
110 <UserObjectPermission: example.com | joe | change_site>
111 >>> user.has_perm("change_site", site)
112 True
113
114 # or we can assign permission for group:
115
116 >>> group = Group.objects.create(name='joe-group')
117 >>> user.groups.add(group)
118 >>> assign_perm("delete_site", group, site)
119 <GroupObjectPermission: example.com | joe-group | delete_site>
120 >>> user.has_perm("delete_site", site)
121 True
122 ```
123
124 Note: Global permissions
125 This function may also be used to assign standard, *global* permissions if
126 `obj` parameter is omitted. Added Permission would be returned in that
127
128 ```shell
129 >>> assign_perm("sites.change_site", user)
130 <Permission: sites | site | Can change site>
131 ```
132
133 """
134 if isinstance(user_or_group, list) and not user_or_group:
135 return None
136
137 if isinstance(obj, list) and not obj:
138 return None
139
140 user, group = get_identity(user_or_group)
141 # If obj is None we try to operate on global permissions
142 if obj is None:
143 perm = _ensure_permission(perm)
144 if user:
145 user.user_permissions.add(perm)
146 return perm
147 if group:
148 group.permissions.add(perm)
149 return perm
150
151 perm = _normalize_perm(perm)
152 if isinstance(obj, (QuerySet, list)):
153 if isinstance(user_or_group, (QuerySet, list)):
154 raise MultipleIdentityAndObjectError("Only bulk operations on either users/groups OR objects supported")
155 if user:
156 model = get_user_obj_perms_model(obj[0] if isinstance(obj, list) else obj.model)
157 return model.objects.bulk_assign_perm(perm, user, obj)
158 if group:
159 model = get_group_obj_perms_model(obj[0] if isinstance(obj, list) else obj.model)
160 return model.objects.bulk_assign_perm(perm, group, obj)
161
162 if isinstance(user_or_group, (QuerySet, list)):
163 if user:
164 model = get_user_obj_perms_model(obj)
165 return model.objects.assign_perm_to_many(perm, user, obj, ignore_conflicts=True)
166 if group:
167 model = get_group_obj_perms_model(obj)
168 return model.objects.assign_perm_to_many(perm, group, obj, ignore_conflicts=True)
169
170 if user:
171 model = get_user_obj_perms_model(obj)
172 return model.objects.assign_perm(perm, user, obj)
173
174 if group:
175 model = get_group_obj_perms_model(obj)
176 return model.objects.assign_perm(perm, group, obj)
177 return None
178
179
180 def assign(perm, user_or_group, obj=None):
181 """Depreciated function name left in for compatibility"""
182 warnings.warn(
183 "Shortcut function 'assign' is being renamed to 'assign_perm'. Update your code accordingly as old name will be depreciated in 2.0 version.",
184 DeprecationWarning,
185 )
186 return assign_perm(perm, user_or_group, obj)
187
188
189 def remove_perm(
190 perm: str | Permission,
191 user_or_group: Any = None,
192 obj: Model | QuerySet | list | None = None,
193 ) -> tuple[int, dict] | None:
194 """Removes permission from user/group and object pair.
195
196 Parameters:
197 perm (str | Permission): permission to remove for the given `obj`, in format: `app_label.codename` or `codename` or `Permission` instance.
198 If `obj` is not given, must be in format `app_label.codename` or `Permission` instance.
199 user_or_group (User | AnonymousUser | Group | list | QuerySet):
200 instance of `User`, `AnonymousUser`, `Group`,
201 list of `User` or `Group`, or queryset of `User` or `Group`;
202 passing any other object would raise a `guardian.exceptions.NotUserNorGroup` exception
203 obj (Model | QuerySet | None): Django's `Model` instance or QuerySet or
204 a list of Django `Model` instances or `None` if removing global permission.
205 *Default* is `None`.
206 """
207 if isinstance(user_or_group, list) and not user_or_group:
208 return None
209
210 if obj is None and isinstance(user_or_group, (QuerySet, list)):
211 raise MultipleIdentityAndObjectError("Bulk global permissions removal is not supported")
212
213 user, group = get_identity(user_or_group)
214 if obj is None:
215 perm = _ensure_permission(perm)
216 if user:
217 user.user_permissions.remove(perm)
218 return None
219 if group:
220 group.permissions.remove(perm)
221 return None
222
223 perm = _normalize_perm(perm)
224 if isinstance(obj, list) and not obj:
225 return None
226
227 if isinstance(obj, (QuerySet, list)):
228 if isinstance(user_or_group, (QuerySet, list)):
229 raise MultipleIdentityAndObjectError("Only bulk operations on either users/groups OR objects are supported")
230 if user:
231 model = get_user_obj_perms_model(obj[0] if isinstance(obj, list) else obj.model)
232 return model.objects.bulk_remove_perm(perm, user, obj)
233 if group:
234 model = get_group_obj_perms_model(obj[0] if isinstance(obj, list) else obj.model)
235 return model.objects.bulk_remove_perm(perm, group, obj)
236
237 if isinstance(user_or_group, (QuerySet, list)):
238 if user:
239 model = get_user_obj_perms_model(obj)
240 return model.objects.remove_perm_from_many(perm, user, obj)
241 if group:
242 model = get_group_obj_perms_model(obj)
243 return model.objects.remove_perm_from_many(perm, group, obj)
244
245 if user:
246 model = get_user_obj_perms_model(obj)
247 return model.objects.remove_perm(perm, user, obj)
248
249 if group:
250 model = get_group_obj_perms_model(obj)
251 return model.objects.remove_perm(perm, group, obj)
252 return None
253
254
255 def get_perms(user_or_group: Any, obj: Model) -> list[str]:
256 """Get all permissions for given user/group and object pair.
257
258 This function returns a comprehensive list of all permissions that the user or group
259 has for the specified object. For users, this includes both direct permissions
260 and permissions inherited from groups.
261
262 Args:
263 user_or_group: User, AnonymousUser, or Group instance
264 obj: Django model instance for which to check permissions
265
266 Returns:
267 List of permission codenames (strings) for the given user/group and object pair.
268
269 Note:
270 For inactive users (is_active=False), returns empty list [].
271 For superusers, returns all available permissions for the object's model.
272 """
273 check = ObjectPermissionChecker(user_or_group)
274 return check.get_perms(obj)
275
276
277 def get_user_perms(user: Any, obj: Model) -> QuerySet:
278 """Get permissions assigned DIRECTLY to a user for a specific object.
279
280 This function returns ONLY permissions that are explicitly assigned to the user
281 for the given object. It does NOT include permissions inherited from groups.
282
283 Args:
284 user: User or AnonymousUser instance
285 obj: Django model instance for which to check permissions
286
287 Returns:
288 QuerySet of permission codenames (strings) that are directly assigned
289 to the user for the given object.
290
291 Note:
292 For inactive users (is_active=False), returns empty QuerySet.
293 Return type is QuerySet, not list (unlike get_perms()).
294 """
295 check = ObjectPermissionChecker(user)
296 return check.get_user_perms(obj)
297
298
299 def get_group_perms(user_or_group: Any, obj: Model) -> QuerySet[Permission]:
300 """Get permissions assigned to groups for a specific object.
301
302 This function returns permissions that are assigned to groups for the given object.
303 When called with a user, it returns permissions from ALL groups the user belongs to.
304 When called with a group, it returns permissions for that specific group only.
305
306 Args:
307 user_or_group: User, AnonymousUser, or Group instance
308 obj: Django model instance for which to check permissions
309
310 Returns:
311 QuerySet of permission codenames (strings) assigned to the group(s)
312 for the given object.
313
314 Note:
315 For inactive users (is_active=False), returns empty QuerySet.
316 Return type is QuerySet, not list (unlike get_perms()).
317 Does NOT include direct user permissions.
318 """
319 check = ObjectPermissionChecker(user_or_group)
320 return check.get_group_perms(obj)
321
322
323 def get_perms_for_model(cls: type[Model] | Model | str) -> QuerySet:
324 """Get all permissions for a given model class.
325
326 Returns:
327 QuerySet of all Permission objects for the given class.
328 It is possible to pass Model as class or instance.
329 """
330 if isinstance(cls, str):
331 app_label, model_name = cls.split(".")
332 model = apps.get_model(app_label, model_name)
333 else:
334 model = cls
335 ctype = get_content_type(model)
336 return Permission.objects.filter(content_type=ctype)
337
338
339 def get_users_with_perms(
340 obj: Model,
341 attach_perms: bool = False,
342 with_superusers: bool = False,
343 with_group_users: bool = True,
344 only_with_perms_in: list[str] | None = None,
345 ) -> Any | list[str]:
346 """Get all users with *any* object permissions for the given `obj`.
347
348 Parameters:
349 obj (Model): Instance of a Django `Model`.
350 attach_perms (bool): If `True`, return a dictionary of `User` instances
351 with the permissions' codename as a list of values.
352 This fetches users eagerly!
353 with_superusers (bool): Wether results should contain superusers.
354 with_group_users (bool): Whether results should contain users who
355 have only group permissions for given `obj`.
356 only_with_perms_in (list[str]): Only return users with these permissions.
357 Example:
358 ```shell
359 >>> from django.contrib.flatpages.models import FlatPage
360 >>> from django.contrib.auth.models import User
361 >>> from guardian.shortcuts import assign_perm, get_users_with_perms
362 >>>
363 >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
364 >>> joe = User.objects.create_user('joe', '[email protected]', 'joesecret')
365 >>> dan = User.objects.create_user('dan', '[email protected]', 'dansecret')
366 >>> assign_perm('change_flatpage', joe, page)
367 >>> assign_perm('delete_flatpage', dan, page)
368 >>>
369 >>> get_users_with_perms(page)
370 [<User: joe>, <User: dan>]
371 >>>
372 >>> get_users_with_perms(page, attach_perms=True)
373 {<User: joe>: [u'change_flatpage'], <User: dan>: [u'delete_flatpage']}
374 >>> get_users_with_perms(page, only_with_perms_in=['change_flatpage'])
375 [<User: joe>]
376 ```
377 """
378 ctype = get_content_type(obj)
379 if not attach_perms:
380 # It's much easier without attached perms so we do it first if that is
381 # the case
382 user_model = get_user_obj_perms_model(obj)
383 related_name = user_model.user.field.related_query_name()
384 if user_model.objects.is_generic():
385 user_filters = {
386 "%s__content_type" % related_name: ctype,
387 "%s__object_pk" % related_name: obj.pk,
388 }
389 else:
390 user_filters = {"%s__content_object" % related_name: obj}
391 qset = Q(**user_filters)
392 if only_with_perms_in is not None:
393 permission_ids = Permission.objects.filter(content_type=ctype, codename__in=only_with_perms_in).values_list(
394 "id", flat=True
395 )
396 qset &= Q(
397 **{
398 "%s__permission_id__in" % related_name: permission_ids,
399 }
400 )
401 if with_group_users:
402 group_model = get_group_obj_perms_model(obj)
403 if group_model.objects.is_generic():
404 group_obj_perm_filters = {
405 "content_type": ctype,
406 "object_pk": obj.pk,
407 }
408 else:
409 group_obj_perm_filters = {
410 "content_object": obj,
411 }
412 if only_with_perms_in is not None:
413 group_obj_perm_filters.update(
414 {
415 "permission_id__in": permission_ids,
416 }
417 )
418 group_ids = group_model.objects.filter(**group_obj_perm_filters).values("group_id").distinct()
419 qset = qset | Q(groups__in=group_ids)
420 if with_superusers:
421 qset = qset | Q(is_superuser=True)
422 return get_user_model().objects.filter(qset).distinct()
423 else:
424 # TODO: Do not hit db for each user!
425 users = {}
426 for user in get_users_with_perms(
427 obj,
428 with_group_users=with_group_users,
429 only_with_perms_in=only_with_perms_in,
430 with_superusers=with_superusers,
431 ):
432 # TODO: Support the case of set with_group_users but not with_superusers.
433 if with_group_users or with_superusers:
434 users[user] = sorted(get_perms(user, obj))
435 else:
436 users[user] = sorted(get_user_perms(user, obj))
437 return users
438
439
440 def get_groups_with_perms(
441 obj: Model, attach_perms: bool = False, only_with_perms_in: list[str] | None = None
442 ) -> Group | dict:
443 """Get all groups with *any* object permissions for the given `obj`.
444
445 Parameters:
446 obj (Model): persisted Django `Model` instance.
447 attach_perms (bool): Whether return result as a dict of `Group` instances
448 with permissions' codenames list of values.
449 This would fetch groups eagerly!
450 only_with_perms_in (list[str]): Only return groups with these permissions.
451
452 Returns:
453 All `Group` objects with the matching object permissions for the given `obj`.
454
455 Example:
456 ```shell
457 >>> from django.contrib.flatpages.models import FlatPage
458 >>> from guardian.shortcuts import assign_perm, get_groups_with_perms
459 >>> from guardian.models import Group
460 >>>
461 >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
462 >>> admins = Group.objects.create(name='Admins')
463 >>> assign_perm('change_flatpage', admins, page)
464 >>>
465 >>> get_groups_with_perms(page)
466 [<Group: admins>]
467 >>>
468 >>> get_groups_with_perms(page, attach_perms=True)
469 {<Group: admins>: [u'change_flatpage']}
470 ```
471 """
472 ctype = get_content_type(obj)
473 group_model = get_group_obj_perms_model(obj)
474
475 if not attach_perms:
476 # It's much easier without attached perms so we do it first if that is the case
477 group_rel_name = group_model.group.field.related_query_name()
478 if group_model.objects.is_generic():
479 group_filters = {
480 "%s__content_type" % group_rel_name: ctype,
481 "%s__object_pk" % group_rel_name: obj.pk,
482 }
483 else:
484 group_filters = {"%s__content_object" % group_rel_name: obj}
485 if only_with_perms_in is not None:
486 permission_ids = Permission.objects.filter(content_type=ctype, codename__in=only_with_perms_in).values_list(
487 "id", flat=True
488 )
489 group_filters.update(
490 {
491 "%s__permission_id__in" % group_rel_name: permission_ids,
492 }
493 )
494
495 group_rel_model = group_model.group.field.related_model
496 return group_rel_model.objects.filter(**group_filters).distinct()
497 else:
498 group_perms_mapping = defaultdict(list)
499 groups_with_perms = get_groups_with_perms(obj, only_with_perms_in=only_with_perms_in)
500 qs = group_model.objects.filter(group__in=groups_with_perms).prefetch_related("group", "permission")
501 if group_model.objects.is_generic():
502 qs = qs.filter(object_pk=obj.pk, content_type=ctype)
503 else:
504 qs = qs.filter(content_object_id=obj.pk)
505
506 for group_perm in qs:
507 group_perms_mapping[group_perm.group].append(group_perm.permission.codename)
508 return dict(group_perms_mapping)
509
510
511 T = TypeVar("T", bound=Model)
512
513
514 def _compute_codenames_and_ctype(
515 perms: str | list[str],
516 ) -> tuple[ContentType | None, set[str]]:
517 """Extracts ContentType and codenames from given list of permissions."""
518 if isinstance(perms, str):
519 perms = [perms]
520 ctype = None
521 app_label = None
522 codenames = set()
523
524 # Compute codenames and set and ctype if possible
525 for perm in perms:
526 if "." in perm:
527 new_app_label, codename = perm.split(".", 1)
528 if app_label is not None and app_label != new_app_label:
529 raise MixedContentTypeError(f"Given perms must have same app label ({app_label} != {new_app_label})")
530 else:
531 app_label = new_app_label
532 else:
533 codename = perm
534 codenames.add(codename)
535 if app_label is not None:
536 new_ctype = _get_ct_cached(app_label, codename)
537 if ctype is not None and ctype != new_ctype:
538 raise MixedContentTypeError(f"ContentType was once computed to be {ctype} and another one {new_ctype}")
539 else:
540 ctype = new_ctype
541
542 return ctype, codenames
543
544
545 def _compute_queryset(
546 ctype: ContentType | None,
547 klass: type[T] | Manager[T] | QuerySet[T] | None,
548 ) -> tuple[ContentType, QuerySet[T]]:
549 """Computes QuerySet and ContentType if still missing"""
550 if ctype is None and klass is not None:
551 queryset = _get_queryset(klass)
552 ctype = get_content_type(queryset.model)
553 elif ctype is not None and klass is None:
554 queryset = _get_queryset(ctype.model_class())
555 elif klass is None:
556 raise WrongAppError("Cannot determine content type")
557 else:
558 queryset = _get_queryset(klass)
559 if ctype != get_content_type(queryset.model):
560 raise MixedContentTypeError("Content type for given perms and klass differs")
561 return ctype, queryset
562
563
564 def get_objects_for_user(
565 user: Any,
566 perms: str | list[str],
567 klass: type[T] | Manager[T] | QuerySet[T] | None = None,
568 use_groups: bool = True,
569 any_perm: bool = False,
570 with_superuser: bool = True,
571 accept_global_perms: bool = True,
572 ) -> QuerySet[T]:
573 """Get objects that a user has *all* the supplied permissions for.
574
575 Parameters:
576 user (User | AnonymousUser): user to check for permissions.
577 perms (str | list[str]): permission(s) to be checked.
578 If `klass` parameter is not given, those should be full permission
579 names rather than only codenames (i.e. `auth.change_user`).
580 If more than one permission is present within sequence, their content type **must** be
581 the same or `MixedContentTypeError` exception would be raised.
582 klass (Modal | Manager | QuerySet): If not provided, this parameter would be
583 computed based on given `params`.
584 use_groups (bool): Whether to check user's groups object permissions.
585 any_perm (bool): Whether any of the provided permissions in sequence is accepted.
586 with_superuser (bool): if `user.is_superuser`, whether to return the entire queryset.
587 Otherwise will only return objects the user has explicit permissions.
588 This must be `True` for the `accept_global_perms` parameter to have any affect.
589 accept_global_perms (bool): Whether global permissions are taken into account.
590 Object based permissions are taken into account if more than one permission is
591 provided in in perms and at least one of these perms is not globally set.
592 If `any_perm` is `False` then the intersection of matching object is returned.
593 Note, that if `with_superuser` is `False`, `accept_global_perms` will be ignored,
594 which means that only object permissions will be checked!
595
596 Raises:
597 MixedContentTypeError: when computed content type for `perms` and/or `klass` clashes.
598 WrongAppError: if cannot compute app label for given `perms` or `klass`.
599
600 Example:
601 ```shell
602 >>> from django.contrib.auth.models import User
603 >>> from guardian.shortcuts import get_objects_for_user
604 >>> joe = User.objects.get(username='joe')
605 >>> get_objects_for_user(joe, 'auth.change_group')
606 []
607 >>> from guardian.shortcuts import assign_perm
608 >>> group = Group.objects.create('some group')
609 >>> assign_perm('auth.change_group', joe, group)
610 >>> get_objects_for_user(joe, 'auth.change_group')
611 [<Group some group>]
612
613 # The permission string can also be an iterable. Continuing with the previous example:
614
615 >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
616 []
617 >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'], any_perm=True)
618 [<Group some group>]
619 >>> assign_perm('auth.delete_group', joe, group)
620 >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
621 [<Group some group>]
622
623 # Take global permissions into account:
624
625 >>> jack = User.objects.get(username='jack')
626 >>> assign_perm('auth.change_group', jack) # this will set a global permission
627 >>> get_objects_for_user(jack, 'auth.change_group')
628 [<Group some group>]
629 >>> group2 = Group.objects.create('other group')
630 >>> assign_perm('auth.delete_group', jack, group2)
631 >>> get_objects_for_user(jack, ['auth.change_group', 'auth.delete_group']) # this retrieves intersection
632 [<Group other group>]
633 >>> get_objects_for_user(jack, ['auth.change_group', 'auth.delete_group'], any_perm) # this retrieves union
634 [<Group some group>, <Group other group>]
635 ```
636
637 Note:
638 If `accept_global_perms` is set to `True`, then all assigned global
639 permissions will also be taken into account.
640
641 - Scenario 1: a user has view permissions generally defined on the model
642 'books' but no object-based permission on a single book instance:
643
644 - If `accept_global_perms` is `True`: A list of all books will be returned.
645 - If `accept_global_perms` is `False`: The list will be empty.
646
647 - Scenario 2: a user has view permissions generally defined on the model
648 'books' and also has an object-based permission to view book 'Whatever':
649
650 - If `accept_global_perms` is `True`: A list of all books will be returned.
651 - If `accept_global_perms` is `False`: The list will only contain book 'Whatever'.
652
653 - Scenario 3: a user only has object-based permission on book 'Whatever':
654
655 - If `accept_global_perms` is `True`: The list will only contain book 'Whatever'.
656 - If `accept_global_perms` is `False`: The list will only contain book 'Whatever'.
657
658 - Scenario 4: a user does not have any permission:
659
660 - If `accept_global_perms` is `True`: An empty list is returned.
661 - If `accept_global_perms` is `False`: An empty list is returned.
662
663 Note: Primary key types
664 Standard PK types (integer family, ``UUIDField``, ``CharField``) use
665 optimised native casts. Non-standard PK types (e.g. ``TextField``,
666 PostgreSQL ``macaddr``/``inet``) are automatically handled via a
667 ``Cast("pk", CharField())`` fallback, so models with any PK type are
668 supported without extra configuration.
669 """
670 ctype, codenames = _compute_codenames_and_ctype(perms)
671 ctype, queryset = _compute_queryset(ctype, klass)
672
673 # At this point, we should have both ctype and queryset and they should
674 # match which means: ctype.model_class() == queryset.model
675 # we should also have `codenames` list
676
677 # First check if user is superuser and if so, return queryset immediately
678 if with_superuser and user.is_superuser:
679 return queryset
680
681 # Check if the user is anonymous. The
682 # django.contrib.auth.models.AnonymousUser object doesn't work for queries
683 # and it's nice to be able to pass in request.user blindly.
684 if user.is_anonymous:
685 user = get_anonymous_user()
686
687 has_global_perms = False
688 # a superuser has by default assigned global perms for any
689 if accept_global_perms and with_superuser:
690 global_perms = {code for code in codenames if user.has_perm(ctype.app_label + "." + code)}
691 for code in global_perms:
692 codenames.remove(code)
693 # prerequisite: there must be elements in global_perms otherwise just follow the procedure for
694 # object based permissions only AND
695 # 1. codenames is empty, which means that permissions are ONLY set globally, therefore return the full queryset.
696 # OR
697 # 2. any_perm is True, then the global permission beats the object based permission anyway,
698 # therefore return full queryset
699 if global_perms and (not codenames or any_perm):
700 return queryset
701 # if we have global perms and still some object based perms differing from global perms and any_perm is set
702 # to false, then we have to flag that global perms exist in order to merge object based permissions by user
703 # and by group correctly. Scenario: global perm change_xx and object based perm delete_xx on object A for user,
704 # and object based permission delete_xx on object B for group, to which user is assigned.
705 # get_objects_for_user(user, [change_xx, delete_xx], use_groups=True, any_perm=False, accept_global_perms=True)
706 # must retrieve object A and B.
707 elif global_perms and codenames:
708 has_global_perms = True
709
710 # Now we should extract the list of pk values for which we would filter the queryset
711 user_model = get_user_obj_perms_model(queryset.model)
712 user_obj_perms_queryset = filter_perms_queryset_by_objects(
713 user_model.objects.filter(user=user).filter(permission__content_type=ctype), klass
714 )
715 if codenames:
716 user_obj_perms_queryset = user_obj_perms_queryset.filter(permission__codename__in=codenames)
717 direct_fields = ["content_object__pk", "permission__codename"]
718 generic_fields = ["object_pk", "permission__codename"]
719 if user_model.objects.is_generic():
720 user_fields = generic_fields
721 else:
722 user_fields = direct_fields
723
724 if use_groups:
725 group_model = get_group_obj_perms_model(queryset.model)
726 group_filters = {
727 "permission__content_type": ctype,
728 "group__in": user.groups.all(),
729 }
730 if codenames:
731 group_filters.update(
732 {
733 "permission__codename__in": codenames,
734 }
735 )
736 groups_obj_perms_queryset = filter_perms_queryset_by_objects(group_model.objects.filter(**group_filters), klass)
737 if group_model.objects.is_generic():
738 group_fields = generic_fields
739 else:
740 group_fields = direct_fields
741 if not any_perm and len(codenames) > 1 and not has_global_perms:
742 user_obj_perms = user_obj_perms_queryset.values_list(*user_fields)
743 groups_obj_perms = groups_obj_perms_queryset.values_list(*group_fields)
744 data = list(user_obj_perms) + list(groups_obj_perms)
745 # sorting/grouping by pk (first in result tuple)
746 data = sorted(data, key=_get_first)
747 pk_list = []
748 for pk, group in groupby(data, _get_first):
749 obj_codenames = {e[1] for e in group}
750 if codenames.issubset(obj_codenames):
751 pk_list.append(pk)
752 objects = queryset.filter(pk__in=pk_list)
753 return objects
754
755 if not any_perm and len(codenames) > 1:
756 counts = user_obj_perms_queryset.values(user_fields[0]).annotate(object_pk_count=Count(user_fields[0]))
757 user_obj_perms_queryset = counts.filter(object_pk_count__gte=len(codenames))
758
759 field_pk = user_fields[0]
760 values = user_obj_perms_queryset
761
762 handle_pk_field = _handle_pk_field(queryset)
763 use_str_pk_for_user = handle_pk_field is None or (
764 user_model.objects.is_generic() and _casts_to_bigint(handle_pk_field)
765 )
766 if not use_str_pk_for_user:
767 values = values.annotate(obj_pk=handle_pk_field(expression=field_pk))
768 field_pk = "obj_pk"
769
770 values = values.values_list(field_pk, flat=True)
771 str_pk_annotated = False
772 if use_str_pk_for_user:
773 queryset = queryset.annotate(str_pk=Cast("pk", CharField()))
774 str_pk_annotated = True
775 q = Q(str_pk__in=values)
776 else:
777 q = Q(pk__in=values)
778 if use_groups:
779 field_pk = group_fields[0]
780 values = groups_obj_perms_queryset
781 use_str_pk_for_group = handle_pk_field is None or (
782 group_model.objects.is_generic() and _casts_to_bigint(handle_pk_field)
783 )
784 if not use_str_pk_for_group:
785 values = values.annotate(obj_pk=handle_pk_field(expression=field_pk))
786 field_pk = "obj_pk"
787 values = values.values_list(field_pk, flat=True)
788 if use_str_pk_for_group:
789 if not str_pk_annotated:
790 queryset = queryset.annotate(str_pk=Cast("pk", CharField()))
791 q |= Q(str_pk__in=values)
792 else:
793 q |= Q(pk__in=values)
794 return queryset.filter(q)
795
796
797 def get_objects_for_group(
798 group: Group,
799 perms: str | list[str],
800 klass: type[T] | Manager[T] | QuerySet[T] | None = None,
801 any_perm: bool = False,
802 accept_global_perms: bool = True,
803 ) -> QuerySet[T]:
804 """Get objects that a group has *all* the supplied permissions for.
805
806 Parameters:
807 group (Group): `Group` instance for which objects would be returned.
808 perms (str | list[str]): permission(s) which should be checked.
809 If `klass` parameter is not given, those should be full permission
810 names rather than only codenames (i.e. `auth.change_user`).
811 If more than one permission is present within sequence,
812 their content type **must** be the same or `MixedContentTypeError` exception is raised.
813 klass (Model | Manager | QuerySet): If not provided this parameter is computed
814 based on given `params`.
815 any_perm (bool): Whether any of permission in sequence is accepted.
816 accept_global_perms (bool): Whether global permissions are taken into account.
817 If `any_perm` is `False`, then the intersection of matching objects based on
818 global and object-based permissionsis returned.
819
820 Returns:
821 objects for which a given `group` has *all* permissions in `perms`.
822
823 Raisess:
824 MixedContentTypeError: when computed content type for `perms` and/or `klass` clashes.
825 WrongAppError: if cannot compute app label for given `perms`/`klass`.
826
827 Example:
828 Let's assume we have a `Task` model belonging to the `tasker` app with
829 the default add_task, change_task and delete_task permissions provided
830 by Django:
831
832 ```shell
833 >>> from guardian.shortcuts import get_objects_for_group
834 >>> from tasker import Task
835 >>> group = Group.objects.create('some group')
836 >>> task = Task.objects.create('some task')
837 >>> get_objects_for_group(group, 'tasker.add_task')
838 []
839 >>> from guardian.shortcuts import assign_perm
840 >>> assign_perm('tasker.add_task', group, task)
841 >>> get_objects_for_group(group, 'tasker.add_task')
842 [<Task some task>]
843
844 # The permission string can also be an iterable. Continuing with the previous example:
845
846 >>> get_objects_for_group(group, ['tasker.add_task', 'tasker.delete_task'])
847 []
848 >>> assign_perm('tasker.delete_task', group, task)
849 >>> get_objects_for_group(group, ['tasker.add_task', 'tasker.delete_task'])
850 [<Task some task>]
851
852 # Global permissions assigned to the group are also taken into account. Continuing with previous example:
853
854 >>> task_other = Task.objects.create('other task')
855 >>> assign_perm('tasker.change_task', group)
856 >>> get_objects_for_group(group, ['tasker.change_task'])
857 [<Task some task>, <Task other task>]
858 >>> get_objects_for_group(group, ['tasker.change_task'], accept_global_perms=False)
859 [<Task some task>]
860 ```
861
862 Note: Primary key types
863 Standard PK types (integer family, ``UUIDField``, ``CharField``) use
864 optimised native casts. Non-standard PK types (e.g. ``TextField``,
865 PostgreSQL ``macaddr``/``inet``) are automatically handled via a
866 ``Cast("pk", CharField())`` fallback, so models with any PK type are
867 supported without extra configuration.
868 """
869 ctype, codenames = _compute_codenames_and_ctype(perms)
870 ctype, queryset = _compute_queryset(ctype, klass)
871
872 # At this point, we should have both ctype and queryset and they should
873 # match which means: ctype.model_class() == queryset.model
874 # we should also have `codenames` list
875
876 global_perms = set()
877 if accept_global_perms:
878 global_perm_set = group.permissions.values_list("codename", flat=True)
879 for code in codenames:
880 if code in global_perm_set:
881 global_perms.add(code)
882 for code in global_perms:
883 codenames.remove(code)
884 if global_perms and (not codenames or any_perm):
885 return queryset
886
887 # Now we should extract list of pk values for which we would filter
888 # queryset
889 group_model = get_group_obj_perms_model(queryset.model)
890 groups_obj_perms_queryset = filter_perms_queryset_by_objects(
891 group_model.objects.filter(group=group).filter(permission__content_type=ctype), klass
892 )
893 if codenames:
894 groups_obj_perms_queryset = groups_obj_perms_queryset.filter(permission__codename__in=codenames)
895 if group_model.objects.is_generic():
896 fields = ["object_pk", "permission__codename"]
897 else:
898 fields = ["content_object__pk", "permission__codename"]
899 if not any_perm and codenames:
900 groups_obj_perms = groups_obj_perms_queryset.values_list(*fields)
901 data = list(groups_obj_perms)
902
903 # sorting/grouping by pk (first in result tuple)
904 data = sorted(data, key=_get_first)
905 pk_list = []
906 for pk, group in groupby(data, _get_first):
907 obj_codenames = {e[1] for e in group}
908 if any_perm or codenames.issubset(obj_codenames):
909 pk_list.append(pk)
910 objects = queryset.filter(pk__in=pk_list)
911 return objects
912
913 field_pk = fields[0]
914 values = groups_obj_perms_queryset
915
916 handle_pk_field = _handle_pk_field(queryset)
917 use_str_pk = handle_pk_field is None or (group_model.objects.is_generic() and _casts_to_bigint(handle_pk_field))
918 if not use_str_pk:
919 values = values.annotate(obj_pk=handle_pk_field(expression=field_pk))
920 field_pk = "obj_pk"
921 else:
922 queryset = queryset.annotate(str_pk=Cast("pk", CharField()))
923
924 values = values.values_list(field_pk, flat=True)
925 if not use_str_pk:
926 return queryset.filter(pk__in=values)
927 else:
928 return queryset.filter(str_pk__in=values)
929
930
931 def _handle_pk_field(queryset):
932 pk = queryset.model._meta.pk
933
934 if isinstance(pk, ForeignKey):
935 return _handle_pk_field(pk.target_field)
936
937 if isinstance(pk, IntegerField):
938 return partial(Cast, output_field=BigIntegerField())
939
940 if isinstance(pk, UUIDField):
941 if connection.features.has_native_uuid_field:
942 return partial(Cast, output_field=UUIDField())
943 return partial(
944 Replace,
945 text=Value("-"),
946 replacement=Value(""),
947 output_field=CharField(),
948 )
949
950 return None
951
952
953 def _casts_to_bigint(handle_pk_field):
954 return (
955 isinstance(handle_pk_field, partial)
956 and handle_pk_field.func is Cast
957 and isinstance(handle_pk_field.keywords.get("output_field"), BigIntegerField)
958 )
959
960
961 def filter_perms_queryset_by_objects(perms_queryset, objects):
962 if isinstance(objects, QuerySet):
963 field = "content_object__pk"
964 if perms_queryset.model.objects.is_generic():
965 field = "object_pk"
966 handle_pk_field = _handle_pk_field(objects)
967 if handle_pk_field is not None:
968 if _casts_to_bigint(handle_pk_field):
969 # Keep object_pk untouched to avoid CAST(object_pk AS bigint)
970 # scans on large guardian tables. We only stringify model PKs.
971 objects = objects.annotate(_pk=Cast("pk", output_field=CharField())).values_list("_pk", flat=True)
972 field = "object_pk"
973 else:
974 objects = objects.annotate(_pk=Cast(handle_pk_field("pk"), output_field=CharField())).values_list(
975 "_pk", flat=True
976 )
977 # Apply the same transformation to the object_pk field for consistent comparison (#930)
978 perms_queryset = perms_queryset.annotate(
979 _transformed_object_pk=Cast(handle_pk_field(field), output_field=CharField())
980 )
981 field = "_transformed_object_pk"
982 else:
983 objects = objects.values_list("pk", flat=True)
984 else:
985 objects = objects.values_list("pk", flat=True)
986 return perms_queryset.filter(**{f"{field}__in": objects})
987 else:
988 return perms_queryset