importer.py 7.5 KB

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