# OTP 二次验证实现文档 ## 功能概述 为 IT 支持服务台坐席端增加 OTP 二次验证功能: - admin 角色登录时需要输入 Google Authenticator 动态码 - 首次绑定需要验证一次码才启用 - OTP 丢失后需管理员重置 ## 实现方案 ### 1. 后端修改 #### 1.1 安装依赖 ```bash pip install pyotp qrcode[pil] pillow ``` #### 1.2 数据库模型 Agent 模型已有字段: - `otp_secret`: OTP 密钥(Base32编码) - `otp_enabled`: OTP 是否启用(0=否, 1=是) #### 1.3 Schema 修改 文件:`backend/app/schemas/agent.py` - `AgentLogin` 增加 `otp_code` 可选字段 - `AgentResponse` 增加 `otp_enabled` 字段 #### 1.4 API 修改 文件:`backend/app/api/agents.py` 新增接口: - `POST /api/agents/otp-bind` - 生成 OTP 密钥和二维码 - `POST /api/agents/otp-verify` - 验证并启用 OTP - `POST /api/agents/otp-unbind` - 解绑 OTP 登录接口修改: - admin 角色且 otp_enabled=1 时,检查 otp_code - 未提供 otp_code 返回 `require_otp: True` - 验证 OTP 码正确后生成 token ### 2. 前端修改 #### 2.1 坐席端 API 文件:`frontend-agent/src/api/agent.ts` - `login()` 增加 `otpCode` 参数 #### 2.2 坐席端 Store 文件:`frontend-agent/src/stores/agent.ts` - `login()` 增加 `otpCode` 参数 - 返回 `require_otp` 标记让页面处理 #### 2.3 坐席端登录页面 文件:`frontend-agent/src/views/Login.vue` - 增加 OTP 输入框(v-if="requireOtp") - 首次登录返回 require_otp 时显示输入框 - 用户输入 OTP 后再次登录 ## 使用流程 ### 首次绑定 OTP 1. 管理员登录坐席端 2. 调用 `POST /api/agents/otp-bind` 3. 获取二维码和密钥 4. 使用 Google Authenticator 扫描二维码 5. 调用 `POST /api/agents/otp-verify` 输入动态码验证 6. 验证成功,otp_enabled 设为 1 ### 登录流程 1. 用户输入 user_id 和 name 2. 后端检查 admin 角色且 otp_enabled=1 3. 返回 `require_otp: True` 4. 前端显示 OTP 输入框 5. 用户输入 6 位动态码 6. 后端验证通过,生成 token ### 解绑流程 1. 管理员调用 `POST /api/agents/otp-unbind` 2. otp_secret 和 otp_enabled 清空 ## 错误码 | 错误码 | 说明 | |--------|------| | 1006 | OTP 验证码错误 | | 1007 | OTP 绑定失败 | | 1008 | 请先绑定 OTP | | 1009 | OTP 验证失败 | | 1010 | OTP 解绑失败 |