api.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from django.http import Http404, HttpResponse
  2. from django.shortcuts import aget_object_or_404
  3. from ninja import Router
  4. from ninja.errors import HttpError
  5. from apps.shared.types import MeID
  6. from glitchtip.api.authentication import AuthHttpRequest
  7. from glitchtip.api.pagination import paginate
  8. from .models import User
  9. from .schema import UserIn, UserSchema
  10. router = Router()
  11. """
  12. Sentry OSS does not document any of these, but they exist
  13. GET /users/
  14. GET /users/<me_id>/
  15. DELETE /users/<me_id>/
  16. PUT /users/<me_id>/
  17. GET /organizations/burke-software/users/ (Not implemented)
  18. """
  19. def get_user_queryset(user_id: int):
  20. return User.objects.filter(id=user_id)
  21. @router.get("/users/", response=list[UserSchema])
  22. @paginate
  23. async def list_users(request: AuthHttpRequest, response: HttpResponse):
  24. """
  25. Exists in Sentry OSS, unsure what the use case is
  26. We make it only list the current user
  27. """
  28. return get_user_queryset(user_id=request.auth.user_id)
  29. @router.get("/users/{slug:user_id}/", response=UserSchema)
  30. async def get_user(request: AuthHttpRequest, user_id: MeID):
  31. user_id = request.auth.user_id
  32. return await aget_object_or_404(get_user_queryset(user_id))
  33. @router.delete("/users/{slug:user_id}/", response={204: None})
  34. async def delete_user(request: AuthHttpRequest, user_id: MeID):
  35. # Can only delete self
  36. if user_id != request.auth.user_id and user_id != "me":
  37. raise Http404
  38. user_id = request.auth.user_id
  39. queryset = get_user_queryset(user_id=user_id)
  40. result, _ = await queryset.filter(
  41. organizations_ext_organizationuser__organizationowner__isnull=True
  42. ).adelete()
  43. if result:
  44. return 204, None
  45. if await queryset.aexists():
  46. raise HttpError(
  47. 400,
  48. "User is organization owner. Delete organization or transfer ownership first.",
  49. )
  50. raise Http404
  51. @router.put(
  52. "/users/{slug:user_id}/",
  53. response=UserSchema,
  54. by_alias=True,
  55. )
  56. async def update_user(request: AuthHttpRequest, user_id: MeID, payload: UserIn):
  57. if user_id != request.auth.user_id and user_id != "me":
  58. raise Http404
  59. user_id = request.auth.user_id
  60. user = await aget_object_or_404(get_user_queryset(user_id))
  61. for attr, value in payload.dict().items():
  62. setattr(user, attr, value)
  63. await user.asave()
  64. return user