feat: Update API token handling to use API-TOKEN header and improve related tests

This commit is contained in:
JSC
2025-07-27 22:15:23 +02:00
parent 3dc21337f9
commit 58030914e6
5 changed files with 80 additions and 85 deletions

View File

@@ -94,26 +94,19 @@ async def get_current_active_user(
async def get_current_user_api_token(
auth_service: Annotated[AuthService, Depends(get_auth_service)],
authorization: Annotated[str | None, Header()] = None,
api_token_header: Annotated[str | None, Header(alias="API-TOKEN")] = None,
) -> User:
"""Get the current authenticated user from API token in Authorization header."""
"""Get the current authenticated user from API token in API-TOKEN header."""
try:
# Check if Authorization header exists
if not authorization:
# Check if API-TOKEN header exists
if not api_token_header:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authorization header required",
detail="API-TOKEN header required",
)
# Check if it's a Bearer token
if not authorization.startswith("Bearer "):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authorization header format",
)
# Extract the API token
api_token = authorization[7:] # Remove "Bearer " prefix
# Use the API token directly
api_token = api_token_header.strip()
if not api_token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -158,12 +151,12 @@ async def get_current_user_api_token(
async def get_current_user_flexible(
auth_service: Annotated[AuthService, Depends(get_auth_service)],
access_token: Annotated[str | None, Cookie()] = None,
authorization: Annotated[str | None, Header()] = None,
api_token_header: Annotated[str | None, Header(alias="API-TOKEN")] = None,
) -> User:
"""Get the current authenticated user from either JWT cookie or API token."""
# Try API token first if Authorization header is present
if authorization:
return await get_current_user_api_token(auth_service, authorization)
# Try API token first if API-TOKEN header is present
if api_token_header:
return await get_current_user_api_token(auth_service, api_token_header)
# Fall back to JWT cookie authentication
return await get_current_user(auth_service, access_token)

View File

@@ -11,7 +11,9 @@ class UserRegisterRequest(BaseModel):
email: EmailStr = Field(..., description="User email address")
password: str = Field(
..., min_length=8, description="User password (minimum 8 characters)",
...,
min_length=8,
description="User password (minimum 8 characters)",
)
name: str = Field(..., min_length=1, max_length=100, description="User full name")
@@ -68,7 +70,7 @@ class ApiTokenResponse(BaseModel):
"""Schema for API token response."""
api_token: str = Field(..., description="Generated API token")
expires_at: datetime = Field(..., description="Token expiration timestamp")
expires_at: datetime | None = Field(None, description="Token expiration timestamp")
class ApiTokenStatusResponse(BaseModel):