Metadata-Version: 2.5
Name: chongming-auth
Version: 0.1.0
Summary: auth 域共享契约：Users 模型 / 建库与 admin 种子 / 登录校验与 JWT 签发（网关内置登录与 auth 插件共用）
Requires-Python: >=3.12
Requires-Dist: chongming-database>=0.2.0
Requires-Dist: chongming-jwt
Requires-Dist: chongming-password
Requires-Dist: orjson>=3.9.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: sqlmodel>=0.0.16
Description-Content-Type: text/markdown

# 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
```
