api.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import logging
  2. from allauth.socialaccount.models import SocialApp
  3. from allauth.socialaccount.providers.openid_connect.views import (
  4. OpenIDConnectOAuth2Adapter,
  5. )
  6. from asgiref.sync import sync_to_async
  7. from django.conf import settings
  8. from django.contrib.auth import aget_user
  9. from django.http import HttpRequest
  10. from ninja import Field, ModelSchema, NinjaAPI, Schema
  11. from apps.alerts.api import router as alerts_router
  12. from apps.api_tokens.api import router as api_tokens_router
  13. from apps.api_tokens.models import APIToken
  14. from apps.api_tokens.schema import APITokenSchema
  15. from apps.difs.api import router as difs_router
  16. from apps.environments.api import router as environments_router
  17. from apps.event_ingest.api import router as event_ingest_router
  18. from apps.event_ingest.embed_api import router as embed_router
  19. from apps.files.api import router as files_router
  20. from apps.importer.api import router as importer_router
  21. from apps.issue_events.api import router as issue_events_router
  22. from apps.observability.api import router as observability_router
  23. from apps.organizations_ext.api import router as organizations_ext_router
  24. from apps.performance.api import router as performance_router
  25. from apps.projects.api import router as projects_router
  26. from apps.releases.api import router as releases_router
  27. from apps.sourcecode.api import router as sourcecode_router
  28. from apps.stats.api import router as stats_router
  29. from apps.stripe.api import router as stripe_router
  30. from apps.teams.api import router as teams_router
  31. from apps.uptime.api import router as uptime_router
  32. from apps.users.api import router as users_router
  33. from apps.users.models import User
  34. from apps.users.schema import UserSchema
  35. from apps.users.utils import ais_user_registration_open
  36. from apps.wizard.api import router as wizard_router
  37. from glitchtip.constants import SOCIAL_ADAPTER_MAP
  38. from ..schema import CamelSchema
  39. from .authentication import SessionAuth, TokenAuth
  40. from .exceptions import ThrottleException
  41. from .parsers import ORJSONParser
  42. logger = logging.getLogger(__name__)
  43. api = NinjaAPI(
  44. parser=ORJSONParser(),
  45. title="GlitchTip API",
  46. urls_namespace="api",
  47. auth=[TokenAuth(), SessionAuth()],
  48. )
  49. api.add_router("0", api_tokens_router)
  50. api.add_router("", event_ingest_router)
  51. api.add_router("0", alerts_router)
  52. api.add_router("0", difs_router)
  53. api.add_router("0", environments_router)
  54. api.add_router("0", files_router)
  55. api.add_router("0", importer_router)
  56. api.add_router("0", issue_events_router)
  57. api.add_router("0", observability_router)
  58. api.add_router("0", organizations_ext_router)
  59. api.add_router("0", performance_router)
  60. api.add_router("0", projects_router)
  61. api.add_router("0", stats_router)
  62. api.add_router("0/stripe", stripe_router)
  63. api.add_router("0", sourcecode_router)
  64. api.add_router("0", teams_router)
  65. api.add_router("0", uptime_router)
  66. api.add_router("0", users_router)
  67. api.add_router("0", wizard_router)
  68. api.add_router("0", releases_router)
  69. api.add_router("embed", embed_router)
  70. if settings.BILLING_ENABLED:
  71. from apps.djstripe_ext.api import router as djstripe_ext_router
  72. api.add_router("0", djstripe_ext_router)
  73. @api.exception_handler(ThrottleException)
  74. def throttled(request: HttpRequest, exc: ThrottleException):
  75. response = api.create_response(
  76. request,
  77. {"message": "Please retry later"},
  78. status=429,
  79. )
  80. if retry_after := exc.retry_after:
  81. if isinstance(retry_after, int):
  82. response["Retry-After"] = retry_after
  83. else:
  84. response["Retry-After"] = retry_after.strftime("%a, %d %b %Y %H:%M:%S GMT")
  85. return response
  86. class SocialAppSchema(ModelSchema):
  87. scopes: list[str]
  88. authorize_url: str | None
  89. class Config:
  90. model = SocialApp
  91. model_fields = ["name", "client_id", "provider"]
  92. class SettingsOut(CamelSchema):
  93. social_apps: list[SocialAppSchema]
  94. billing_enabled: bool
  95. i_paid_for_glitchtip: bool = Field(alias="iPaidForGlitchTip")
  96. enable_user_registration: bool
  97. enable_organization_creation: bool
  98. stripe_public_key: str | None
  99. plausible_url: str | None
  100. plausible_domain: str | None
  101. chatwoot_website_token: str | None
  102. sentryDSN: str | None
  103. sentry_traces_sample_rate: float | None
  104. environment: str | None
  105. version: str
  106. server_time_zone: str
  107. use_new_social_callbacks: bool
  108. @api.get("settings/", response=SettingsOut, by_alias=True, auth=None)
  109. async def get_settings(request: HttpRequest):
  110. social_apps: list[SocialApp] = []
  111. async for social_app in SocialApp.objects.order_by("name"):
  112. provider = social_app.get_provider(request)
  113. social_app.scopes = provider.get_scope()
  114. adapter_cls = SOCIAL_ADAPTER_MAP.get(social_app.provider)
  115. if adapter_cls == OpenIDConnectOAuth2Adapter:
  116. adapter = adapter_cls(request, social_app.provider_id)
  117. elif adapter_cls:
  118. adapter = adapter_cls(request)
  119. else:
  120. adapter = None
  121. if adapter:
  122. social_app.authorize_url = await sync_to_async(
  123. lambda: adapter.authorize_url
  124. )()
  125. social_app.provider = social_app.provider_id or social_app.provider
  126. social_apps.append(social_app)
  127. billing_enabled = settings.BILLING_ENABLED
  128. return {
  129. "social_apps": social_apps,
  130. "billing_enabled": billing_enabled,
  131. "i_paid_for_glitchtip": settings.I_PAID_FOR_GLITCHTIP,
  132. "enable_user_registration": await ais_user_registration_open(),
  133. "enable_organization_creation": settings.ENABLE_ORGANIZATION_CREATION,
  134. "stripe_public_key": settings.STRIPE_PUBLIC_KEY,
  135. "plausible_url": settings.PLAUSIBLE_URL,
  136. "plausible_domain": settings.PLAUSIBLE_DOMAIN,
  137. "chatwoot_website_token": settings.CHATWOOT_WEBSITE_TOKEN,
  138. "sentryDSN": settings.SENTRY_FRONTEND_DSN,
  139. "sentry_traces_sample_rate": settings.SENTRY_TRACES_SAMPLE_RATE,
  140. "environment": settings.ENVIRONMENT,
  141. "version": settings.GLITCHTIP_VERSION,
  142. "server_time_zone": settings.TIME_ZONE,
  143. "use_new_social_callbacks": settings.USE_NEW_SOCIAL_CALLBACKS,
  144. }
  145. class APIRootSchema(Schema):
  146. version: str
  147. user: UserSchema | None
  148. auth: APITokenSchema | None
  149. @api.get("0/", auth=None, response=APIRootSchema, by_alias=True)
  150. async def api_root(request: HttpRequest):
  151. """/api/0/ gives information about the server and current user"""
  152. user_data = None
  153. auth_data = None
  154. user = await aget_user(request)
  155. if user.is_authenticated:
  156. user_data = await User.objects.prefetch_related("socialaccount_set").aget(
  157. id=user.id
  158. )
  159. # Fetch api auth header to get api token
  160. openapi_scheme = "bearer"
  161. header = "Authorization"
  162. headers = request.headers
  163. auth_value = headers.get(header)
  164. if auth_value:
  165. parts = auth_value.split(" ")
  166. if len(parts) >= 2 and parts[0].lower() == openapi_scheme:
  167. token = " ".join(parts[1:])
  168. api_token = await APIToken.objects.filter(
  169. token=token, user__is_active=True
  170. ).afirst()
  171. if api_token:
  172. auth_data = api_token
  173. user_data = await User.objects.prefetch_related(
  174. "socialaccount_set"
  175. ).aget(id=api_token.user_id)
  176. return {
  177. "version": "0",
  178. "user": user_data,
  179. "auth": auth_data,
  180. }