Files
amq-adapter-python/core/deps.py
T
2025-02-25 20:37:33 +00:00

62 lines
1.9 KiB
Python

from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
#from jose import jwt, JWTError
from pydantic import BaseModel
from schemas.user_schema import UserSchema
from core.auth import oauth2_schema, authenticate
#from core.configs import settings
from core.security import create_password_hash
class TokenData(BaseModel):
userid: Optional[str] = None
async def get_current_user(
token: str = Depends(oauth2_schema)
) -> UserSchema:
credential_exception: HTTPException = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='User provided credentials are not correct.',
headers={"WWW-Authenticate": "Bearer"}
)
try:
#payload = jwt.decode(
# token,
# settings.JWT_SECRET,
# algorithms=[settings.ALGORITHM],
# options={"verify_aud": False}
#)
userid: str = 'user' #payload.get("sub")
if userid is None:
raise credential_exception
token_data: TokenData = TokenData(userid=userid)
except Exception:
raise credential_exception
if int(token_data.userid) != 0:
raise credential_exception
# The returned value at this point should be UserModel, but since we do not have any persistence
# and this is for demo purposes only
return UserSchema(id=token_data.userid, username='user', hash_pass=create_password_hash('user1234'))
security = HTTPBasic()
async def get_current_username(credentials: HTTPBasicCredentials = Depends(security)) -> str:
user = await authenticate(credentials.username, credentials.password)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username