api.py 7.3 KB

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