Debian Codegraph @

guardian/models/models.py

raw
1 from django.contrib.auth.models import Group, Permission
2 from django.contrib.contenttypes.fields import GenericForeignKey
3 from django.contrib.contenttypes.models import ContentType
4 from django.core.exceptions import ValidationError
5 from django.db import models
6 from django.utils.translation import gettext_lazy as _
7
8 from guardian.compat import user_model_label
9 from guardian.ctypes import get_content_type
10 from guardian.managers import GroupObjectPermissionManager, UserObjectPermissionManager
11
12
13 class BaseObjectPermission(models.Model):
14 """Base ObjectPermission model.
15
16 Child classed should additionally define a `content_object` field and either `user` or `group` field.
17
18 See Also:
19 `UserObjectPermission` and `GroupObjectPermission`
20 """
21
22 permission = models.ForeignKey(Permission, on_delete=models.CASCADE)
23
24 class Meta:
25 abstract = True
26
27 def __str__(self) -> str:
28 return "{} | {} | {}".format(
29 str(self.content_object), str(getattr(self, "user", False) or self.group), str(self.permission.codename)
30 )
31
32 def save(self, *args, **kwargs) -> None:
33 """Save the current instance.
34
35 Override this if you need to control the saving process.
36 The `force_insert` and `force_update` parameters can be used to insist that the “save”
37 must be an SQL insert or update statement, respectively (or equivalent for non-SQL backends).
38 Normally, they should not be set.
39
40 Other Parameters:
41 force_insert (bool): If True, the save will be forced to be an insert.
42 force_update (bool): If True, the save will be forced to be an update.
43 """
44 content_type = get_content_type(self.content_object)
45 if content_type != self.permission.content_type:
46 raise ValidationError(
47 "Cannot persist permission not designed for "
48 "this class (permission's type is %r and object's type is %r)"
49 % (self.permission.content_type, content_type)
50 )
51 return super().save(*args, **kwargs)
52
53
54 class BaseGenericObjectPermission(models.Model):
55 content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
56 object_pk = models.CharField(_("object ID"), max_length=255)
57 content_object = GenericForeignKey(fk_field="object_pk")
58
59 class Meta:
60 abstract = True
61 indexes = [
62 models.Index(fields=["content_type", "object_pk"]),
63 ]
64
65
66 class UserObjectPermissionBase(BaseObjectPermission):
67 """Base class for creating object level permissions for users.
68
69 This class can be used as a base class for creating a custom model to
70 manager user object-level permissions.
71
72 Attributes:
73 user (ForeignKey): The django user model that has the permission.
74 permission (ForeignKey): Foreign key to the permission granted.
75 content_object (ForeignKey, GenericForeignKey):
76 A foreign Key to the model class that the permission will be granted for.
77
78 Example:
79 ```python
80 from guardian.models import UserObjectPermissionBase
81
82 class OrgUserObjectPermission(UserObjectPermissionBase):
83 \"\"\"Organization Specific permissions.\"\"\"
84
85 class Meta(UserObjectPermissionBase.Meta):
86 verbose_name = "Organization Permission"
87 verbose_name_plural = "Organization Permissions"
88
89 # Note: class attribute must be named content_object
90 content_object = models.ForeignKey("myapp.Org", on_delete=models.CASCADE, db_column="org_object_id")
91
92 ```
93
94 See Also:
95 - [Django-Guardian Performance Tuning](https://django-guardian.readthedocs.io/en/stable/userguide/performance.html)
96 - [How to override the default UserObjectPermission](https://django-guardian.readthedocs.io/en/stable/configuration.html#guardian-user-obj-perms-model)
97 """
98
99 user = models.ForeignKey(user_model_label, on_delete=models.CASCADE)
100
101 objects = UserObjectPermissionManager()
102
103 class Meta:
104 abstract = True
105 unique_together = ["user", "permission", "content_object"]
106
107
108 class UserObjectPermissionAbstract(UserObjectPermissionBase, BaseGenericObjectPermission):
109 class Meta(UserObjectPermissionBase.Meta, BaseGenericObjectPermission.Meta):
110 abstract = True
111 unique_together = ["user", "permission", "object_pk"]
112
113
114 class UserObjectPermission(UserObjectPermissionAbstract):
115 """The default implementation of the UserObjectPermissionAbstract model.
116
117 If `GUARDIAN_USER_OBJ_PERMS_MODEL` is not set at the beginning of the project, this model will be used.
118 Uses Django's contenttypes framework to store generic relations.
119
120 See Also:
121 - [Django's Documentation on Abstract Base Models](https://docs.djangoproject.com/en/stable/topics/db/models/#abstract-base-classes)
122 - [Django-Guardian Performance Tuning](https://django-guardian.readthedocs.io/en/stable/userguide/performance.html)
123 - [How to override the default UserObjectPermission](https://django-guardian.readthedocs.io/en/stable/configuration.html#guardian-user-obj-perms-model)
124 """
125
126 class Meta(UserObjectPermissionAbstract.Meta):
127 abstract = False
128 indexes = [
129 models.Index(fields=["permission", "user", "content_type", "object_pk"]),
130 models.Index(fields=["user", "content_type", "object_pk"]),
131 ]
132
133
134 class GroupObjectPermissionBase(BaseObjectPermission):
135 """Base class for creating django-guardian groups.
136
137 This class can be used as a base class for creating a groups permission.
138
139 Attributes:
140 group (ForeignKey): A foreign key to the django auth group.
141 permission (ForeignKey): Foreign key to the permission granted.
142 content_object (ForeignKey, GenericForeignKey):
143 A foreign Key to the model class that the permission will be granted for.
144
145 Example:
146 ```python
147 from guardian.models import GroupObjectPermissionBase
148
149 class OrgGroupObjectPermission(GroupObjectPermissionBase):
150 \"\"\"Organization Groups.\"\"\"
151
152 class Meta(GroupObjectPermissionBase.Meta):
153 verbose_name = "Organization Role"
154 verbose_name_plural = "Organization Roles"
155
156 content_object = models.ForeignKey("myapp.Org", on_delete=models.CASCADE, db_column="org_object_id")
157 ```
158
159 See Also:
160 - [Django-Guardian Performance Tuning](https://django-guardian.readthedocs.io/en/stable/userguide/performance.html)
161 - [How to override the default UserObjectPermission](https://django-guardian.readthedocs.io/en/stable/configuration.html#guardian-user-obj-perms-model)
162 """
163
164 group = models.ForeignKey(Group, on_delete=models.CASCADE)
165
166 objects = GroupObjectPermissionManager()
167
168 class Meta:
169 abstract = True
170 unique_together = ["group", "permission", "content_object"]
171
172
173 class GroupObjectPermissionAbstract(GroupObjectPermissionBase, BaseGenericObjectPermission):
174 class Meta(GroupObjectPermissionBase.Meta, BaseGenericObjectPermission.Meta):
175 abstract = True
176 unique_together = ["group", "permission", "object_pk"]
177
178
179 class GroupObjectPermission(GroupObjectPermissionAbstract):
180 """The default implementation of the GroupObjectPermissionAbstract model.
181
182 If `GUARDIAN_GROUP_OBJ_PERMS_MODEL` is not set at the beginning of the project, this model will be used.
183 Uses Django's contenttypes framework to store generic relations.
184
185 See Also:
186 - [Django's Documentation on Abstract Base Models](https://docs.djangoproject.com/en/stable/topics/db/models/#abstract-base-classes)
187 - [Django-Guardian Performance Tuning](https://django-guardian.readthedocs.io/en/stable/userguide/performance.html)
188 - [How to override the default GroupObjectPermission](https://django-guardian.readthedocs.io/en/stable/configuration.html#guardian-user-obj-perms-model)
189 """
190
191 class Meta(GroupObjectPermissionAbstract.Meta):
192 abstract = False
193 indexes = [
194 models.Index(fields=["permission", "group", "content_type", "object_pk"]),
195 models.Index(fields=["group", "content_type", "object_pk"]),
196 ]