api.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 (
  6. OpenIDConnectOAuth2Adapter,
  7. )
  8. from asgiref.sync import sync_to_async
  9. from django.conf import settings
  10. from django.contrib.auth import aget_user
  11. from django.http import HttpRequest
  12. from ninja import Field, ModelSchema, NinjaAPI, Schema
  13. from ninja.errors import ValidationError
  14. from sentry_sdk import capture_exception, set_context, set_level
  15. from apps.alerts.api import router as alerts_router
  16. from apps.api_tokens.api import router as api_tokens_router
  17. from apps.api_tokens.models import APIToken
  18. from apps.api_tokens.schema import APITokenSchema
  19. from apps.environments.api import router as environments_router
  20. from apps.event_ingest.api import router as event_ingest_router
  21. from apps.event_ingest.embed_api import router as embed_router
  22. from apps.files.api import router as files_router
  23. from apps.importer.api import router as importer_router
  24. from apps.issue_events.api import router as issue_events_router
  25. from apps.organizations_ext.api import router as organizations_ext_router
  26. from apps.projects.api import router as projects_router
  27. from apps.releases.api import router as releases_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 EnvelopeParser
  41. try:
  42. from djstripe.settings import djstripe_settings
  43. except ImportError:
  44. pass
  45. logger = logging.getLogger(__name__)
  46. api = NinjaAPI(
  47. parser=EnvelopeParser(),
  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", environments_router)
  56. api.add_router("0", files_router)
  57. api.add_router("0", importer_router)
  58. api.add_router("0", issue_events_router)
  59. api.add_router("0", organizations_ext_router)
  60. api.add_router("0", projects_router)
  61. api.add_router("0", stats_router)
  62. api.add_router("0", teams_router)
  63. api.add_router("0", uptime_router)
  64. api.add_router("0", users_router)
  65. api.add_router("0", wizard_router)
  66. api.add_router("0", releases_router)
  67. api.add_router("embed", embed_router)
  68. # Would be better at the router level
  69. # https://github.com/vitalik/django-ninja/issues/442
  70. @api.exception_handler(ValidationError)
  71. def log_validation(request, exc):
  72. if request.resolver_match.route == "api/<project_id>/envelope/":
  73. set_level("warning")
  74. set_context(
  75. "incoming event", [orjson.loads(line) for line in request.body.splitlines()]
  76. )
  77. capture_exception(exc)
  78. logger.warning(f"Validation error on {request.path}", exc_info=exc)
  79. return api.create_response(request, {"detail": exc.errors}, status=422)
  80. @api.exception_handler(ThrottleException)
  81. def throttled(request: HttpRequest, exc: ThrottleException):
  82. response = api.create_response(
  83. request,
  84. {"message": "Please retry later"},
  85. status=429,
  86. )
  87. if retry_after := exc.retry_after:
  88. if isinstance(retry_after, int):
  89. response["Retry-After"] = retry_after
  90. else:
  91. response["Retry-After"] = retry_after.strftime("%a, %d %b %Y %H:%M:%S GMT")
  92. return response
  93. class SocialAppSchema(ModelSchema):
  94. scopes: list[str]
  95. authorize_url: Optional[str]
  96. class Config:
  97. model = SocialApp
  98. model_fields = ["name", "client_id", "provider"]
  99. class SettingsOut(CamelSchema):
  100. social_apps: list[SocialAppSchema]
  101. billing_enabled: bool
  102. i_paid_for_glitchtip: bool = Field(serialization_alias="iPaidForGlitchTip")
  103. enable_user_registration: bool
  104. enable_organization_creation: bool
  105. stripe_public_key: Optional[str]
  106. plausible_url: Optional[str]
  107. plausible_domain: Optional[str]
  108. chatwoot_website_token: Optional[str]
  109. sentryDSN: Optional[str]
  110. sentry_traces_sample_rate: Optional[float]
  111. environment: Optional[str]
  112. version: str
  113. server_time_zone: str
  114. @api.get("settings/", response=SettingsOut, by_alias=True, auth=None)
  115. async def get_settings(request: HttpRequest):
  116. social_apps: list[SocialApp] = []
  117. async for social_app in SocialApp.objects.order_by("name"):
  118. provider = social_app.get_provider(request)
  119. social_app.scopes = provider.get_scope()
  120. adapter_cls = SOCIAL_ADAPTER_MAP.get(social_app.provider)
  121. if adapter_cls == OpenIDConnectOAuth2Adapter:
  122. adapter = adapter_cls(request, social_app.provider_id)
  123. elif adapter_cls:
  124. adapter = adapter_cls(request)
  125. else:
  126. adapter = None
  127. if adapter:
  128. social_app.authorize_url = await sync_to_async(
  129. lambda: adapter.authorize_url
  130. )()
  131. social_app.provider = social_app.provider_id or social_app.provider
  132. social_apps.append(social_app)
  133. billing_enabled = settings.BILLING_ENABLED
  134. return {
  135. "social_apps": social_apps,
  136. "billing_enabled": billing_enabled,
  137. "i_paid_for_glitchtip": settings.I_PAID_FOR_GLITCHTIP,
  138. "enable_user_registration": await ais_user_registration_open(),
  139. "enable_organization_creation": settings.ENABLE_ORGANIZATION_CREATION,
  140. "stripe_public_key": djstripe_settings.STRIPE_PUBLIC_KEY
  141. if billing_enabled
  142. else None,
  143. "plausible_url": settings.PLAUSIBLE_URL,
  144. "plausible_domain": settings.PLAUSIBLE_DOMAIN,
  145. "chatwoot_website_token": settings.CHATWOOT_WEBSITE_TOKEN,
  146. "sentryDSN": settings.SENTRY_FRONTEND_DSN,
  147. "sentry_traces_sample_rate": settings.SENTRY_TRACES_SAMPLE_RATE,
  148. "environment": settings.ENVIRONMENT,
  149. "version": settings.GLITCHTIP_VERSION,
  150. "server_time_zone": settings.TIME_ZONE,
  151. }
  152. class APIRootSchema(Schema):
  153. version: str
  154. user: Optional[UserSchema]
  155. auth: Optional[APITokenSchema]
  156. @api.get("0/", auth=None, response=APIRootSchema)
  157. async def api_root(request: HttpRequest):
  158. """/api/0/ gives information about the server and current user"""
  159. user_data = None
  160. auth_data = None
  161. user = await aget_user(request)
  162. if user.is_authenticated:
  163. user_data = await User.objects.prefetch_related("socialaccount_set").aget(
  164. id=user.id
  165. )
  166. # Fetch api auth header to get api token
  167. openapi_scheme = "bearer"
  168. header = "Authorization"
  169. headers = request.headers
  170. auth_value = headers.get(header)
  171. if auth_value:
  172. parts = auth_value.split(" ")
  173. if len(parts) >= 2 and parts[0].lower() == openapi_scheme:
  174. token = " ".join(parts[1:])
  175. api_token = await APIToken.objects.filter(
  176. token=token, user__is_active=True
  177. ).afirst()
  178. if api_token:
  179. auth_data = api_token
  180. user_data = await User.objects.prefetch_related(
  181. "socialaccount_set"
  182. ).aget(id=api_token.user_id)
  183. return {
  184. "version": "0",
  185. "user": user_data,
  186. "auth": auth_data,
  187. }