Metadata-Version: 2.4
Name: liteauth
Version: 0.0.1
Summary: Ready to use and customizable Authentications and Oauth2 management for FastAPI
Project-URL: Homepage, https://github.com/yezz123/liteauth
Project-URL: Documentation, https://liteauth.yezz.me/
Project-URL: Funding, https://github.com/sponsors/yezz123
Project-URL: Source, https://github.com/yezz123/liteauth
Project-URL: Changelog, https://liteauth.yezz.me/release/
Author-email: Yue Jian <yuexiawyl@163.com>
License-Expression: MIT
License-File: LICENSE
Keywords: Authentication,Cookie,FastAPI,JWT,Oauth2,Pydantic
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Framework :: FastAPI
Classifier: Framework :: Pydantic
Classifier: Framework :: Pydantic :: 2
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet
Classifier: Topic :: Internet :: WWW/HTTP :: Session
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: cashews>=7.5.0
Requires-Dist: fastapi>=0.111.0
Requires-Dist: itsdangerous<3.0.0,>=2.2.0
Requires-Dist: makefun>=1.16.0
Requires-Dist: pydantic-settings>=2.1.0
Requires-Dist: pydantic<3.0.0,>=2.10.5
Requires-Dist: pyjwt[crypto]<3.0.0,>=2.6.0
Requires-Dist: python-dateutil<3.0.0,>=2.8
Requires-Dist: pytz<2027.0,>=2023.3
Requires-Dist: typing-extensions>=4.12.0
Requires-Dist: uvicorn>=0.39.0
Description-Content-Type: text/markdown

# LiteAuth

<p align="center">
  <em>为 FastAPI 打造的全新重构认证与授权框架 — 双模式认证、存储可插拔、类型安全</em>
</p>

<p align="center">
  <a href="https://www.python.org/downloads/">
    <img src="https://img.shields.io/badge/python-3.9+-blue.svg" alt="Python 3.9+">
  </a>
  <a href="https://pydantic.dev">
    <img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pydantic/pydantic/main/docs/badge/v2.json" alt="Pydantic v2">
  </a>
</p>

---

**源码仓库**: <https://gitee.com/YueXia_1/liteauth>

---

LiteAuth 是对经典 authx 库的**彻底重构**。与将一切认证逻辑塞入单一巨类的旧架构不同，LiteAuth 提供**两种独立认证模式**，按需选用：

- **经典 JWT 模式（`LiteAuth`）** — 纯无状态认证，token 通过 JWT 签名验证，不涉及任何服务端存储。适用于简单 API、微服务等场景
- **Session 模式（`SessionAuth`）** — 服务端存储 token，支持单独吊销和全量管理。存储后端通过 `SessionStoreProtocol` 可插拔，开发环境用内存存储，生产环境无缝切换到 Redis

两种模式互不依赖，纯 JWT 模式不需要 session 存储，也无任何 session 相关开销。设计要点：

- **可插拔存储协议** — Session 模式下开发用内存存储、生产用 Redis，应用代码零改动
- **Sa-Token 兼容的层级键设计** — 带命名空间、可搜索、多登录类型隔离
- **全链路类型安全** — 公开 API 零 `Any`，基于 `Protocol` 类型实现扩展

## 安装

```bash
pip install liteauth
```

生产环境使用 Redis 存储 session 时需要额外安装 `cashews` 缓存库：

```bash
pip install liteauth[cashews]
```

## 快速开始

### 经典 JWT 模式

```python
from fastapi import FastAPI, Depends, HTTPException
from liteauth import LiteAuth, AuthConfig

app = FastAPI()

config = AuthConfig(
    JWT_SECRET_KEY="change-this-secret",
    JWT_TOKEN_LOCATION=["headers"],
)

auth = LiteAuth(config=config)
auth.handle_errors(app)

@app.post("/login")
def login(username: str, password: str):
    if username == "test" and password == "test":
        token = auth.create_access_token(uid=username)
        return {"access_token": token}
    raise HTTPException(401, detail="Invalid credentials")

@app.get("/protected", dependencies=[Depends(auth.access_token_required)])
def protected():
    return {"message": "Hello World"}
```

### Session 模式（服务端 token 存储）

