importer.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import aiohttp
  2. import tablib
  3. from asgiref.sync import sync_to_async
  4. from django.db.models import Q
  5. from django.urls import reverse
  6. from apps.organizations_ext.models import OrganizationUser, OrganizationUserRole
  7. from apps.organizations_ext.resources import (
  8. OrganizationResource,
  9. OrganizationUserResource,
  10. )
  11. from apps.projects.models import Project
  12. from apps.projects.resources import ProjectKeyResource, ProjectResource
  13. from apps.teams.resources import TeamResource
  14. from apps.users.models import User
  15. from apps.users.resources import UserResource
  16. from .exceptions import ImporterException
  17. class GlitchTipImporter:
  18. """
  19. Generic importer tool to use with cli or web
  20. If used by a non server admin, it's important to assume all incoming
  21. JSON is hostile and not from a real GT server. Foreign Key ids could be
  22. faked and used to elevate privileges. Always confirm new data is associated with
  23. appropriate organization. Also assume user is at least an org admin, no need to
  24. double check permissions when creating assets within the organization.
  25. create_users should be False unless running as superuser/management command
  26. """
  27. def __init__(
  28. self, url: str, auth_token: str, organization_slug: str, create_users=False
  29. ):
  30. self.url = url.rstrip("/")
  31. self.headers = {"Authorization": f"Bearer {auth_token}"}
  32. self.create_users = create_users
  33. self.organization_slug = organization_slug
  34. self.organization_id = None
  35. self.organization_url = reverse(
  36. "api:get_organization", args=[self.organization_slug]
  37. )
  38. self.organization_users_url = reverse(
  39. "api:list_organization_members",
  40. kwargs={"organization_slug": self.organization_slug},
  41. )
  42. self.projects_url = reverse(
  43. "api:list_organization_projects", args=[self.organization_slug]
  44. )
  45. self.teams_url = reverse("api:list_teams", args=[self.organization_slug])
  46. async def run(self, organization_id=None):
  47. """Set organization_id to None to import (superuser only)"""
  48. if organization_id is None:
  49. await self.import_organization()
  50. else:
  51. self.organization_id = organization_id
  52. await self.import_organization_users()
  53. await self.import_projects()
  54. await self.import_teams()
  55. async def get(self, url: str):
  56. async with aiohttp.ClientSession() as session:
  57. async with session.get(url, headers=self.headers) as res:
  58. return await res.json()
  59. async def import_organization(self):
  60. resource = OrganizationResource()
  61. data = await self.get(self.url + self.organization_url)
  62. self.organization_id = data["id"] # TODO unsafe for web usage
  63. dataset = tablib.Dataset()
  64. dataset.dict = [data]
  65. await sync_to_async(resource.import_data)(dataset, raise_errors=True)
  66. async def import_organization_users(self):
  67. resource = OrganizationUserResource()
  68. org_users = await self.get(self.url + self.organization_users_url)
  69. if not org_users:
  70. return
  71. if self.create_users:
  72. user_resource = UserResource()
  73. users_list = [
  74. org_user["user"] for org_user in org_users if org_user is not None
  75. ]
  76. users = [
  77. {k: v for k, v in user.items() if k in ["id", "email", "name"]}
  78. for user in users_list
  79. ]
  80. dataset = tablib.Dataset()
  81. dataset.dict = users
  82. await sync_to_async(user_resource.import_data)(dataset, raise_errors=True)
  83. for org_user in org_users:
  84. org_user["organization"] = self.organization_id
  85. org_user["role"] = OrganizationUserRole.from_string(org_user["role"])
  86. if self.create_users:
  87. org_user["user"] = (
  88. User.objects.filter(email=org_user["user"]["email"])
  89. .values_list("pk", flat=True)
  90. .first()
  91. )
  92. else:
  93. org_user["user"] = None
  94. dataset = tablib.Dataset()
  95. dataset.dict = org_users
  96. await sync_to_async(resource.import_data)(dataset, raise_errors=True)
  97. async def import_projects(self):
  98. project_resource = ProjectResource()
  99. project_key_resource = ProjectKeyResource()
  100. projects = await self.get(self.url + self.projects_url)
  101. project_keys = []
  102. for project in projects:
  103. project["organization"] = self.organization_id
  104. keys = await self.get(
  105. self.url
  106. + reverse(
  107. "api:list_project_keys",
  108. args=[self.organization_slug, project["slug"]],
  109. )
  110. )
  111. for key in keys:
  112. key["project"] = project["id"]
  113. key["public_key"] = key["public"]
  114. project_keys += keys
  115. dataset = tablib.Dataset()
  116. dataset.dict = projects
  117. await sync_to_async(project_resource.import_data)(dataset, raise_errors=True)
  118. owned_project_ids = [
  119. pk
  120. async for pk in Project.objects.filter(
  121. organization_id=self.organization_id,
  122. pk__in=[d["projectId"] for d in project_keys],
  123. ).values_list("pk", flat=True)
  124. ]
  125. project_keys = list(
  126. filter(lambda key: key["projectId"] in owned_project_ids, project_keys)
  127. )
  128. dataset.dict = project_keys
  129. await sync_to_async(project_key_resource.import_data)(
  130. dataset, raise_errors=True
  131. )
  132. async def import_teams(self):
  133. resource = TeamResource()
  134. teams = await self.get(self.url + self.teams_url)
  135. for team in teams:
  136. team["organization"] = self.organization_id
  137. team["projects"] = ",".join(
  138. map(
  139. str,
  140. [
  141. pk
  142. async for pk in Project.objects.filter(
  143. organization_id=self.organization_id,
  144. pk__in=[int(d["id"]) for d in team["projects"]],
  145. ).values_list("id", flat=True)
  146. ],
  147. )
  148. )
  149. team_members = await self.get(
  150. self.url
  151. + reverse(
  152. "api:list_team_organization_members",
  153. args=[self.organization_slug, team["slug"]],
  154. )
  155. )
  156. team_member_emails = [d["email"] for d in team_members]
  157. team["members"] = ",".join(
  158. [
  159. str(i)
  160. async for i in OrganizationUser.objects.filter(
  161. organization_id=self.organization_id
  162. )
  163. .filter(
  164. Q(email__in=team_member_emails)
  165. | Q(user__email__in=team_member_emails)
  166. )
  167. .values_list("pk", flat=True)
  168. ]
  169. )
  170. dataset = tablib.Dataset()
  171. dataset.dict = teams
  172. await sync_to_async(resource.import_data)(dataset, raise_errors=True)
  173. async def check_auth(self):
  174. async with aiohttp.ClientSession() as session:
  175. async with session.get(self.url + "/api/0/", headers=self.headers) as res:
  176. data = await res.json()
  177. if res.status != 200 or not data["user"]:
  178. raise ImporterException("Bad auth token")