fix REST API CSRF and auth handling

This commit is contained in:
Nick Sweeting 2024-09-03 14:16:44 -07:00
parent 41a318a8bd
commit 01094ecb03
No known key found for this signature in database
9 changed files with 164 additions and 89 deletions

View file

@ -7,10 +7,10 @@ from django.utils import timezone
from datetime import timedelta
from api.models import APIToken
from api.auth import auth_using_token, auth_using_password
from api.auth import auth_using_token, auth_using_password, get_or_create_api_token
router = Router(tags=['Authentication'])
router = Router(tags=['Authentication'], auth=None)
class PasswordAuthSchema(Schema):
@ -28,14 +28,8 @@ def get_api_token(request, auth_data: PasswordAuthSchema):
)
if user and user.is_superuser:
api_tokens = APIToken.objects.filter(created_by_id=user.pk, expires__gt=timezone.now())
if api_tokens.exists():
api_token = api_tokens.last()
else:
api_token = APIToken.objects.create(created_by_id=user.pk, expires=timezone.now() + timedelta(days=30))
assert api_token.is_valid(), f"API token is not valid {api_token.abid}"
api_token = get_or_create_api_token(user)
assert api_token is not None, "Failed to create API token"
return api_token.__json__()
return {"success": False, "errors": ["Invalid credentials"]}