models.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 owner_changed, 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=Coalesce(
  157. SubquerySum(
  158. "projects__transactioneventprojecthourlystatistic__count",
  159. filter=event_subscription_filter,
  160. ),
  161. 0,
  162. ),
  163. uptime_check_event_count=SubqueryCount(
  164. "monitor__checks", filter=subscription_filter
  165. ),
  166. file_size=(
  167. Coalesce(
  168. SubquerySum(
  169. "release__releasefile__file__blob__size",
  170. filter=subscription_filter,
  171. ),
  172. 0,
  173. )
  174. + Coalesce(
  175. SubquerySum(
  176. "projects__debuginformationfile__file__blob__size",
  177. filter=subscription_filter,
  178. ),
  179. 0,
  180. )
  181. )
  182. / 1000000,
  183. total_event_count=F("issue_event_count")
  184. + F("transaction_count")
  185. + F("uptime_check_event_count")
  186. + F("file_size"),
  187. )
  188. return queryset.distinct("pk")
  189. class Organization(SharedBaseModel, OrganizationBase):
  190. slug = SlugField(
  191. max_length=200,
  192. blank=False,
  193. editable=True,
  194. populate_from="name",
  195. unique=True,
  196. help_text=_("The name in all lowercase, suitable for URL identification"),
  197. )
  198. is_accepting_events = models.BooleanField(
  199. default=True, help_text="Used for throttling at org level"
  200. )
  201. open_membership = models.BooleanField(
  202. default=True, help_text="Allow any organization member to join any team"
  203. )
  204. scrub_ip_addresses = models.BooleanField(
  205. default=True,
  206. help_text="Default for whether projects should script IP Addresses",
  207. )
  208. objects = OrganizationManager()
  209. def slugify_function(self, content):
  210. reserved_words = [
  211. "login",
  212. "register",
  213. "app",
  214. "profile",
  215. "organizations",
  216. "settings",
  217. "issues",
  218. "performance",
  219. "_health",
  220. "rest-auth",
  221. "api",
  222. "accept",
  223. "stripe",
  224. "admin",
  225. "__debug__",
  226. ]
  227. slug = slugify(content)
  228. if slug in reserved_words:
  229. return slug + "-1"
  230. return slug
  231. def add_user(self, user, role=OrganizationUserRole.MEMBER):
  232. """
  233. Adds a new user and if the first user makes the user an admin and
  234. the owner.
  235. """
  236. users_count = self.users.all().count()
  237. if users_count == 0:
  238. role = OrganizationUserRole.OWNER
  239. org_user = self._org_user_model.objects.create(
  240. user=user, organization=self, role=role
  241. )
  242. if users_count == 0:
  243. self._org_owner_model.objects.create(
  244. organization=self, organization_user=org_user
  245. )
  246. # User added signal
  247. user_added.send(sender=self, user=user)
  248. return org_user
  249. @property
  250. def owners(self):
  251. return self.users.filter(
  252. organizations_ext_organizationuser__role=OrganizationUserRole.OWNER
  253. )
  254. @property
  255. def email(self):
  256. """Used to identify billing contact for stripe."""
  257. billing_contact = self.owner.organization_user.user
  258. return billing_contact.email
  259. def get_user_scopes(self, user):
  260. org_user = self.organization_users.get(user=user)
  261. return org_user.get_scopes()
  262. def change_owner(self, new_owner):
  263. """
  264. Changes ownership of an organization.
  265. """
  266. old_owner = self.owner.organization_user
  267. self.owner.organization_user = new_owner
  268. self.owner.save()
  269. owner_changed.send(sender=self, old=old_owner, new=new_owner)
  270. def is_owner(self, user):
  271. """
  272. Returns True is user is the organization's owner, otherwise false
  273. """
  274. return self.owner.organization_user.user == user
  275. class OrganizationUser(SharedBaseModel, OrganizationUserBase):
  276. user = models.ForeignKey(
  277. "users.User",
  278. blank=True,
  279. null=True,
  280. on_delete=models.CASCADE,
  281. related_name="organizations_ext_organizationuser",
  282. )
  283. role = models.PositiveSmallIntegerField(choices=OrganizationUserRole.choices)
  284. email = models.EmailField(
  285. blank=True, null=True, help_text="Email for pending invite"
  286. )
  287. class Meta(OrganizationOwnerBase.Meta):
  288. unique_together = (("user", "organization"), ("email", "organization"))
  289. def __str__(self, *args, **kwargs):
  290. if self.user:
  291. return super().__str__(*args, **kwargs)
  292. return self.email
  293. def get_email(self):
  294. if self.user:
  295. return self.user.email
  296. return self.email
  297. def get_role(self):
  298. return self.get_role_display().lower()
  299. def get_scopes(self):
  300. role = OrganizationUserRole.get_role(self.role)
  301. return role["scopes"]
  302. def accept_invite(self, user):
  303. self.user = user
  304. self.email = None
  305. self.save()
  306. @property
  307. def pending(self):
  308. return self.user_id is None
  309. @property
  310. def is_active(self):
  311. """Non pending means active"""
  312. return not self.pending
  313. class OrganizationOwner(OrganizationOwnerBase):
  314. """Only usage is for billing contact currently"""
  315. class OrganizationInvitation(OrganizationInvitationBase):
  316. """Required to exist for django-organizations"""