fix API token_auth and CSRF setup

This commit is contained in:
Nick Sweeting 2024-09-03 01:21:13 -07:00
parent 9af260df16
commit c1c55d6da7
No known key found for this signature in database
2 changed files with 12 additions and 5 deletions

View file

@ -30,8 +30,8 @@ def auth_using_token(token, request: Optional[HttpRequest]=None) -> Optional[Abs
if not user: if not user:
print('[❌] Failed to authenticate API user using API Key:', request) print('[❌] Failed to authenticate API user using API Key:', request)
return None return None
return cast(AbstractBaseUser, user)
def auth_using_password(username, password, request: Optional[HttpRequest]=None) -> Optional[AbstractBaseUser]: def auth_using_password(username, password, request: Optional[HttpRequest]=None) -> Optional[AbstractBaseUser]:
"""Given a username and password, check if they are valid and return the corresponding user""" """Given a username and password, check if they are valid and return the corresponding user"""

View file

@ -3,6 +3,8 @@ __package__ = 'archivebox.api'
from typing import Optional from typing import Optional
from ninja import Router, Schema from ninja import Router, Schema
from django.utils import timezone
from datetime import timedelta
from api.models import APIToken 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
@ -25,9 +27,14 @@ def get_api_token(request, auth_data: PasswordAuthSchema):
request=request, request=request,
) )
if user: if user and user.is_superuser:
# TODO: support multiple tokens in the future, for now we just have one per user api_tokens = APIToken.objects.filter(created_by_id=user.pk, expires__gt=timezone.now())
api_token, created = APIToken.objects.get_or_create(created_by_id=user.pk) 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}"
return api_token.__json__() return api_token.__json__()