api.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import logging
  2. from typing import Optional
  3. import orjson
  4. from allauth.socialaccount.models import SocialApp
  5. from allauth.socialaccount.providers.openid_connect.views import OpenIDConnectAdapter
  6. from asgiref.sync import sync_to_async
  7. from django.conf import settings
  8. from django.http import HttpRequest
  9. from ninja import Field, ModelSchema, NinjaAPI
  10. from ninja.errors import ValidationError
  11. from sentry_sdk import capture_exception, set_context, set_level
  12. from apps.api_tokens.api import router as api_tokens_router
  13. from apps.event_ingest.api import router as event_ingest_router
  14. from apps.event_ingest.embed_api import router as embed_router
  15. from apps.importer.api import router as importer_router
  16. from apps.issue_events.api import router as issue_events_router
  17. from apps.releases.api import router as releases_router
  18. from apps.teams.api import router as teams_router
  19. from apps.users.api import router as users_router
  20. from apps.users.utils import ais_user_registration_open
  21. from glitchtip.constants import SOCIAL_ADAPTER_MAP
  22. from ..schema import CamelSchema
  23. from .authentication import SessionAuth, TokenAuth
  24. from .exceptions import ThrottleException
  25. from .parsers import EnvelopeParser
  26. try:
  27. from djstripe.settings import djstripe_settings
  28. except ImportError:
  29. pass
  30. logger = logging.getLogger(__name__)
  31. api = NinjaAPI(
  32. parser=EnvelopeParser(),
  33. title="GlitchTip API",
  34. urls_namespace="api",
  35. auth=[TokenAuth(), SessionAuth()],
  36. )
  37. api.add_router("0", api_tokens_router)
  38. api.add_router("", event_ingest_router)
  39. api.add_router("0", importer_router)
  40. api.add_router("0", issue_events_router)
  41. api.add_router("0", teams_router)
  42. api.add_router("0", users_router)
  43. api.add_router("0", releases_router)
  44. api.add_router("embed", embed_router)
  45. # Would be better at the router level
  46. # https://github.com/vitalik/django-ninja/issues/442
  47. @api.exception_handler(ValidationError)
  48. def log_validation(request, exc):
  49. if request.resolver_match.route == "api/<project_id>/envelope/":
  50. set_level("warning")
  51. set_context(
  52. "incoming event", [orjson.loads(line) for line in request.body.splitlines()]
  53. )
  54. capture_exception(exc)
  55. logger.warning(f"Validation error on {request.path}", exc_info=exc)
  56. return api.create_response(request, {"detail": exc.errors}, status=422)
  57. @api.exception_handler(ThrottleException)
  58. def throttled(request: HttpRequest, exc: ThrottleException):
  59. response = api.create_response(
  60. request,
  61. {"message": "Please retry later"},
  62. status=429,
  63. )
  64. if retry_after := exc.retry_after:
  65. if isinstance(retry_after, int):
  66. response["Retry-After"] = retry_after
  67. else:
  68. response["Retry-After"] = retry_after.strftime("%a, %d %b %Y %H:%M:%S GMT")
  69. return response
  70. class SocialAppSchema(ModelSchema):
  71. scopes: list[str]
  72. authorize_url: Optional[str]
  73. class Config:
  74. model = SocialApp
  75. model_fields = ["name", "client_id", "provider"]
  76. class SettingsOut(CamelSchema):
  77. social_apps: list[SocialAppSchema]
  78. billing_enabled: bool
  79. i_paid_for_glitchtip: bool = Field(serialization_alias="iPaidForGlitchTip")
  80. enable_user_registration: bool
  81. enable_organization_creation: bool
  82. stripe_public_key: Optional[str]
  83. plausible_url: Optional[str]
  84. plausible_domain: Optional[str]
  85. chatwoot_website_token: Optional[str]
  86. sentryDSN: Optional[str]
  87. sentry_traces_sample_rate: Optional[float]
  88. environment: Optional[str]
  89. version: str
  90. server_time_zone: str
  91. @api.get("settings/", response=SettingsOut, by_alias=True, auth=None)
  92. async def get_settings(request: HttpRequest):
  93. social_apps: list[SocialApp] = []
  94. async for social_app in SocialApp.objects.order_by("name"):
  95. provider = social_app.get_provider(request)
  96. social_app.scopes = provider.get_scope(request)
  97. adapter_cls = SOCIAL_ADAPTER_MAP.get(social_app.provider)
  98. if adapter_cls == OpenIDConnectAdapter:
  99. adapter = adapter_cls(request, social_app.provider_id)
  100. elif adapter_cls:
  101. adapter = adapter_cls(request)
  102. else:
  103. adapter = None
  104. if adapter:
  105. social_app.authorize_url = await sync_to_async(
  106. lambda: adapter.authorize_url
  107. )()
  108. social_app.provider = social_app.provider_id or social_app.provider
  109. social_apps.append(social_app)
  110. billing_enabled = settings.BILLING_ENABLED
  111. return {
  112. "social_apps": social_apps,
  113. "billing_enabled": billing_enabled,
  114. "i_paid_for_glitchtip": settings.I_PAID_FOR_GLITCHTIP,
  115. "enable_user_registration": await ais_user_registration_open(),
  116. "enable_organization_creation": settings.ENABLE_ORGANIZATION_CREATION,
  117. "stripe_public_key": djstripe_settings.STRIPE_PUBLIC_KEY
  118. if billing_enabled
  119. else None,
  120. "plausible_url": settings.PLAUSIBLE_URL,
  121. "plausible_domain": settings.PLAUSIBLE_DOMAIN,
  122. "chatwoot_website_token": settings.CHATWOOT_WEBSITE_TOKEN,
  123. "sentryDSN": settings.SENTRY_FRONTEND_DSN,
  124. "sentry_traces_sample_rate": settings.SENTRY_TRACES_SAMPLE_RATE,
  125. "environment": settings.ENVIRONMENT,
  126. "version": settings.GLITCHTIP_VERSION,
  127. "server_time_zone": settings.TIME_ZONE,
  128. }