Fix auth dependencies
This commit is contained in:
@@ -1,7 +1,8 @@
|
|||||||
from typing import Optional
|
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 import OAuth2PasswordBearer
|
||||||
|
from fastapi.security.utils import get_authorization_scheme_param
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from app.core.auth import get_token_data, TokenExpiredError, TokenInvalidError
|
from app.core.auth import get_token_data, TokenExpiredError, TokenInvalidError
|
||||||
@@ -109,9 +110,25 @@ def get_current_superuser(
|
|||||||
return current_user
|
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(
|
def get_optional_current_user(
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
token: Optional[str] = Depends(oauth2_scheme)
|
token: Optional[str] = Depends(get_optional_token)
|
||||||
) -> Optional[User]:
|
) -> Optional[User]:
|
||||||
"""
|
"""
|
||||||
Get the current user if authenticated, otherwise return None.
|
Get the current user if authenticated, otherwise return None.
|
||||||
|
|||||||
Reference in New Issue
Block a user