Metadata-Version: 2.4
Name: liteauth
Version: 0.1.11
Summary: Python 异步权限认证框架，受 Sa-Token 启发 — 多账号体系、JWT、OAuth2、SSO
Project-URL: Homepage, https://gitee.com/YueXia_1/liteauth
Project-URL: Repository, https://gitee.com/YueXia_1/liteauth
Project-URL: Documentation, https://gitee.com/YueXia_1/liteauth
Author-email: YueJian <yuexia@example.com>
License: Apache-2.0
License-File: LICENSE
Keywords: auth,authentication,fastapi,jwt,oauth2,sa-token,sso
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet :: WWW/HTTP :: Session
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: cashews>=7.5.0
Requires-Dist: pydantic-settings>=2.0
Requires-Dist: pydantic>=2.13.4
Requires-Dist: pyjwt>=2.8.0
Provides-Extra: all
Requires-Dist: cryptography>=41.0.0; extra == 'all'
Requires-Dist: fastapi>=0.100.0; extra == 'all'
Requires-Dist: hiredis>=3.4.0; extra == 'all'
Requires-Dist: orjson>=3.11.9; extra == 'all'
Requires-Dist: redis<6.0,>=5.0; extra == 'all'
Requires-Dist: uvicorn>=0.24.0; extra == 'all'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100.0; extra == 'fastapi'
Requires-Dist: uvicorn>=0.24.0; extra == 'fastapi'
Provides-Extra: jwt-rsa
Requires-Dist: cryptography>=41.0.0; extra == 'jwt-rsa'
Provides-Extra: orjson
Requires-Dist: orjson>=3.11.9; extra == 'orjson'
Provides-Extra: redis
Requires-Dist: hiredis>=3.4.0; extra == 'redis'
Requires-Dist: redis<6.0,>=5.0; extra == 'redis'
Description-Content-Type: text/markdown

# liteauth

