models.py 9.6 KB

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