Debian Codegraph @

src/organizations/base.py

raw symbols SCIP
1
2 import uuid
3
4 from django.conf import settings
5 from django.core.exceptions import FieldDoesNotExist
6 from django.db import models
7 from django.db.models.base import ModelBase
8 from django.urls import reverse
9 from django.utils.translation import gettext_lazy as _
10
11 from organizations import signals
12 from organizations.managers import ActiveOrgManager
13 from organizations.managers import OrgManager
14
15 USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User")
16
17
18 # Extracted from six
19 def with_metaclass(meta, *bases):
20 class metaclass(type):
21 def __new__(cls, name, this_bases, d):
22 return meta(name, bases, d)
23
24 return type.__new__(metaclass, "temporary_class", (), {})
25
26
27
28 class OrgMeta(ModelBase):
29 """
30 Base metaclass for dynamically linking related organization models.
31
32 This is particularly useful for custom organizations that can avoid
33 multitable inheritance and also add additional attributes to the
34 organization users especially.
35
36 The `module_registry` dictionary is used to track the architecture across
37 different Django apps. If more than one application makes use of these
38 base models, the extended models will share class relationships, which is
39 clearly undesirable. This ensures that the relationships between models
40 within a module using these base classes are from other organization models.
41
42 """
43
44 module_registry = {}
45
46 def __new__(cls, name, bases, attrs): # noqa
47 # Borrowed from Django-polymorphic
48 # Workaround compatibility issue with with_metaclass() and custom
49 # Django model metaclasses:
50 if not attrs and name == "NewBase":
51 return super(OrgMeta, cls).__new__(cls, name, bases, attrs)
52
53 base_classes = ["OrgModel", "OrgUserModel", "OrgOwnerModel", "OrgInviteModel"]
54 model = super(OrgMeta, cls).__new__(cls, name, bases, attrs)
55 module = model.__module__
56 if not cls.module_registry.get(module):
57 cls.module_registry[module] = {
58 "OrgModel": None,
59 "OrgUserModel": None,
60 "OrgOwnerModel": None,
61 "OrgInviteModel": None,
62 }
63 for b in bases:
64 key = None
65 if b.__name__ in ["AbstractOrganization", "OrganizationBase"]:
66 key = "OrgModel"
67 elif b.__name__ in ["AbstractOrganizationUser", "OrganizationUserBase"]:
68 key = "OrgUserModel"
69 elif b.__name__ in ["AbstractOrganizationOwner", "OrganizationOwnerBase"]:
70 key = "OrgOwnerModel"
71 elif b.__name__ in [
72 "AbstractOrganizationInvitation",
73 "OrganizationInvitationBase",
74 ]:
75 key = "OrgInviteModel"
76 if key:
77 cls.module_registry[module][key] = model
78
79 if all([cls.module_registry[module][klass] for klass in base_classes]):
80 model.update_org(module)
81 model.update_org_users(module)
82 model.update_org_owner(module)
83 model.update_org_invite(module)
84
85 return model
86
87 def update_org(cls, module):
88 """
89 Adds the `users` field to the organization model
90 """
91 try:
92 cls.module_registry[module]["OrgModel"]._meta.get_field("users")
93 except FieldDoesNotExist:
94 cls.module_registry[module]["OrgModel"].add_to_class(
95 "users",
96 models.ManyToManyField(
97 USER_MODEL,
98 through=cls.module_registry[module]["OrgUserModel"].__name__,
99 related_name="%(app_label)s_%(class)s",
100 ),
101 )
102
103 cls.module_registry[module]["OrgModel"].invitation_model = cls.module_registry[
104 module
105 ]["OrgInviteModel"]
106
107 def update_org_users(cls, module):
108 """
109 Adds the `user` field to the organization user model and the link to
110 the specific organization model.
111 """
112 try:
113 cls.module_registry[module]["OrgUserModel"]._meta.get_field("user")
114 except FieldDoesNotExist:
115 cls.module_registry[module]["OrgUserModel"].add_to_class(
116 "user",
117 models.ForeignKey(
118 USER_MODEL,
119 related_name="%(app_label)s_%(class)s",
120 on_delete=models.CASCADE,
121 ),
122 )
123 try:
124 cls.module_registry[module]["OrgUserModel"]._meta.get_field("organization")
125 except FieldDoesNotExist:
126 cls.module_registry[module]["OrgUserModel"].add_to_class(
127 "organization",
128 models.ForeignKey(
129 cls.module_registry[module]["OrgModel"],
130 related_name="organization_users",
131 on_delete=models.CASCADE,
132 ),
133 )
134
135 def update_org_owner(cls, module):
136 """
137 Creates the links to the organization and organization user for the owner.
138 """
139 try:
140 cls.module_registry[module]["OrgOwnerModel"]._meta.get_field(
141 "organization_user"
142 )
143 except FieldDoesNotExist:
144 cls.module_registry[module]["OrgOwnerModel"].add_to_class(
145 "organization_user",
146 models.OneToOneField(
147 cls.module_registry[module]["OrgUserModel"],
148 on_delete=models.CASCADE,
149 ),
150 )
151 try:
152 cls.module_registry[module]["OrgOwnerModel"]._meta.get_field("organization")
153 except FieldDoesNotExist:
154 cls.module_registry[module]["OrgOwnerModel"].add_to_class(
155 "organization",
156 models.OneToOneField(
157 cls.module_registry[module]["OrgModel"],
158 related_name="owner",
159 on_delete=models.CASCADE,
160 ),
161 )
162
163 def update_org_invite(cls, module):
164 """
165 Adds the links to the organization and to the organization user
166 """
167 try:
168 cls.module_registry[module]["OrgInviteModel"]._meta.get_field("invited_by")
169 except FieldDoesNotExist:
170 cls.module_registry[module]["OrgInviteModel"].add_to_class(
171 "invited_by",
172 models.ForeignKey(
173 USER_MODEL,
174 related_name="%(app_label)s_%(class)s_sent_invitations",
175 on_delete=models.CASCADE,
176 ),
177 )
178 try:
179 cls.module_registry[module]["OrgInviteModel"]._meta.get_field("invitee")
180 except FieldDoesNotExist:
181 cls.module_registry[module]["OrgInviteModel"].add_to_class(
182 "invitee",
183 models.ForeignKey(
184 USER_MODEL,
185 null=True,
186 blank=True,
187 related_name="%(app_label)s_%(class)s_invitations",
188 on_delete=models.CASCADE,
189 ),
190 )
191 try:
192 cls.module_registry[module]["OrgInviteModel"]._meta.get_field(
193 "organization"
194 )
195 except FieldDoesNotExist:
196 cls.module_registry[module]["OrgInviteModel"].add_to_class(
197 "organization",
198 models.ForeignKey(
199 cls.module_registry[module]["OrgModel"],
200 related_name="organization_invites",
201 on_delete=models.CASCADE,
202 ),
203 )
204
205
206 class AbstractBaseOrganization(models.Model):
207 """
208 The umbrella object with which users can be associated.
209
210 An organization can have multiple users but only one who can be designated
211 the owner user.
212 """
213
214 name = models.CharField(max_length=200, help_text=_("The name of the organization"))
215 is_active = models.BooleanField(default=True)
216
217 objects = OrgManager()
218 active = ActiveOrgManager()
219
220 class Meta:
221 abstract = True
222 ordering = ["name"]
223
224 def __str__(self):
225 return self.name
226
227 @property
228 def user_relation_name(self):
229 """
230 Returns the string name of the related name to the user.
231
232 This provides a consistent interface across different organization
233 model classes.
234 """
235 return "{0}_{1}".format(
236 self._meta.app_label.lower(), self.__class__.__name__.lower()
237 )
238
239 def is_member(self, user):
240 return True if user in self.users.all() else False
241
242
243 class OrganizationBase(with_metaclass(OrgMeta, AbstractBaseOrganization)):
244 class Meta(AbstractBaseOrganization.Meta):
245 abstract = True
246
247 @property
248 def _org_user_model(self):
249 return self.__class__.module_registry[self.__class__.__module__]["OrgUserModel"]
250
251 def add_user(self, user, **kwargs):
252 org_user = self._org_user_model.objects.create(
253 user=user, organization=self, **kwargs
254 )
255 signals.user_added.send(sender=self, user=user)
256 return org_user
257
258
259 class AbstractBaseOrganizationUser(models.Model):
260 """
261 ManyToMany through field relating Users to Organizations.
262
263 It is possible for a User to be a member of multiple organizations, so this
264 class relates the OrganizationUser to the User model using a ForeignKey
265 relationship, rather than a OneToOne relationship.
266
267 Authentication and general user information is handled by the User class
268 and the contrib.auth application.
269 """
270
271 class Meta:
272 abstract = True
273 ordering = ["organization", "user"]
274 unique_together = ("user", "organization")
275
276 def __str__(self):
277 return "{name} {org}".format(
278 name=self.name if self.user.is_active else self.user.email,
279 org=self.organization.name,
280 )
281
282 @property
283 def name(self):
284 """
285 Returns the connected user's full name or string representation if the
286 full name method is unavailable (e.g. on a custom user class).
287 """
288 try:
289 return self.user.get_full_name()
290 except AttributeError:
291 return str(self.user)
292
293
294 class OrganizationUserBase(with_metaclass(OrgMeta, AbstractBaseOrganizationUser)):
295 class Meta(AbstractBaseOrganizationUser.Meta):
296 abstract = True
297
298
299 class AbstractBaseOrganizationOwner(models.Model):
300 """
301 Each organization must have one and only one organization owner.
302 """
303
304 class Meta:
305 abstract = True
306
307 def __str__(self):
308 return "{0}: {1}".format(self.organization, self.organization_user)
309
310
311 class OrganizationOwnerBase(with_metaclass(OrgMeta, AbstractBaseOrganizationOwner)):
312 class Meta(AbstractBaseOrganizationOwner.Meta):
313 abstract = True
314
315
316 class AbstractBaseInvitation(models.Model):
317 """
318 Tracks invitations to organizations
319
320 This tracks *users* specifically, rather than OrganizationUsers, as it's
321 considered *more critical* to know who invited or joined even if they
322 are no longer members of the organization.
323 """
324
325 guid = models.UUIDField(editable=False)
326 invitee_identifier = models.CharField(
327 max_length=1000,
328 help_text=_(
329 "The contact identifier for the invitee, email, phone number, social media handle, etc."
330 ),
331 )
332
333 class Meta:
334 abstract = True
335
336 def __str__(self):
337 return "{0}: {1}".format(self.organization, self.invitee_identifier)
338
339 def save(self, **kwargs):
340 if not self.guid:
341 self.guid = str(uuid.uuid4())
342 return super().save(**kwargs)
343
344 def get_absolute_url(self):
345 """Returns the invitation URL"""
346 return reverse("invitations_register", kwargs={"guid": self.guid})
347
348 def activation_kwargs(self):
349 """Override this to add kwargs to add_user on activation"""
350 return {}
351
352 def activate(self, user):
353 """
354 Updates the `invitee` value and saves the instance
355
356 Provided as a way of extending the behavior.
357
358 Args:
359 user: the newly created user
360
361 Returns:
362 the linking organization user
363
364 """
365 org_user = self.organization.add_user(user, **self.activation_kwargs())
366 self.invitee = user
367 self.save()
368 return org_user
369
370 def invitation_token(self):
371 """
372 Returns a unique token for the user
373
374 Hash based on identification, account id, time invitited, and secret key of site
375 """
376 raise NotImplementedError
377
378
379 class OrganizationInvitationBase(with_metaclass(OrgMeta, AbstractBaseInvitation)):
380 class Meta(AbstractBaseInvitation.Meta):
381 abstract = True