Fix auth dependencies
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi import Depends, HTTPException, status, Header
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from fastapi.security.utils import get_authorization_scheme_param
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.auth import get_token_data, TokenExpiredError, TokenInvalidError
|
||||
@@ -109,9 +110,25 @@ def get_current_superuser(
|
||||
return current_user
|
||||
|
||||
|
||||
# Define a custom dependency that doesn't raise an exception when no token is provided
|
||||
async def get_optional_token(authorization: str = Header(None)):
|
||||
"""
|
||||
Get the token from the Authorization header without requiring it.
|
||||
Returns None if no token is provided.
|
||||
"""
|
||||
if not authorization:
|
||||
return None
|
||||
|
||||
scheme, token = get_authorization_scheme_param(authorization)
|
||||
if scheme.lower() != "bearer":
|
||||
return None
|
||||
|
||||
return token
|
||||
|
||||
|
||||
def get_optional_current_user(
|
||||
db: Session = Depends(get_db),
|
||||
token: Optional[str] = Depends(oauth2_scheme)
|
||||
token: Optional[str] = Depends(get_optional_token)
|
||||
) -> Optional[User]:
|
||||
"""
|
||||
Get the current user if authenticated, otherwise return None.
|
||||
@@ -134,4 +151,4 @@ def get_optional_current_user(
|
||||
return None
|
||||
return user
|
||||
except (TokenExpiredError, TokenInvalidError):
|
||||
return None
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user