如何在FastAPI中仅为创建者设置编辑/删除权限
教育信息权限控制修复方案
问题与需求
- 需求:仅允许教育信息的创建者(对应数据中的
user_id用户)对自己的教育信息执行编辑、删除操作 - 当前问题:前端任意用户无需权限即可修改/删除任意教育信息,UUID防ID猜测无法解决权限校验缺失的核心问题
核心问题分析
现有的update_user_education接口完全缺失权限校验逻辑——只要能拿到教育信息的UUID,不管是谁都能修改,根本没验证操作人是否是信息的所有者。
修复步骤
1. 优化创建接口(可选但推荐)
创建教育信息时,直接绑定当前登录用户的ID,避免恶意用户伪造他人的教育信息:
def create_user_education(request: schemas.StudentEducation, db: Session, current_user = Depends(oauth2.get_current_user)): try: uid = str(uuid.uuid4().hex) new_education = My_Education( id=uid, user_id=current_user.id, # 强制使用当前登录用户ID,不再从请求体取 institute=request.institute, website=request.website, country=request.country, city=request.city, degree=request.degree, start_date=request.start_date + timedelta(hours=+6), end_date=request.end_date + timedelta(hours=+6), description=request.description ) db.add(new_education) db.commit() db.refresh(new_education) return {properties.create_message} except SQLAlchemyError: raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=properties.error_message)
2. 修复更新接口的权限校验
在更新前先验证操作人是否是该教育信息的所有者:
def update_user_education(id: str, request: schemas.StudentEducation, db: Session, current_user = Depends(oauth2.get_current_user)): try: # 同时过滤ID和用户ID,只查询当前用户拥有的教育信息 education = db.query(My_Education).filter( My_Education.id == id, My_Education.user_id == current_user.id ).first() if not education: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"教育信息ID {id}不存在或您无权限操作" ) # 更新时禁止修改user_id,防止篡改归属 update_data = { 'institute': request.institute, 'website': request.website, 'country': request.country, 'city': request.city, 'degree': request.degree, 'start_date': request.start_date + timedelta(hours=+6), 'end_date': request.end_date + timedelta(hours=+6), 'description': request.description } db.query(My_Education).filter(My_Education.id == id).update(update_data) db.commit() return {properties.update_message} except SQLAlchemyError: raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=properties.error_message)
3. 删除接口的权限校验(同理)
如果有删除接口,同样添加所有者校验:
def delete_user_education(id: str, db: Session, current_user = Depends(oauth2.get_current_user)): try: education = db.query(My_Education).filter( My_Education.id == id, My_Education.user_id == current_user.id ).first() if not education: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"教育信息ID {id}不存在或您无权限操作" ) db.delete(education) db.commit() return {properties.delete_message} except SQLAlchemyError: raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=properties.error_message)
关键逻辑说明
- 所有修改/删除接口必须先校验:当前登录用户的
user_id与目标教育信息的user_id完全一致 - 创建接口强制绑定当前用户ID,从源头避免归属错误
- 更新时禁止修改
user_id,防止用户篡改教育信息的所有者
内容的提问来源于stack exchange,提问作者Soumick Apon
相关产品推荐
相关产品推荐

