diff --git a/inventory-backend/app/api/v1/auth.py b/inventory-backend/app/api/v1/auth.py index c5aafc6..f3265ac 100644 --- a/inventory-backend/app/api/v1/auth.py +++ b/inventory-backend/app/api/v1/auth.py @@ -28,8 +28,11 @@ def login(): return jsonify(response_data), 200 except ValueError as ve: + # [修改] 捕获业务逻辑错误(如密码错误、用户不存在),返回 401 Unauthorized return jsonify({'msg': str(ve)}), 401 + except Exception as e: + # [修改] 捕获系统级错误(如数据库连接失败),返回 500 Internal Server Error current_app.logger.error(f"Login Failed Error: {str(e)}") return jsonify({'msg': f'服务器内部错误: {str(e)}'}), 500 diff --git a/inventory-backend/app/services/auth_service.py b/inventory-backend/app/services/auth_service.py index 82e2b6b..6c24f00 100644 --- a/inventory-backend/app/services/auth_service.py +++ b/inventory-backend/app/services/auth_service.py @@ -30,16 +30,22 @@ class AuthService: 'department': 'System' } else: - raise Exception("密码错误") + # [修改] 使用 ValueError 表示认证失败 + raise ValueError("密码错误") # 2. 如果不是 IRIS,检查数据库用户 else: user = SysUser.query.filter_by(username=username).first() - if not user or not user.check_password(password): - raise Exception("用户名或密码错误") + + # [修改] 分开判断,逻辑更清晰,且使用 ValueError + if not user: + raise ValueError("用户不存在") + + if not user.check_password(password): + raise ValueError("密码错误") if user.status != 'active': - raise Exception("账号已被禁用") + raise ValueError("账号已被禁用,请联系管理员") user_role = user.role user_id = user.id @@ -75,7 +81,7 @@ class AuthService: if role not in valid_roles: raise Exception(f"角色无效,可选角色: {valid_roles}") - # 处理 Email 为空的情况,避免违反 Unique 约束 (视数据库设置而定,这里简单处理为空串) + # 处理 Email 为空的情况 email = data.get('email', '') if email and SysUser.query.filter_by(email=email).first(): raise Exception("邮箱已被使用") diff --git a/inventory-web/src/App.vue b/inventory-web/src/App.vue index 99eacf6..760b6b1 100644 --- a/inventory-web/src/App.vue +++ b/inventory-web/src/App.vue @@ -1,12 +1,19 @@ \ No newline at end of file