Files
chongming-auth/README.md
T
2026-09-10 16:30:53 +08:00

54 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# chongming-auth
auth 域共享契约包:网关内置登录与 auth 插件(用户管理)的公共依赖。
两侧不允许互相 import(插件/worker SDK 保持与网关解耦),共享物只放这里。
## 职责拆分(auth 域)
| 部分 | 归属 | 说明 |
| --- | --- | --- |
| Users 模型(唯一权威定义) | 本包 | 禁止在别处重复定义同表模型 |
| 建库 / admin 种子 / 登录校验 / JWT 签发 | 本包 | `store.py` |
| `POST /api/v1/auth/login`(内置登录端点) | 网关核心 `chongming/app/routes/auth.py` | 管理平面可用性底线:auth 插件缩容/故障时登录与 admin API 仍可用 |
| 注册 / 资料 / 改密(用户管理) | auth 插件 `plugins.auth` | 可替换的业务部分,支持 inline/external |
## 稳定契约(改动即破坏性变更)
1. **JWT claims**:`sub / username / email / full_name / avatar_url / phone /
is_verified / is_superuser / created_at / updated_at / last_login_at`,
token 有效期默认 10800s(`DEFAULT_TOKEN_EXPIRES_SECONDS`)。
网关 admin API 依赖 `is_superuser` 判定超管(`worker_admin.py`);
网关 JWT 校验依赖(`core/auth.py`)按 `[security]` 的 secret/algorithm 验签。
2. **登录响应 shape**:`{result, token, message, timestamp}`,失败文案
(`用户名错误` / `密码错误` / `用户已经注销或被禁用`)与前端兼容。
3. **users 表 schema**:对既有 `auth.db`(SQLite)与 PostgreSQL users 表零迁移。
## 数据库定位
与 `chongming_worker.Plugin.init_database` 语义一致:
- 配置含 `database.url`(插件 config.toml 的 `[workers.config.database]`)→ PostgreSQL;
- 否则 SQLite:`data_dir/auth.db`(`[workers.config]` 的 `data_dir`,默认 `./data`)。
网关 lifespan(`setup_auth_store`)与 auth 插件读取同一份配置,指向同一张表。
## 用法
```python
from chongming_auth import open_database, seed_admin, verify_login, issue_token
db = await open_database({"data_dir": "./data"}) # 或 {"database": {"url": "postgresql://..."}}
await seed_admin(db) # 幂等,多进程并发安全
user, message = await verify_login(db, "admin", "admin")
if user is not None:
token = issue_token(user, secret, algorithm)
```
## 开发
```bash
cd utils/auth
uv sync
uv run pytest
```