Metadata-Version: 2.4
Name: liteauth
Version: 0.2.8
Summary: Python permission authentication framework inspired by sa-token, with FastAPI integration
Project-URL: Homepage, https://gitee.com/YueXia_1/liteauth
Project-URL: Repository, https://gitee.com/YueXia_1/liteauth
Project-URL: Issues, https://gitee.com/YueXia_1/liteauth/issues
Author: liteauth contributors
License: MIT
License-File: LICENSE
Keywords: authentication,authorization,fastapi,jwt,oauth2,permission,role,sa-token,session,sso
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT 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: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP :: Session
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: cashews>=7.5.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: all
Requires-Dist: cryptography>=42.0.0; extra == 'all'
Requires-Dist: fastapi>=0.100.0; extra == 'all'
Requires-Dist: pyjwt>=2.13.0; extra == 'all'
Requires-Dist: redis>=5.0; extra == 'all'
Provides-Extra: crypto
Requires-Dist: cryptography>=42.0.0; extra == 'crypto'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100.0; extra == 'fastapi'
Provides-Extra: jwt
Requires-Dist: pyjwt>=2.13.0; extra == 'jwt'
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == 'redis'
Description-Content-Type: text/markdown

# liteauth

![liteauth](docs/logo.png)

Python 权限认证框架，源自 [sa-token](https://github.com/dromara/sa-token) 的设计思想。

[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-MIT-green)](https://gitee.com/YueXia_1/liteauth/blob/master/LICENSE)

---

## 特性

- **登录/注销** — 单端/多端登录、同端互斥
- **踢人下线** — 按用户 ID 或 Token 精确踢出
- **权限/角色校验** — 通配符支持（`art.*` → `art.add`）
- **Session 管理** — Account-Session（跨设备）/ Token-Session（单设备）
- **账号封禁** — 分类封禁 + 阶梯封禁
- **多账号体系** — `AuthLogic("user")` / `AuthLogic("admin")` 独立隔离
- **SSO 单点登录** — 三种模式
- **OAuth2.0** — 授权服务器（Authorization Code / Implicit / Client Credentials）
- **JWT 模式** — 标准 / 无状态 / Mixin 三种模式
- **FastAPI** — 独立依赖函数、装饰器、中间件
- **可插拔存储** — 内存 / 磁盘(SQLite) / Redis

---

## 安装

```bash
pip install liteauth

# 可选依赖
pip install liteauth[fastapi]   # FastAPI 集成
pip install liteauth[redis]     # Redis 存储
pip install liteauth[jwt]       # JWT 模式
pip install liteauth[crypto]    # AES 加密
pip install liteauth[all]       # 全部
```

---

## 快速开始

### 核心 API

```python
from liteauth import AuthLogic, PermissionInterface, AuthManager

class MyPermission(PermissionInterface):
    async def get_permission_list(self, login_id, login_type):
        return {"admin": ["*"]}.get(login_id, ["user:view"])
    async def get_role_list(self, login_id, login_type):
        return {"admin": ["admin"]}.get(login_id, ["user"])

# 统一初始化（推荐在应用启动时调用一次）
AuthManager.init(
    permission_interface=MyPermission(),
)

auth = AuthLogic()
await auth.login("admin")
```

### FastAPI

```python
from fastapi import FastAPI, Depends
from liteauth import AuthLogic, AuthManager
from liteauth.integration.fastapi import login_required, require_permission, register_exception_handlers

app = FastAPI()

AuthManager.init(
    permission_interface=MyPermission(),
)

auth = AuthLogic()
AuthManager.register_auth(auth)
register_exception_handlers(app)

@app.post("/login")
async def login(username: str):
    return await auth.login(username)

@app.get("/users/me")
async def me(user_id: str = Depends(login_required())):
    return {"user_id": user_id}

@app.get("/admin")
async def admin(_: None = Depends(require_permission("admin:panel"))):
    return {"msg": "welcome"}
```

### 装饰器

```python
from liteauth.integration.fastapi.decorator import login_required, require_permission, require_role, ignore_auth

@router.get("/users")
@login_required
async def users(): ...

@router.get("/admin")
@require_permission("admin:panel")
async def admin(): ...

@router.get("/public")
@ignore_auth
async def public(): ...
```

### JWT 无状态模式

```python
from liteauth import JwtStatelessLogic, AuthConfig

auth = JwtStatelessLogic(config=AuthConfig(
    jwt_secret="my-secret-key",
    jwt_access_token_timeout=3600,
))

result = await auth.login("user123")
# → TokenResponse(access_token="eyJ...", refresh_token="eyJ...")

await auth.check_login()   # 解码 JWT，不查数据库
new = await auth.refresh(result.refresh_token)  # 刷新 Token
```

---

## 四种认证模式

### JWT Simple

```python
from liteauth import JwtSimpleLogic, AuthConfig

auth = JwtSimpleLogic(config=AuthConfig(jwt_secret="my-key"))
result = await auth.login("user123")     # token 是 JWT
await auth.check_login()                  # 走 DAO 查询
await auth.kickout("user123")             # 完整支持
```

### 对比

| | 标准 | JWT Simple | JWT 无状态 | JWT Mixin |
|---|---|---|---|---|
| Token 格式 | UUID | JWT | JWT | JWT |
| Token 校验 | DAO | DAO | JWT 解码 | JWT 解码 |
| 踢人下线 | ✅ | ✅ | ❌ | ❌ |
| Token-Session | ✅ | ✅ | ❌ | ✅ |
| 双 Token | — | — | ✅ | ✅ |
| get_extra() | ❌ | ✅ | ✅ | ✅ |

---

## 异常处理

一行注册，自动转换异常为 JSON 响应：

```python
from liteauth.integration.fastapi import register_exception_handlers
register_exception_handlers(app)
```

| 异常 | HTTP | 响应示例 |
|---|---|---|
| `NotLoginException` | 401 | `{"detail":"已被踢下线","code":"NOT_LOGIN","scene":"-5"}` |
| `NotPermissionException` | 403 | `{"detail":"无此权限","code":"PERMISSION_DENIED","permission":"admin:panel"}` |
| `NotRoleException` | 403 | `{"detail":"无此角色","code":"ROLE_DENIED","role":"admin"}` |
| `DisableServiceException` | 403 | `{"detail":"账号已被封禁","code":"DISABLE"}` |

---

## 存储后端

```python
# 内存（默认，开发/测试）
from liteauth import MemoryDao
dao = MemoryDao(size=100_000)

# 磁盘持久化（SQLite，单机生产）
from liteauth.dao.disk import DiskDao
dao = DiskDao(directory="./auth_cache")

# Redis（分布式生产）
from liteauth import RedisDao
dao = RedisDao.from_url("redis://localhost:6379/0")

# 使用
auth = AuthLogic(dao=dao)
```

---

## 多账号体系

```python
user_auth = AuthLogic(login_type="user")
admin_auth = AuthLogic(login_type="admin")

AuthManager.register_auth(user_auth)
AuthManager.register_auth(admin_auth)

# FastAPI
@app.get("/admin")
async def admin(_: None = Depends(require_permission("admin:panel", login_type="admin"))):
    ...
```

---

## 高级特性

### SSO 单点登录

```python
from liteauth.sso import SsoConfig, SsoRouter, SsoClient

router = SsoRouter(SsoConfig(server_url="http://auth.example.com"))
app.include_router(router.get_router(), prefix="/sso")

client = SsoClient(auth, config=sso_config)
```

### OAuth2.0

```python
from liteauth.oauth2 import OAuth2Config, OAuth2Client, OAuth2Router

# FastAPI 路由
router = OAuth2Router(OAuth2Config(server_url="http://localhost:8000"))
app.include_router(router.get_router(), prefix="/oauth2")

# Flask 用户可直接使用 OAuth2Template + 自定义路由
template = OAuth2Template(config)
await template.authorize(client_id="app1", response_type="code", user_id="123")
```

### 临时 Token

```python
from liteauth import TempTokenUtil

token = TempTokenUtil.create_token("user@example.com", timeout=300, secret="key")
value = TempTokenUtil.parse_token(token, secret="key")  # → "user@example.com"
```

### 二级认证

```python
await auth.open_safe(service="payment", timeout=120)   # 开启
await auth.check_safe(service="payment")                 # 校验
await auth.close_safe(service="payment")                 # 关闭
```

---

## 依赖

| 模块 | 依赖 |
|---|---|
| 核心 | `pydantic>=2.0`, `cashews>=7.5` |
| FastAPI | `fastapi>=0.139` |
| Redis | `redis>=8.0` |
| JWT | `pyjwt>=2.13` |
| Crypto | `cryptography>=49.0` |

---

## License

MIT
