models.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. from django.db import models
  2. from django.db.models import Count, F, OuterRef, Q, Subquery, Sum
  3. from django.db.models.functions import Coalesce
  4. from django.utils.text import slugify
  5. from django.utils.translation import gettext_lazy as _
  6. from organizations.abstract import SharedBaseModel
  7. from organizations.base import (
  8. OrganizationBase,
  9. OrganizationInvitationBase,
  10. OrganizationOwnerBase,
  11. OrganizationUserBase,
  12. )
  13. from organizations.fields import SlugField
  14. from organizations.managers import OrgManager
  15. from organizations.signals import user_added
  16. from projects.models import Project
  17. # Defines which scopes belong to which role
  18. # Credit to sentry/conf/server.py
  19. ROLES = (
  20. {
  21. "id": "member",
  22. "name": "Member",
  23. "desc": "Members can view and act on events, as well as view most other data within the organization.",
  24. "scopes": set(
  25. [
  26. "event:read",
  27. "event:write",
  28. "event:admin",
  29. "project:releases",
  30. "project:read",
  31. "org:read",
  32. "member:read",
  33. "team:read",
  34. ]
  35. ),
  36. },
  37. {
  38. "id": "admin",
  39. "name": "Admin",
  40. "desc": "Admin privileges on any teams of which they're a member. They can create new teams and projects, as well as remove teams and projects which they already hold membership on (or all teams, if open membership is on). Additionally, they can manage memberships of teams that they are members of.",
  41. "scopes": set(
  42. [
  43. "event:read",
  44. "event:write",
  45. "event:admin",
  46. "org:read",
  47. "member:read",
  48. "project:read",
  49. "project:write",
  50. "project:admin",
  51. "project:releases",
  52. "team:read",
  53. "team:write",
  54. "team:admin",
  55. "org:integrations",
  56. ]
  57. ),
  58. },
  59. {
  60. "id": "manager",
  61. "name": "Manager",
  62. "desc": "Gains admin access on all teams as well as the ability to add and remove members.",
  63. "is_global": True,
  64. "scopes": set(
  65. [
  66. "event:read",
  67. "event:write",
  68. "event:admin",
  69. "member:read",
  70. "member:write",
  71. "member:admin",
  72. "project:read",
  73. "project:write",
  74. "project:admin",
  75. "project:releases",
  76. "team:read",
  77. "team:write",
  78. "team:admin",
  79. "org:read",
  80. "org:write",
  81. "org:integrations",
  82. ]
  83. ),
  84. },
  85. {
  86. "id": "owner",
  87. "name": "Organization Owner",
  88. "desc": "Unrestricted access to the organization, its data, and its settings. Can add, modify, and delete projects and members, as well as make billing and plan changes.",
  89. "is_global": True,
  90. "scopes": set(
  91. [
  92. "org:read",
  93. "org:write",
  94. "org:admin",
  95. "org:integrations",
  96. "member:read",
  97. "member:write",
  98. "member:admin",
  99. "team:read",
  100. "team:write",
  101. "team:admin",
  102. "project:read",
  103. "project:write",
  104. "project:admin",
  105. "project:releases",
  106. "event:read",
  107. "event:write",
  108. "event:admin",
  109. ]
  110. ),
  111. },
  112. )
  113. class OrganizationUserRole(models.IntegerChoices):
  114. MEMBER = 0, "Member"
  115. ADMIN = 1, "Admin"
  116. MANAGER = 2, "Manager"
  117. OWNER = 3, "Owner" # Many users can be owner but only one primary owner
  118. @classmethod
  119. def from_string(cls, string: str):
  120. for status in cls:
  121. if status.label.lower() == string.lower():
  122. return status
  123. @classmethod
  124. def get_role(cls, role: int):
  125. return ROLES[role]
  126. class OrganizationManager(OrgManager):
  127. def with_event_counts(self, current_period=True):
  128. period_start = "djstripe_customers__subscriptions__current_period_start"
  129. period_end = "djstripe_customers__subscriptions__current_period_end"
  130. projects = Project.objects.filter(organization=OuterRef("pk")).values(
  131. "organization"
  132. )
  133. issue_event_filter = Q()
  134. transaction_event_filter = Q()
  135. dif_file_size_filter = Q()
  136. uptime_check_event_filter = Q()
  137. release_file_filter = Q()
  138. if current_period:
  139. issue_event_filter = Q(
  140. issue__event__created__gte=OuterRef(period_start),
  141. issue__event__created__lt=OuterRef(period_end),
  142. )
  143. transaction_event_filter = Q(
  144. transactiongroup__transactionevent__created__gte=OuterRef(period_start),
  145. transactiongroup__transactionevent__created__lt=OuterRef(period_end),
  146. )
  147. dif_file_size_filter = Q(
  148. debuginformationfile__created__gte=OuterRef(period_start),
  149. debuginformationfile__created__lt=OuterRef(period_end),
  150. )
  151. uptime_check_event_filter = Q(
  152. monitor__checks__created__gte=F(period_start),
  153. monitor__checks__created__lt=F(period_end),
  154. )
  155. release_file_filter = Q(
  156. release__releasefile__created__gte=F(period_start),
  157. release__releasefile__created__lt=F(period_end),
  158. )
  159. total_issue_events = projects.annotate(
  160. total=Count(
  161. "issue__event",
  162. filter=issue_event_filter,
  163. )
  164. ).values("total")
  165. total_transaction_events = projects.annotate(
  166. total=Count(
  167. "transactiongroup__transactionevent",
  168. filter=transaction_event_filter,
  169. )
  170. ).values("total")
  171. total_dif_file_size = projects.annotate(
  172. total=Sum(
  173. "debuginformationfile__file__blob__size", filter=dif_file_size_filter
  174. )
  175. ).values("total")
  176. return self.annotate(
  177. issue_event_count=Coalesce(Subquery(total_issue_events), 0),
  178. transaction_count=Coalesce(Subquery(total_transaction_events), 0),
  179. uptime_check_event_count=Count(
  180. "monitor__checks",
  181. filter=uptime_check_event_filter,
  182. ),
  183. file_size=(
  184. Coalesce(
  185. Sum(
  186. "release__releasefile__file__blob__size",
  187. filter=release_file_filter,
  188. ),
  189. 0,
  190. )
  191. + Coalesce(total_dif_file_size, 0)
  192. )
  193. / 1000000,
  194. total_event_count=F("issue_event_count")
  195. + F("transaction_count")
  196. + F("uptime_check_event_count")
  197. + F("file_size"),
  198. )
  199. class Organization(SharedBaseModel, OrganizationBase):
  200. slug = SlugField(
  201. max_length=200,
  202. blank=False,
  203. editable=True,
  204. populate_from="name",
  205. unique=True,
  206. help_text=_("The name in all lowercase, suitable for URL identification"),
  207. )
  208. is_accepting_events = models.BooleanField(
  209. default=True, help_text="Used for throttling at org level"
  210. )
  211. open_membership = models.BooleanField(
  212. default=True, help_text="Allow any organization member to join any team"
  213. )
  214. scrub_ip_addresses = models.BooleanField(
  215. default=True,
  216. help_text="Default for whether projects should script IP Addresses",
  217. )
  218. objects = OrganizationManager()
  219. def slugify_function(self, content):
  220. reserved_words = [
  221. "login",
  222. "register",
  223. "app",
  224. "profile",
  225. "organizations",
  226. "settings",
  227. "issues",
  228. "performance",
  229. "_health",
  230. "rest-auth",
  231. "api",
  232. "accept",
  233. "stripe",
  234. "admin",
  235. "__debug__",
  236. ]
  237. slug = slugify(content)
  238. if slug in reserved_words:
  239. return slug + "-1"
  240. return slug
  241. def add_user(self, user, role=OrganizationUserRole.MEMBER):
  242. """
  243. Adds a new user and if the first user makes the user an admin and
  244. the owner.
  245. """
  246. users_count = self.users.all().count()
  247. if users_count == 0:
  248. role = OrganizationUserRole.OWNER
  249. org_user = self._org_user_model.objects.create(
  250. user=user, organization=self, role=role
  251. )
  252. if users_count == 0:
  253. self._org_owner_model.objects.create(
  254. organization=self, organization_user=org_user
  255. )
  256. # User added signal
  257. user_added.send(sender=self, user=user)
  258. return org_user
  259. @property
  260. def owners(self):
  261. return self.users.filter(
  262. organizations_ext_organizationuser__role=OrganizationUserRole.OWNER
  263. )
  264. @property
  265. def email(self):
  266. """Used to identify billing contact for stripe."""
  267. billing_contact = self.owner.organization_user.user
  268. return billing_contact.email
  269. def get_user_scopes(self, user):
  270. org_user = self.organization_users.get(user=user)
  271. return org_user.get_scopes()
  272. class OrganizationUser(SharedBaseModel, OrganizationUserBase):
  273. user = models.ForeignKey(
  274. "users.User",
  275. blank=True,
  276. null=True,
  277. on_delete=models.CASCADE,
  278. related_name="organizations_ext_organizationuser",
  279. )
  280. role = models.PositiveSmallIntegerField(choices=OrganizationUserRole.choices)
  281. email = models.EmailField(
  282. blank=True, null=True, help_text="Email for pending invite"
  283. )
  284. class Meta(OrganizationOwnerBase.Meta):
  285. unique_together = (("user", "organization"), ("email", "organization"))
  286. def __str__(self, *args, **kwargs):
  287. if self.user:
  288. return super().__str__(*args, **kwargs)
  289. return self.email
  290. def get_email(self):
  291. if self.user:
  292. return self.user.email
  293. return self.email
  294. def get_role(self):
  295. return self.get_role_display().lower()
  296. def get_scopes(self):
  297. role = OrganizationUserRole.get_role(self.role)
  298. return role["scopes"]
  299. def accept_invite(self, user):
  300. self.user = user
  301. self.email = None
  302. self.save()
  303. @property
  304. def pending(self):
  305. return self.user_id is None
  306. @property
  307. def is_active(self):
  308. """Non pending means active"""
  309. return not self.pending
  310. class OrganizationOwner(OrganizationOwnerBase):
  311. """Only usage is for billing contact currently"""
  312. class OrganizationInvitation(OrganizationInvitationBase):
  313. """Required to exist for django-organizations"""