2
0

v1_auth.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. __package__ = 'archivebox.api'
  2. from typing import Optional
  3. from ninja import Router, Schema
  4. from api.models import APIToken
  5. from api.auth import auth_using_token, auth_using_password
  6. router = Router(tags=['Authentication'])
  7. class PasswordAuthSchema(Schema):
  8. """Schema for a /get_api_token request"""
  9. username: Optional[str] = None
  10. password: Optional[str] = None
  11. @router.post("/get_api_token", auth=None, summary='Generate an API token for a given username & password (or currently logged-in user)') # auth=None because they are not authed yet
  12. def get_api_token(request, auth_data: PasswordAuthSchema):
  13. user = auth_using_password(
  14. username=auth_data.username,
  15. password=auth_data.password,
  16. request=request,
  17. )
  18. if user:
  19. # TODO: support multiple tokens in the future, for now we just have one per user
  20. api_token, created = APIToken.objects.get_or_create(created_by_id=user.pk)
  21. return api_token.__json__()
  22. return {"success": False, "errors": ["Invalid credentials"]}
  23. class TokenAuthSchema(Schema):
  24. """Schema for a /check_api_token request"""
  25. token: str
  26. @router.post("/check_api_token", auth=None, summary='Validate an API token to make sure its valid and non-expired') # auth=None because they are not authed yet
  27. def check_api_token(request, token_data: TokenAuthSchema):
  28. user = auth_using_token(
  29. token=token_data.token,
  30. request=request,
  31. )
  32. if user:
  33. return {"success": True, "user_id": str(user.pk)}
  34. return {"success": False, "user_id": None}