> Python 异步权限认证框架，受 [Sa-Token](https://github.com/dromara/sa-token) 启发。

支持多账号体系、JWT（Simple / Mixin / Stateless）、OAuth2 服务端、SSO、Session 管理、角色/权限校验、踢人/顶号/封禁等能力。

## 设计原则

- **Core 无框架依赖** — 核心认证逻辑与 FastAPI / Flask / Django 解耦
- **Async first** — 全异步设计，原生适配 FastAPI / Starlette
- **多账号体系** — 一个系统多套用户表（`user` / `admin` / `merchant`），各自独立认证
- **可插拔存储** — Memory / Redis 自由切换，也可实现自定义 Store
- **JWT 可选** — 三种模式（Simple / Mixin / Stateless）按需选用

## 快速开始

```python
from liteauth import LiteAuthManager, LiteAuthConfig
from liteauth.store import MemoryStore

sa = LiteAuthManager(config=LiteAuthConfig(), store=MemoryStore())
user_auth = sa.create_logic("user")

pair = await user_auth.login("10001")
token = pair.access_token                     # 统一 TokenPair（基础模式 refresh_token 为 None）
login_id = await user_auth.get_login_id_by_token(token)  # "10001"
```

## 模式功能对比

liteauth 提供四种认证模式：基础模式（UUID + 全状态）与三种 JWT 模式（Simple / Mixin / Stateless），按需选用。

| 能力 | 基础模式 | JWT Simple | JWT Mixin | JWT Stateless |
| --- | --- | --- | --- | --- |
| 对应类 | `AuthLogic` | `JwtAuthLogic` | `JwtMixinAuthLogic` | `JwtStatelessAuthLogic` |
| Token 格式 | UUID | JWT | JWT | JWT |
| 存储依赖 | Store | Store | Store | ❌ 无（完全无状态） |
| login_id 来源 | Store（token→id 映射） | Store | JWT payload | JWT payload |
| 双 Token（access + refresh） | ❌ | ❌ | ✅ | ✅ |
| 服务端作废 token | ✅ | ✅ | ⚠️ 仅当前 token，refresh 无法作废 | ❌（logout 仅清客户端缓存） |
| Session（Account / Token） | ✅ | ✅ | ✅ | ❌ |
| 踢人 / 顶号 | ✅ | ✅ | ❌ | ❌ |
| 全部下线（logout_by_login_id） | ✅ | ✅ | ❌ | ❌ |
| 封禁（disable / disable_service） | ✅ | ✅ | ✅ | ❌ |
| 角色 / 权限校验 | ✅ | ✅ | ✅ | ✅ |
| 二级认证（safe） | ✅ Store 记录 | ✅ Store 记录 | ✅ Store 记录 | ✅ fresh claim |
| JWT payload 解析 | ❌ | ✅ | ✅ | ✅ |

**如何选择**：
- **基础模式** — 不需要 JWT 时的全功能兜底
- **JWT Simple** — 想要 JWT 格式（便于跨端解析 / 调试），同时保留 Redis 全状态能力
- **JWT Mixin** — 减少 Redis 查询（login_id 直接从 payload 读取），接受放弃踢人 / 顶号 / 全部下线
- **JWT Stateless** — 完全无状态，适合分布式 / 微服务；放弃 Session、封禁、服务端作废，内置 fresh-claim 二级认证

## JWT Stateless 双 Token（access + refresh）

Stateless 模式完全无状态（不依赖任何 Store），登录返回 `TokenPair`：

```python
from liteauth.plugin.jwt import JwtConfig, JwtStatelessAuthLogic
from liteauth.core.config import LiteAuthConfig

auth = JwtStatelessAuthLogic(
    "user",
    LiteAuthConfig(jwt=JwtConfig(
        secret_key="your-secret",
        jwt_access_token_timeout=3600,    # access 短效（秒）
        jwt_refresh_token_timeout=604800, # refresh 有限（秒）
        enable_refresh_token=True,        # False 时只签发 access
    )),
)

# 登录 → TokenPair(access_token, refresh_token, token_type, expires_in, ...)
pair = await auth.login("10001")
login_id = await auth.get_login_id_by_token(pair.access_token)  # "10001"

# 刷新 → 新 token 对（纯无状态，不依赖存储）
new_pair = await auth.refresh(pair.refresh_token)
```

安全模型说明（纯无状态取舍）：
- access 泄漏危害窗口 = `jwt_access_token_timeout`（短）
- refresh 泄漏危害窗口 = `jwt_refresh_token_timeout`（有限）
- 不依赖存储 ⇒ 无法作废旧 token / 检测重放，`logout` 仅清客户端缓存
- `get_login_id_by_token` 会拒绝 refresh token（校验 `token_use` claim）

## FastAPI 集成

```python
from fastapi import FastAPI, Depends
from liteauth.integration.fastapi.dependency import require_login, require_role

app = FastAPI()
sa.init_app(app)

@app.get("/me", dependencies=[Depends(require_login("user"))])
async def me():
    return {"msg": "已登录"}

@app.get("/admin", dependencies=[Depends(require_role("admin", auth="user"))])
async def admin():
    return {"msg": "管理员"}
```

### 路由中间件方式

```python
from liteauth.core.router import GuardRule
from liteauth.integration.fastapi.middleware import GuardRuleMiddleware

router = GuardRule()
router.match("/api/admin/**").check(lambda ctx: admin_auth.check_login(ctx))
app.add_middleware(GuardRuleMiddleware, guard_rule=router)
```

## 安装

```bash
pip install liteauth

# 带 FastAPI 集成
pip install liteauth[fastapi]

# 带 Redis 存储
pip install liteauth[redis]

# 全量
pip install liteauth[all]
```

## 项目结构

```
liteauth/
├── core/           # 核心认证逻辑（无框架依赖）
│   ├── logic.py    # AuthLogic — 认证逻辑实现
│   ├── config.py   # LiteAuthConfig — 全局配置
│   ├── session.py  # AuthSession — 会话管理
│   ├── router.py   # GuardRule — 路由鉴权器
│   └── ...
├── store/          # 存储层抽象
│   ├── base.py     # Store 协议
│   ├── memory.py   # MemoryStore
│   └── redis.py    # RedisStore
├── integration/    # Web 框架集成
│   └── fastapi/    # FastAPI Depends / Middleware
├── plugin/         # 插件
│   ├── jwt/        # JWT Simple / Mixin / Stateless
│   ├── oauth2/     # OAuth2 服务端
│   └── sso/        # SSO 单点登录
├── strategy/       # 可替换策略
│   ├── key_builder.py  # Redis key 命名规则
│   └── token.py        # Token 生成策略
└── manager.py      # LiteAuthManager 全局管理器
```

## 许可证

Apache-2.0
