fix: 修复 HTTPBearer 返回 422 错误的问题
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
- 设置 HTTPBearer(auto_error=False) 避免验证错误 - 在 get_current_user 中手动检查并返回 401
This commit is contained in:
@@ -22,7 +22,7 @@ from ..models.tenant_app import TenantApp
|
|||||||
from ..models.tenant_wechat_app import TenantWechatApp
|
from ..models.tenant_wechat_app import TenantWechatApp
|
||||||
|
|
||||||
router = APIRouter(prefix="/auth", tags=["认证"])
|
router = APIRouter(prefix="/auth", tags=["认证"])
|
||||||
security = HTTPBearer()
|
security = HTTPBearer(auto_error=False)
|
||||||
|
|
||||||
|
|
||||||
class LoginRequest(BaseModel):
|
class LoginRequest(BaseModel):
|
||||||
@@ -48,24 +48,33 @@ class ChangePasswordRequest(BaseModel):
|
|||||||
# 权限依赖
|
# 权限依赖
|
||||||
|
|
||||||
async def get_current_user(
|
async def get_current_user(
|
||||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
|
||||||
db: Session = Depends(get_db)
|
db: Session = Depends(get_db)
|
||||||
) -> User:
|
) -> User:
|
||||||
"""获取当前用户"""
|
"""获取当前用户"""
|
||||||
|
if not credentials:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="需要登录认证",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"}
|
||||||
|
)
|
||||||
|
|
||||||
token = credentials.credentials
|
token = credentials.credentials
|
||||||
token_data = decode_token(token)
|
token_data = decode_token(token)
|
||||||
|
|
||||||
if not token_data:
|
if not token_data:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
detail="Token 无效或已过期"
|
detail="Token 无效或已过期",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"}
|
||||||
)
|
)
|
||||||
|
|
||||||
user = db.query(User).filter(User.id == token_data.user_id).first()
|
user = db.query(User).filter(User.id == token_data.user_id).first()
|
||||||
if not user or user.status != 1:
|
if not user or user.status != 1:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
detail="用户不存在或已禁用"
|
detail="用户不存在或已禁用",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"}
|
||||||
)
|
)
|
||||||
|
|
||||||
return user
|
return user
|
||||||
|
|||||||
Reference in New Issue
Block a user