models.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. from django.conf import settings
  2. from django.db import models
  3. from django.db.models import F, OuterRef, Q
  4. from django.db.models.functions import Coalesce
  5. from django.utils.text import slugify
  6. from django.utils.translation import gettext_lazy as _
  7. from organizations.abstract import SharedBaseModel
  8. from organizations.base import (
  9. OrganizationBase,
  10. OrganizationInvitationBase,
  11. OrganizationOwnerBase,
  12. OrganizationUserBase,
  13. )
  14. from organizations.fields import SlugField
  15. from organizations.managers import OrgManager
  16. from organizations.signals import user_added
  17. from sql_util.utils import SubqueryCount, SubquerySum
  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. subscription_filter = Q()
  130. event_subscription_filter = Q()
  131. if current_period and settings.BILLING_ENABLED:
  132. subscription_filter = Q(
  133. created__gte=OuterRef(
  134. "djstripe_customers__subscriptions__current_period_start"
  135. ),
  136. created__lt=OuterRef(
  137. "djstripe_customers__subscriptions__current_period_end"
  138. ),
  139. )
  140. event_subscription_filter = Q(
  141. date__gte=OuterRef(
  142. "djstripe_customers__subscriptions__current_period_start"
  143. ),
  144. date__lt=OuterRef(
  145. "djstripe_customers__subscriptions__current_period_end"
  146. ),
  147. )
  148. queryset = self.annotate(
  149. issue_event_count=Coalesce(
  150. SubquerySum(
  151. "projects__eventprojecthourlystatistic__count",
  152. filter=event_subscription_filter,
  153. ),
  154. 0,
  155. ),
  156. transaction_count=SubqueryCount(
  157. "projects__transactiongroup__transactionevent",
  158. filter=subscription_filter,
  159. ),
  160. uptime_check_event_count=SubqueryCount(
  161. "monitor__checks", filter=subscription_filter
  162. ),
  163. file_size=(
  164. Coalesce(
  165. SubquerySum(
  166. "release__releasefile__file__blob__size",
  167. filter=subscription_filter,
  168. ),
  169. 0,
  170. )
  171. + Coalesce(
  172. SubquerySum(
  173. "projects__debuginformationfile__file__blob__size",
  174. filter=subscription_filter,
  175. ),
  176. 0,
  177. )
  178. )
  179. / 1000000,
  180. total_event_count=F("issue_event_count")
  181. + F("transaction_count")
  182. + F("uptime_check_event_count")
  183. + F("file_size"),
  184. )
  185. return queryset.distinct("pk")
  186. class Organization(SharedBaseModel, OrganizationBase):
  187. slug = SlugField(
  188. max_length=200,
  189. blank=False,
  190. editable=True,
  191. populate_from="name",
  192. unique=True,
  193. help_text=_("The name in all lowercase, suitable for URL identification"),
  194. )
  195. is_accepting_events = models.BooleanField(
  196. default=True, help_text="Used for throttling at org level"
  197. )
  198. open_membership = models.BooleanField(
  199. default=True, help_text="Allow any organization member to join any team"
  200. )
  201. scrub_ip_addresses = models.BooleanField(
  202. default=True,
  203. help_text="Default for whether projects should script IP Addresses",
  204. )
  205. objects = OrganizationManager()
  206. def slugify_function(self, content):
  207. reserved_words = [
  208. "login",
  209. "register",
  210. "app",
  211. "profile",
  212. "organizations",
  213. "settings",
  214. "issues",
  215. "performance",
  216. "_health",
  217. "rest-auth",
  218. "api",
  219. "accept",
  220. "stripe",
  221. "admin",
  222. "__debug__",
  223. ]
  224. slug = slugify(content)
  225. if slug in reserved_words:
  226. return slug + "-1"
  227. return slug
  228. def add_user(self, user, role=OrganizationUserRole.MEMBER):
  229. """
  230. Adds a new user and if the first user makes the user an admin and
  231. the owner.
  232. """
  233. users_count = self.users.all().count()
  234. if users_count == 0:
  235. role = OrganizationUserRole.OWNER
  236. org_user = self._org_user_model.objects.create(
  237. user=user, organization=self, role=role
  238. )
  239. if users_count == 0:
  240. self._org_owner_model.objects.create(
  241. organization=self, organization_user=org_user
  242. )
  243. # User added signal
  244. user_added.send(sender=self, user=user)
  245. return org_user
  246. @property
  247. def owners(self):
  248. return self.users.filter(
  249. organizations_ext_organizationuser__role=OrganizationUserRole.OWNER
  250. )
  251. @property
  252. def email(self):
  253. """Used to identify billing contact for stripe."""
  254. billing_contact = self.owner.organization_user.user
  255. return billing_contact.email
  256. def get_user_scopes(self, user):
  257. org_user = self.organization_users.get(user=user)
  258. return org_user.get_scopes()
  259. class OrganizationUser(SharedBaseModel, OrganizationUserBase):
  260. user = models.ForeignKey(
  261. "users.User",
  262. blank=True,
  263. null=True,
  264. on_delete=models.CASCADE,
  265. related_name="organizations_ext_organizationuser",
  266. )
  267. role = models.PositiveSmallIntegerField(choices=OrganizationUserRole.choices)
  268. email = models.EmailField(
  269. blank=True, null=True, help_text="Email for pending invite"
  270. )
  271. class Meta(OrganizationOwnerBase.Meta):
  272. unique_together = (("user", "organization"), ("email", "organization"))
  273. def __str__(self, *args, **kwargs):
  274. if self.user:
  275. return super().__str__(*args, **kwargs)
  276. return self.email
  277. def get_email(self):
  278. if self.user:
  279. return self.user.email
  280. return self.email
  281. def get_role(self):
  282. return self.get_role_display().lower()
  283. def get_scopes(self):
  284. role = OrganizationUserRole.get_role(self.role)
  285. return role["scopes"]
  286. def accept_invite(self, user):
  287. self.user = user
  288. self.email = None
  289. self.save()
  290. @property
  291. def pending(self):
  292. return self.user_id is None
  293. @property
  294. def is_active(self):
  295. """Non pending means active"""
  296. return not self.pending
  297. class OrganizationOwner(OrganizationOwnerBase):
  298. """Only usage is for billing contact currently"""
  299. class OrganizationInvitation(OrganizationInvitationBase):
  300. """Required to exist for django-organizations"""