api.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. from django.http import Http404, HttpResponse
  2. from ninja import Router
  3. from ninja.pagination import paginate
  4. from glitchtip.api.authentication import AuthHttpRequest, SessionAuth
  5. from .models import APIToken
  6. from .schema import APITokenIn, APITokenSchema
  7. router = Router(auth=SessionAuth())
  8. def get_queryset(request: AuthHttpRequest):
  9. user_id = request.auth.user_id
  10. return APIToken.objects.filter(user_id=user_id)
  11. @router.get("api-tokens/", response=list[APITokenSchema])
  12. @paginate
  13. async def list_api_tokens(request: AuthHttpRequest, response: HttpResponse):
  14. return get_queryset(request)
  15. @router.post("api-tokens/", response={201: APITokenSchema})
  16. async def create_api_token(request: AuthHttpRequest, payload: APITokenIn):
  17. user_id = request.auth.user_id
  18. return await APIToken.objects.acreate(
  19. **payload.dict(exclude_none=True), user_id=user_id
  20. )
  21. @router.delete("api-tokens/{token_id}/", response={204: None})
  22. async def delete_api_token(request: AuthHttpRequest, token_id: int):
  23. result = await get_queryset(request).filter(id=token_id).adelete()
  24. if not result[0]:
  25. raise Http404()
  26. return