models.py 11 KB

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