full-stack-fastapi-template icon indicating copy to clipboard operation
full-stack-fastapi-template copied to clipboard

How can I use another deps?

Open yusuke2930 opened this issue 4 years ago • 7 comments

I want to use get_current_client_user like this. but, this is not working.... only reusable_oauth2 is working

from typing import Generator

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt
from pydantic import ValidationError
from sqlalchemy.orm import Session

from app import crud, models, schemas
from app.core import security
from app.core.config import settings
from app.db.session import SessionLocal

reusable_oauth2 = OAuth2PasswordBearer(
    tokenUrl=f"{settings.API_V1_STR}/login/access-token"
)

client_reusable_oauth2 = OAuth2PasswordBearer(
    tokenUrl=f"{settings.API_V1_STR}/client/login/access-token"
)


def get_db() -> Generator:
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()


def get_current_user(
    db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)
) -> models.User:
    try:
        payload = jwt.decode(
            token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
        )
        token_data = schemas.TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    user = crud.user.get(db, id=token_data.sub)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user


def get_current_active_user(
    current_user: models.User = Depends(get_current_user),
) -> models.User:
    if not crud.user.is_active(current_user):
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


def get_current_active_superuser(
    current_user: models.User = Depends(get_current_user),
) -> models.User:
    if not crud.user.is_superuser(current_user):
        raise HTTPException(
            status_code=400, detail="The user doesn't have enough privileges"
        )
    return current_user


def get_current_client_user(
    db: Session = Depends(get_db), token: str = Depends(client_reusable_oauth2)
) -> models.ClientUser:
    try:
        payload = jwt.decode(
            token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
        )
        token_data = schemas.TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    client_user = crud.client_user.get(db, id=token_data.sub)
    if not client_user:
        raise HTTPException(status_code=404, detail="User not found")
    return client_user


def get_current_active_client_user(
    current_user: models.ClientUser = Depends(get_current_client_user),
) -> models.ClientUser:
    if not crud.client_user.is_active(current_user):
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user

yusuke2930 avatar Sep 13 '21 19:09 yusuke2930

It sounds like get_current_user is working, even though I call get_current_client_user

yusuke2930 avatar Sep 14 '21 06:09 yusuke2930

Code seems ok for me, but I only looked at it a little, maybe check what crud.client_user.get is doing?

karolzlot avatar Sep 21 '21 17:09 karolzlot

@karolzlot It is working on development. But authentication is required for get_current_user, not get_current_client_user on Swagger UI. like this スクリーンショット 2021-09-29 13 35 30 .

yusuke2930 avatar Sep 29 '21 04:09 yusuke2930

it would be easier if you show code of example endpoint

karolzlot avatar Sep 29 '21 13:09 karolzlot

@karolzlot Thanks! endpoint here Do you need any other information?


from sqlalchemy.orm import Session
from fastapi import APIRouter, Body, Depends, HTTPException
from app import crud, models, schemas
from app.api import deps


router = APIRouter()

@router.get("/casts", response_model=List[schemas.Cast])
def search_casts(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    current_user: models.ClientUser = Depends(deps.get_current_active_client_user),
) -> Any:
    """
    Retrieve casts.
    """
    scope = current_user.get_rank_scope()
    casts = crud.cast.get_filtered_cast(db, scope=scope, skip=skip, limit=limit)
    return casts

yusuke2930 avatar Sep 30 '21 13:09 yusuke2930

For me it looks ok.

If it still doesn't work then you can make example GitHub repo so this issue can be reproduced. You can remove any code which you don't want to share.

karolzlot avatar Sep 30 '21 16:09 karolzlot

@karolzlot OK,thanks a lot.

yusuke2930 avatar Oct 03 '21 14:10 yusuke2930