38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
from fastapi import Depends, HTTPException
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jwt import exceptions
|
|
from starlette import status
|
|
|
|
from bsition.api.utils.jwt import validate_token
|
|
from bsition.backend.redis.tokens import valid_token
|
|
from bsition.backend.postgres.users import get_user_by_username
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/token")
|
|
|
|
|
|
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
try:
|
|
payload = validate_token(token)
|
|
username: str = payload.get("sub")
|
|
if username is None:
|
|
raise credentials_exception
|
|
except exceptions.DecodeError:
|
|
raise credentials_exception
|
|
except exceptions.ExpiredSignatureError:
|
|
raise credentials_exception
|
|
|
|
if not valid_token(token, username):
|
|
print("no es valido!")
|
|
raise credentials_exception
|
|
|
|
user = get_user_by_username(username)
|
|
if user is None:
|
|
raise credentials_exception
|
|
return user
|