diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py index 48e7bb0..5f7db08 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -22,7 +22,7 @@ from ..models.tenant_app import TenantApp from ..models.tenant_wechat_app import TenantWechatApp router = APIRouter(prefix="/auth", tags=["认证"]) -security = HTTPBearer() +security = HTTPBearer(auto_error=False) class LoginRequest(BaseModel): @@ -48,24 +48,33 @@ class ChangePasswordRequest(BaseModel): # 权限依赖 async def get_current_user( - credentials: HTTPAuthorizationCredentials = Depends(security), + credentials: Optional[HTTPAuthorizationCredentials] = Depends(security), db: Session = Depends(get_db) ) -> User: """获取当前用户""" + if not credentials: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="需要登录认证", + headers={"WWW-Authenticate": "Bearer"} + ) + token = credentials.credentials token_data = decode_token(token) if not token_data: raise HTTPException( 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() if not user or user.status != 1: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="用户不存在或已禁用" + detail="用户不存在或已禁用", + headers={"WWW-Authenticate": "Bearer"} ) return user