初步实现数据加密、权限管理、日志审计等功能

This commit is contained in:
2026-02-02 10:09:28 +08:00
parent b6b37a453b
commit 807e634318
27 changed files with 3787 additions and 59 deletions

322
INTEGRATION_CHECKLIST.md Normal file
View File

@@ -0,0 +1,322 @@
# API 集成检查清单
## ✅ 已完成的集成工作
### 1. 路由集成 (app/api/v1/router.py)
已添加以下路由到 API Router
```python
# 新增导入
from app.api.v1.endpoints import (
...
user_management, # 用户管理
audit, # 审计日志
)
# 新增路由
api_router.include_router(user_management.router, prefix="/users", tags=["User Management"])
api_router.include_router(audit.router, prefix="/audit", tags=["Audit Logs"])
```
**路由端点**
- `/api/v1/auth/` - 认证相关register, login, me, refresh
- `/api/v1/users/` - 用户管理CRUD操作仅管理员
- `/api/v1/audit/` - 审计日志查询(仅管理员)
### 2. 主应用配置 (app/main.py)
#### 2.1 导入更新
```python
from app.core.config import settings
from app.infra.audit.middleware import AuditMiddleware
```
#### 2.2 数据库初始化
```python
# 在 lifespan 中存储数据库实例到 app.state
app.state.db = pgdb
```
#### 2.3 FastAPI 配置
```python
app = FastAPI(
lifespan=lifespan,
title=settings.PROJECT_NAME,
description="TJWater Server - 供水管网智能管理系统",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
)
```
#### 2.4 审计中间件(可选)
```python
# 取消注释以启用审计日志
# app.add_middleware(AuditMiddleware)
```
### 3. 依赖项更新 (app/auth/dependencies.py)
更新 `get_db()` 函数从 Request 对象获取数据库:
```python
async def get_db(request: Request) -> Database:
"""从 app.state 获取数据库实例"""
if not hasattr(request.app.state, "db"):
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Database not initialized"
)
return request.app.state.db
```
### 4. 审计日志更新
- `app/api/v1/endpoints/audit.py` - 使用正确的数据库依赖
- `app/core/audit.py` - 接受可选的 db 参数
---
## 📋 部署前检查清单
### 环境配置
- [ ] 复制 `.env.example``.env`
- [ ] 配置 `SECRET_KEY`JWT密钥
- [ ] 配置 `ENCRYPTION_KEY`(数据加密密钥)
- [ ] 配置数据库连接信息
### 数据库迁移
- [ ] 执行用户表迁移:`psql -U postgres -d tjwater -f migrations/001_create_users_table.sql`
- [ ] 执行审计日志表迁移:`psql -U postgres -d tjwater -f migrations/002_create_audit_logs_table.sql`
- [ ] 验证表已创建:`\dt` 在 psql 中
### 依赖检查
- [ ] 确认已安装:`cryptography`
- [ ] 确认已安装:`python-jose[cryptography]`
- [ ] 确认已安装:`passlib[bcrypt]`
- [ ] 确认已安装:`email-validator`(用于 Pydantic email 验证)
### 代码验证
- [ ] 检查所有文件导入正常
- [ ] 运行加密功能测试:`python tests/test_encryption.py`
- [ ] 启动服务器:`uvicorn app.main:app --reload`
- [ ] 访问 API 文档http://localhost:8000/docs
### API 测试
- [ ] 测试登录POST `/api/v1/auth/login`
- [ ] 测试获取当前用户GET `/api/v1/auth/me`
- [ ] 测试用户列表需管理员GET `/api/v1/users/`
- [ ] 测试审计日志需管理员GET `/api/v1/audit/logs`
---
## 🔧 快速测试命令
### 1. 生成密钥
```bash
# JWT 密钥
openssl rand -hex 32
# 加密密钥
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
```
### 2. 执行迁移
```bash
cd /home/zhifu/TJWaterServer/TJWaterServerBinary
psql -U postgres -d tjwater -f migrations/001_create_users_table.sql
psql -U postgres -d tjwater -f migrations/002_create_audit_logs_table.sql
```
### 3. 测试加密
```bash
python tests/test_encryption.py
```
### 4. 启动服务器
```bash
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
```
### 5. 测试登录 API
```bash
# 使用默认管理员账号
curl -X POST "http://localhost:8000/api/v1/auth/login" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=admin&password=admin123"
# 或使用迁移的账号
curl -X POST "http://localhost:8000/api/v1/auth/login" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=tjwater&password=tjwater@123"
```
### 6. 测试受保护接口
```bash
# 保存 Token
TOKEN="<从登录响应中获取的 access_token>"
# 获取当前用户信息
curl -X GET "http://localhost:8000/api/v1/auth/me" \
-H "Authorization: Bearer $TOKEN"
# 获取用户列表(需管理员权限)
curl -X GET "http://localhost:8000/api/v1/users/" \
-H "Authorization: Bearer $TOKEN"
# 查询审计日志(需管理员权限)
curl -X GET "http://localhost:8000/api/v1/audit/logs" \
-H "Authorization: Bearer $TOKEN"
```
---
## 📚 API 端点总览
### 认证接口 (`/api/v1/auth`)
| 方法 | 端点 | 描述 | 权限 |
|------|------|------|------|
| POST | `/register` | 用户注册 | 公开 |
| POST | `/login` | OAuth2 登录 | 公开 |
| POST | `/login/simple` | 简化登录(兼容旧版) | 公开 |
| GET | `/me` | 获取当前用户信息 | 认证用户 |
| POST | `/refresh` | 刷新 Token | 认证用户 |
### 用户管理 (`/api/v1/users`)
| 方法 | 端点 | 描述 | 权限 |
|------|------|------|------|
| GET | `/` | 获取用户列表 | 管理员 |
| GET | `/{id}` | 获取用户详情 | 所有者/管理员 |
| PUT | `/{id}` | 更新用户信息 | 所有者/管理员 |
| DELETE | `/{id}` | 删除用户 | 管理员 |
| POST | `/{id}/activate` | 激活用户 | 管理员 |
| POST | `/{id}/deactivate` | 停用用户 | 管理员 |
### 审计日志 (`/api/v1/audit`)
| 方法 | 端点 | 描述 | 权限 |
|------|------|------|------|
| GET | `/logs` | 查询审计日志 | 管理员 |
| GET | `/logs/count` | 获取日志总数 | 管理员 |
| GET | `/logs/my` | 查看我的操作记录 | 认证用户 |
---
## ⚠️ 注意事项
### 1. 审计中间件
审计中间件默认是**禁用**的。如需启用,在 `app/main.py` 中取消注释:
```python
app.add_middleware(AuditMiddleware)
```
**注意**:启用后会自动记录所有 POST/PUT/DELETE 请求,可能增加数据库负载。
### 2. 向后兼容
保留了原有的简化登录接口 `/auth/login/simple`,可以直接使用查询参数:
```bash
POST /api/v1/auth/login/simple?username=admin&password=admin123
```
### 3. 数据库连接
确保数据库实例在应用启动时正确初始化并存储到 `app.state.db`
### 4. 权限控制示例
为现有接口添加权限控制:
```python
from app.auth.permissions import require_role, get_current_admin
from app.domain.models.role import UserRole
# 需要管理员权限
@router.delete("/resource/{id}")
async def delete_resource(
id: int,
current_user = Depends(get_current_admin)
):
...
# 需要操作员以上权限
@router.post("/resource")
async def create_resource(
data: dict,
current_user = Depends(require_role(UserRole.OPERATOR))
):
...
```
---
## 🚀 完整启动流程
```bash
# 1. 进入项目目录
cd /home/zhifu/TJWaterServer/TJWaterServerBinary
# 2. 配置环境变量(如果还没有)
cp .env.example .env
# 编辑 .env 填写必要的配置
# 3. 执行数据库迁移(如果还没有)
psql -U postgres -d tjwater < migrations/001_create_users_table.sql
psql -U postgres -d tjwater < migrations/002_create_audit_logs_table.sql
# 4. 测试加密功能
python tests/test_encryption.py
# 5. 启动服务器
uvicorn app.main:app --reload
# 6. 访问 API 文档
# 浏览器打开: http://localhost:8000/docs
```
---
## 📞 故障排查
### 问题 1: 导入错误
```
ModuleNotFoundError: No module named 'jose'
```
**解决**: 安装依赖 `pip install python-jose[cryptography]`
### 问题 2: 数据库未初始化
```
503 Service Unavailable: Database not initialized
```
**解决**: 检查 `main.py` 中的 lifespan 函数是否正确设置 `app.state.db`
### 问题 3: Token 验证失败
```
401 Unauthorized: Could not validate credentials
```
**解决**:
1. 检查 SECRET_KEY 是否配置正确
2. 确认 Token 格式:`Authorization: Bearer {token}`
3. 检查 Token 是否过期
### 问题 4: 表不存在
```
relation "users" does not exist
```
**解决**: 执行数据库迁移脚本
---
## 📖 相关文档
- **使用指南**: `SECURITY_README.md`
- **部署指南**: `DEPLOYMENT.md`
- **实施总结**: `SECURITY_IMPLEMENTATION_SUMMARY.md`
- **自动设置**: `setup_security.sh`
---
**最后更新**: 2026-02-02
**状态**: ✅ API 已完全集成