# 工作台认证系统 · 2026-07-29 完整架构

## 三层认证体系

### 1. 飞书环境门控
```javascript
var isInFeishu = /feishu/i.test(navigator.userAgent) || /Lark/i.test(navigator.userAgent);
if (!isInFeishu) {
  // 显示 "请在飞书内打开"，阻断访问
  return;
}
```

### 2. 飞书 OAuth 免登（优先）
当 URL 含 `?code=xxx` 时，浏览器端直接换 token 免密登录：
```javascript
// Step 1: 获取 app_access_token
fetch('https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal', {
  body: JSON.stringify({app_id: APP_ID, app_secret: APP_SECRET})
})
// Step 2: code 换用户身份
fetch('https://open.feishu.cn/open-apis/authen/v1/oidc/access_token', {
  body: JSON.stringify({grant_type: 'authorization_code', code: code}),
  headers: {'Authorization': 'Bearer ' + appAccessToken}
})
// Step 3: 按 name 匹配 user_roles → 自动登录
cbDb.collection('user_roles').where({name: name}).get()
```

⚠️ app_secret 暴露在前端代码中。对于内网工具可接受，生产环境应走云函数。

### 3. 邮箱+密码登录（fallback）
```javascript
cbDb.collection('user_roles').where({email: email}).get().then(function(res) {
  if (user.pwd !== pwd) throw new Error('密码错误');
  if (user.status === '禁用') throw new Error('账户已被禁用');
  finishLogin({name: user.name, role: user.role, dept: user.dept, email, tabs: user.tabs});
});
```

## CloudBase user_roles 集合

### 字段
| 字段 | 类型 | 说明 |
|------|------|------|
| name | string | 中文姓名 |
| email | string | 拼音邮箱 |
| pwd | string | ⚠️ 必须用 pwd，不能用 password（CloudBase 自动屏蔽） |
| role | string | admin / manager / sales |
| dept | string | 部门全称（如 诊断原料销售拓展部） |
| status | string | 在职 / 禁用 |
| tabs | object | {dashboard: true} 控制 Tab 可见性 |

### 权限规则
```json
{"read": "auth != null", "write": "auth != null"}
```

### 初始化
1. CloudBase 控制台 → 开启匿名登录 → 创建 user_roles 集合 → 设权限
2. Chrome 打开 `http://127.0.0.1:8765/工具/init_users.html` → 一键导入 23 人

## 修改密码
```javascript
function doChangePwd() {
  cbDb.collection('user_roles').where({email: email}).get().then(function(res) {
    if (users[0].pwd !== oldPwd) throw ...
    return cbDb.collection('user_roles').doc(users[0]._id).update({pwd: newPwd});
  });
}
```

## 超管页面
- URL: `/admin.html`
- 首次打开自动检测无数据 → 免登录进入初始化模式
- 有数据后 → 需管理员登录
- 功能：增删改查用户、重置密码、禁用/启用

## CloudBase SDK
```
https://static.cloudbase.net/cloudbase-js-sdk/latest/cloudbase.full.js
```
⚠️ 不能用 `imgcache.qq.com` 旧地址——飞书 WebView 加载失败导致白屏。

## 登录失败排查
| 现象 | 可能原因 |
|------|---------|
| 白屏 | SDK CDN 地址错误 |
| 卡在"连接中" | 匿名登录未开启 |
| "邮箱未注册" | user_roles 权限未设 或 用户未导入 |
| 密码错误但密码正确 | 字段名用了 password 而非 pwd |
