I'm struggling to find a decent implementation to return a validated user with class implementation. Previously it worked with simple functions, but I want to refactor this piece. So I added a class and trying to make it work. The problem is it doesn't seem to create a new instance of a class. If I'm trying to do Depends(UserAuthService().test) I'm getting an error
{
"message": "Bad request.",
"details": "'TokenService' object is not callable"
}
router.py
router = APIRouter()
@router.get("/verify")
def verify_user(user: User = Depends(UserAuthService().get_current_valid_user)):
return user
user_auth_service.py
class UserAuthService:
def __init__(self):
self.user_repository = UserRepository()
self.token_service = TokenService()
def get_current_user(self, token: str = Depends(OAUTH2_SCHEME)):
credentials_exception = HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Could not validate the token"
)
user_does_not_exist_exception = HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="User does not exist"
)
try:
payload = self.token_service.decode_access_token(token)
sub: int = payload.get("sub")
if sub is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = self.user_repository.get_user(sub)
if user is None:
raise user_does_not_exist_exception
return User(**user)
def get_current_valid_user(self, user: User = Depends(get_current_user)):
if user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return user
def test(self):
return self.token_service('123456')
P.S. as you can see there's Depends inside class methods, but that's from previous functional implementation.