在 fastAPI 删除方法上设置用户权限时获取 401 Unauthorized

Getting the 401 Unauthorized while setting User permissions on fastAPI delete method

我正在尝试在应用 oAuth2 后使用匹配的 current_user.id 和 owner_id 设置删除权限。当我 print Item.owner_id == current_user.id 它显示了两者的正确 ID,表明所有者和当前用户是同一个人。所以我创建了一个新用户,并仅使用此权限 current_user.is_superuser 授予它超级用户权限,它有效但该功能仅供管理员使用,因此我需要 Item.owner_id == current_user.id 才能工作。

这是我要实现的路线:

@router.delete("/delete/{id}")
def delete_item(id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user_from_token)):
    item = retrieve_item(id=id, db=db)
    if not item:
        return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Item with id {id} not found")
    print(item.owner_id, current_user.id, current_user.is_superuser)
    if item.owner_id == current_user or current_user.is_superuser:
        delete_item_by_id(id=id, db=db, owner_id=current_user.id)
        return {"msg": "Successfully deleted item."}
    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Not permitted")

创建路径如下:

@router.post("/create-item/", response_model=Item)
def create_item(item: CreateItem, db: Session = Depends(get_db), current_user: Vendor = Depends(get_current_user_from_token)):
    item = create_new_item(item=item, db=db, owner_id=current_user.id)
    return item

这是我的函数:

def delete_item_by_id(id: int, db: Session, owner_id):
    existing_item = db.query(Item).filter(Item.id == id)
    if not existing_item.first():
        return 0
    existing_item.delete(synchronize_session=False)

    db.commit()
    return 1

项目class:

class Item(BaseModel):
    name: str
    price: int


    class Config():
        orm_mode = True

用户class:

class User(BaseModel):
    username: str
    email: EmailStr
    is_active: bool

    class Config():
        orm_mode = True

这是项目数据库基础:

class Item(Base):
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, nullable=False)
    price = (Column(Integer, nullable=False))

    is_active = Column(Boolean(), default=True)
    owner_id = Column(Integer, ForeignKey("user.id")
                      )  # watch for this user.id
    owner = relationship("User", back_populates="item")

这是用户数据库基础:

class User(Base):
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, nullable=False)
    email = Column(String, nullable=False, index=True)
    hashed_password = (Column(String, nullable=False))
    is_active = Column(Boolean(), default=True)
    is_superuser = Column(Boolean(), default=False)
    item = relationship("Item", back_populates="owner")

问题在于您比较 item.owner_id == current_user 的 if 条件。你应该比较 item.owner == current_useritem.owner_id == current_user.id