api.py 5.0 KB

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