v1_auth.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. __package__ = 'archivebox.api'
  2. from typing import Optional
  3. from ninja import Router, Schema
  4. from django.utils import timezone
  5. from datetime import timedelta
  6. from api.models import APIToken
  7. from api.auth import auth_using_token, auth_using_password
  8. router = Router(tags=['Authentication'])
  9. class PasswordAuthSchema(Schema):
  10. """Schema for a /get_api_token request"""
  11. username: Optional[str] = None
  12. password: Optional[str] = None
  13. @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
  14. def get_api_token(request, auth_data: PasswordAuthSchema):
  15. user = auth_using_password(
  16. username=auth_data.username,
  17. password=auth_data.password,
  18. request=request,
  19. )
  20. if user and user.is_superuser:
  21. api_tokens = APIToken.objects.filter(created_by_id=user.pk, expires__gt=timezone.now())
  22. if api_tokens.exists():
  23. api_token = api_tokens.last()
  24. else:
  25. api_token = APIToken.objects.create(created_by_id=user.pk, expires=timezone.now() + timedelta(days=30))
  26. assert api_token.is_valid(), f"API token is not valid {api_token.abid}"
  27. return api_token.__json__()
  28. return {"success": False, "errors": ["Invalid credentials"]}
  29. class TokenAuthSchema(Schema):
  30. """Schema for a /check_api_token request"""
  31. token: str
  32. @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
  33. def check_api_token(request, token_data: TokenAuthSchema):
  34. user = auth_using_token(
  35. token=token_data.token,
  36. request=request,
  37. )
  38. if user:
  39. return {"success": True, "user_id": str(user.pk)}
  40. return {"success": False, "user_id": None}