```python
from fastapi import FastAPI, Depends
from liteauth import AuthConfig, LiteAuth
from liteauth.auth import SessionAuth

app = FastAPI()

config = AuthConfig(
    JWT_SECRET_KEY="change-this-secret",
    JWT_TOKEN_LOCATION=["headers"],
)

# 所有 SessionAuth 实例默认共享同一个内存存储，通过 login_type 隔离
admin_auth = SessionAuth(config=config, login_type="admin")
user_auth  = SessionAuth(config=config, login_type="user")

admin_auth.handle_errors(app)

@app.post("/admin/login")
async def admin_login():
    token = await admin_auth.create_access_token(uid="admin")
    return {"access_token": token}

@app.get("/admin/data", dependencies=[Depends(admin_auth.access_token_required)])
async def admin_data():
    return {"secret": "sensitive data"}
```

### 生产环境：Redis 存储

```python
from cashews import Cache
from liteauth.auth import SessionAuth
from liteauth.store import CashewsSessionStore

cache = Cache()
cache.setup("redis://localhost:6379")

store = CashewsSessionStore(cache, default_ttl_seconds=3600)

auth = SessionAuth(config=config, session_store=store)
```

## 架构

```
                    ┌──────────────────────────────────────┐
                    │           LiteAuth                   │
                    │  经典 JWT 模式，纯无状态              │
                    │  (JWT 签名验证，无 session 存储)      │
                    └──────────────────────────────────────┘

                    ┌──────────────────────────────────────┐
                    │          SessionAuth                 │
                    │  Session 模式，服务端存储 token       │
                    └──────────────┬───────────────────────┘
                                   │ 委托给
                    ┌──────────────▼───────────────────────┐
                    │          SessionService               │
                    │     (session 生命周期管理)            │
                    └──────────────┬───────────────────────┘
                                   │ 实现自
             ┌─────────────────────┼────────────────────────┐
             │                     │                        │
  ┌──────────▼──────────┐  ┌──────▼──────┐  ┌──────────────▼──────────────┐
  │ InMemorySessionStore│  │CashewsStore │  │     自定义存储后端          │
  │  (开发环境，默认)     │  │ (生产环境)  │  │ (实现 SessionStoreProtocol) │
  └─────────────────────┘  └─────────────┘  └─────────────────────────────┘
```

### 核心组件

| 组件 | 模式 | 作用 |
|------|------|------|
| `LiteAuth` | 经典 JWT | 纯无状态 JWT 认证（access/refresh token、CSRF、黑名单），不涉及 session 存储 |
| `SessionAuth` | Session | Session 模式认证 — token 存储在服务端，支持单独吊销和全量管理 |
| `AuthManager` | 通用 | 多登录类型管理器，隔离不同认证上下文（如 admin + user），两种模式皆可使用 |
| `SessionStoreProtocol` | Session | 存储后端的类型协议 — 实现它可以接入 Redis、MySQL 等 |
| `InMemorySessionStore` | Session | 内置内存存储（开发环境默认），支持可选 TTL 和最大 session 数驱逐 |
| `CashewsSessionStore` | Session | 基于 `cashews` 的生产级 Redis 存储，带可选 TTL |
| `KeyBuilder` | Session | Sa-Token 风格的层级键构造器，用于命名空间化的缓存键 |
| `PolicyEngine` | 通用 | 可插拔的策略引擎，支持 scope、角色、属性、自定义评估器 |

## 功能特性

- **双认证模式**：经典 JWT（`LiteAuth`）和 session 存储（`SessionAuth`）
- **多种 token 位置**：请求头、Cookie（含 CSRF）、查询参数、JSON 请求体
- **服务端吊销**：吊销单个 token 或某个用户的所有 session
- **可插拔存储**：实现 `SessionStoreProtocol` 即可接入任意后端
- **多登录类型隔离**：同一框架内独立运行多个认证上下文
- **Sa-Token 兼容键设计**：冒号分隔的层级键，Redis 友好
- **滑动 session TTL**：每次验证自动更新最后一次活跃时间戳
- **策略引擎**：scope、角色、环境检查、自定义评估器
- **类型安全**：完整 Protocol 类型标注，公开接口无 `Any`
- **可扩展错误处理**：自定义错误处理器，支持按登录类型定制错误信息

## 项目状态

这是对原 authx 框架的**彻底重写**。内部架构从零开始重建，核心关注点放在 session 模式认证、存储可插拔性和类型安全上。项目处于活跃开发阶段，公开 API 在成熟过程中可能发生变化。

## 许可证

MIT
