
Permissions & Ownership: Preventing Unauthorized Access in FastAPI
The Problem Without ownership checks, any logged in user can delete or modify anyone else's data. User A creates an item. User B deletes it. That's a serious security flaw. The Solution : user_id on Every Item class Item(Base): __tablename__ = "items" id = Column(Integer, primary_key=True) name = Column(String, nullable=False) price = Column(Numeric(10, 2), nullable=False) user_id = Column(Integer, ForeignKey("users.id"), nullable=False) When an item is created, the logged in user's ID is automatically saved as the owner. Ownership Check on Delete & Update @app.delete("/items/{item_id}") def delete_item(item_id: int, current_user: dict = Depends(verify_token)): item = db.query(Item).filter(Item.id == item_id).first() if not item: raise HTTPException(status_code=404, detail="Item not found") if item.user_id != current_user["user_id"]: raise HTTPException(status_code=403, detail="Forbidden — you don't own this item") db.delete(item) db.commit() Two checks: Does the item exist? If not → 4
Continue reading on Dev.to Python
Opens in a new tab




