routes_auth.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. __package__ = 'archivebox.api'
  2. from typing import Optional
  3. from django.contrib.auth import authenticate
  4. from ninja import Router, Schema
  5. from api.models import APIToken
  6. from api.auth import auth_using_token, auth_using_password
  7. router = Router(tags=['Authentication'])
  8. class PasswordAuthSchema(Schema):
  9. """Schema for a /get_api_token request"""
  10. username: Optional[str] = None
  11. password: Optional[str] = None
  12. @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
  13. def get_api_token(request, auth_data: PasswordAuthSchema):
  14. user = auth_using_password(
  15. username=auth_data.username,
  16. password=auth_data.password,
  17. request=request,
  18. )
  19. if user:
  20. # TODO: support multiple tokens in the future, for now we just have one per user
  21. api_token, created = APIToken.objects.get_or_create(user=user)
  22. return api_token.__json__()
  23. return {"success": False, "errors": ["Invalid credentials"]}
  24. class TokenAuthSchema(Schema):
  25. """Schema for a /check_api_token request"""
  26. token: str
  27. @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
  28. def check_api_token(request, token_data: TokenAuthSchema):
  29. user = auth_using_token(
  30. token=token_data.token,
  31. request=request,
  32. )
  33. if user:
  34. return {"success": True, "user_id": str(user.id)}
  35. return {"success": False, "user_id": None}