deploy: Update frontend build for deployment

This commit is contained in:
super committed 2026-03-03 11:37:34 +08:00
1 parent f18b6ce2df
commit b3e233bf76
6 files changed
+306 -2266

No files matched your search

+5 -2
View File
@@ -10,15 +10,18 @@ with app.app_context():
print(f"Found admin user. Current role: {admin.role}")
if admin.role != 'admin':
admin.role = 'admin'
db.session.commit()
print("Updated admin user role to 'admin'")
# Always update password to ensure it's set correctly
admin.set_password('Hxit@54321')
db.session.commit()
print("Updated admin user password to 'Hxit@54321'")
else:
print("Admin user not found. Creating...")
admin = User(username='admin', email='admin@example.com', role='admin')
admin.set_password('Hxit@54321')
db.session.add(admin)
db.session.commit()
print("Created admin user with role 'admin'")
print("Created admin user with role 'admin' and password 'Hxit@54321'")
# Also check if there are other users that should be admin but aren't
users = User.query.all()
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""
密码重置脚本
用途:用于重置用户密码,特别是在用户忘记密码时
使用方法:python3 reset_password.py <username> <new_password>
"""
import sys
from app import create_app, db
from app.models import User
if len(sys.argv) != 3:
print("Usage: python3 reset_password.py <username> <new_password>")
print("Example: python3 reset_password.py admin Hxit@54321")
sys.exit(1)
username = sys.argv[1]
new_password = sys.argv[2]
app = create_app()
with app.app_context():
# 查找用户
user = User.query.filter_by(username=username).first()
if user:
print(f"Found user: {user.username}, Role: {user.role}")
# 设置新密码
user.set_password(new_password)
db.session.commit()
print(f"✅ SUCCESS: Password reset for user '{username}' to '{new_password}'")
else:
print(f"❌ FAILURE: User '{username}' not found")
# 列出所有可用用户
print("\nAvailable users:")
users = User.query.all()
for u in users:
print(f" - {u.username} (Role: {u.role})")
+24
View File
@@ -0,0 +1,24 @@
from app import create_app, db
from app.models import User
app = create_app()
with app.app_context():
# 测试 admin 用户登录
admin = User.query.filter_by(username='admin').first()
if admin:
print(f"Testing admin user login...")
# 测试新密码
password = 'Hxit@54321'
if admin.check_password(password):
print(f"✅ SUCCESS: Admin user can login with password '{password}'")
else:
print(f"❌ FAILURE: Admin user cannot login with password '{password}'")
# 测试错误密码
wrong_password = 'wrongpassword'
if not admin.check_password(wrong_password):
print(f"✅ SUCCESS: Admin user correctly rejects wrong password")
else:
print(f"❌ FAILURE: Admin user accepts wrong password")
else:
print("Admin user not found!")
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""
测试登录 API
用途:直接测试后端的登录 API 是否能正常响应
使用方法:python3 test_login_api.py <username> <password>
"""
import sys
import json
import requests
if len(sys.argv) != 3:
print("Usage: python3 test_login_api.py <username> <password>")
print("Example: python3 test_login_api.py admin Hxit@54321")
sys.exit(1)
username = sys.argv[1]
password = sys.argv[2]
# 测试登录 API
url = "http://localhost:5002/api/user/login"
headers = {"Content-Type": "application/json"}
data = {"username": username, "password": password}
print(f"Testing login API for user '{username}'...")
try:
response = requests.post(url, headers=headers, data=json.dumps(data), timeout=5)
print(f"Status code: {response.status_code}")
print(f"Response: {response.json()}")
if response.status_code == 200:
print("✅ SUCCESS: Login API returned 200 OK")
else:
print("❌ FAILURE: Login API returned error")
except requests.exceptions.ConnectionError:
print("❌ FAILURE: Cannot connect to the server. Is the backend running?")
except Exception as e:
print(f"❌ FAILURE: Error testing login API: {e}")
# 测试另一种方式:使用 Flask 应用上下文直接测试
print("\nTesting with Flask app context...")
try:
from app import create_app
from app.models import User
app = create_app()
with app.app_context():
user = User.query.filter_by(username=username).first()
if user:
print(f"Found user: {user.username}, Role: {user.role}")
if user.check_password(password):
print(f"✅ SUCCESS: Password is correct for user '{username}'")
else:
print(f"❌ FAILURE: Password is incorrect for user '{username}'")
else:
print(f"❌ FAILURE: User '{username}' not found")
except Exception as e:
print(f"❌ FAILURE: Error testing with app context: {e}")
File diff suppressed because it is too large. Load diff
+100 -85
View File
@@ -1,124 +1,139 @@
# Enterprise AI Gateway Project Context
## 1. 🚀 项目一句话概述
这是一个企业级 AI 聚合网关平台,旨在统一管理和分发各类 AI Agent(如 Dify 应用),为企业内部提供统一的 AI 对话入口、权限控制(RBAC)、审计日志及个性化工作台功能。
## 1. 🚀 项目概述 (Project Overview)
**Enterprise AI Gateway** 是一个企业级 AI 聚合网关平台,旨在统一管理和分发各类 AI Agent(如 Dify 应用)。它为企业内部提供统一的 AI 对话入口、细粒度的权限控制(RBAC)、全链路审计日志以及个性化的用户工作台。
## 2. 🛠 核心技术栈 (Tech Stack)
## 2. 🛠 技术栈 (Tech Stack)
### 前端 (Frontend)
- **框架**: Vue 3 (Composition API) + TypeScript
- **构建工具**: Vite
- **UI 框架**: TailwindCSS + Lucide Icons
- **路由**: Vue Router 4
- **国际化**: Vue I18n
- **网络请求**: 原生 Fetch API (用于 SSE 流式传输) + Axios (常规请求)
- **国际化**: Vue I18n (支持 zh-CN, zh-TW, en-US, th-TH)
- **网络请求**: 原生 Fetch API (用于 SSE 流式传输) + Axios (常规 API 请求)
### 后端 (Backend)
- **框架**: Flask (Python 3.12)
- **ORM**: SQLAlchemy (Flask-SQLAlchemy)
- **并发处理**: Gevent (异步 Worker,支持高并发 SSE)
- **ORM**: SQLAlchemy 2.0 (Flask-SQLAlchemy)
- **数据库迁移**: Alembic (Flask-Migrate)
- **服务器**: Gunicorn (生产) / Werkzeug (开发)
- **依赖库**: `requests` (HTTP调用), `pydantic` (数据验证)
- **服务器**: Gunicorn (生产环境 WSGI 容器)
- **依赖库**: `requests` (HTTP调用), `pydantic` (数据验证), `psycopg2-binary` (PostgreSQL 驱动)
### 基础设施 (Infrastructure)
- **数据库**: PostgreSQL
- **缓存**: Redis (用于 Session 或 任务队列,可选)
- **容器化**: Docker + Docker Compose
- **反向代理**: Nginx (处理 HTTPS, 静态资源, 反向代理)
- **进程管理**: Supervisor (守护 Gunicorn 进程)
- **数据库**: PostgreSQL (生产环境)
- **缓存**: Redis (可选,用于 Session 或 任务队列)
- **代码托管**: Gitee (`super` 分支)
## 3. 📂 核心目录结构 (Directory Structure)
```text
hxops/
├── backend/ # Flask 后端根目录
├── backend/ # Flask 后端
│ ├── app/
│ │ ├── api/ # API 路由蓝图 (Blueprints)
│ │ │ ├── admin.py # 管理员接口 (Agent管理, 部门管理)
│ │ │ ├── chat.py # 对话接口 (SSE流式代理)
│ │ │ ├── user.py # 用户端接口 (首页, 收藏, 常用问题)
│ │ ├── api/ # API 路由 (Blueprint)
│ │ │ ├── admin.py # 管理员接口
│ │ │ ├── chat.py # 对话接口 (SSE流式)
│ │ │ └── ...
│ │ ├── services/ # 业务逻辑层
│ │ │ └── dify.py # Dify API 集成服务 (核心)
│ │ ├── models.py # 数据库模型定义
│ │ ├── decorators.py # 权限控制装饰器
│ │ └── __init__.py # App 工厂函数
│ ├── migrations/ # 数据库迁移脚本
│ ├── run.py # 启动入口 (端口 5002)
│ │ ├── services/ # 业务逻辑 (DifyService)
│ │ ├── models.py # 数据库模型
│ │ └── __init__.py # App 工厂
│ ├── deploy/ # 部署配置
│ │ └── gunicorn_config.py # Gunicorn 生产配置 (Gevent)
│ ├── migrations/ # 数据库迁移文件
│ ├── run.py # 启动入口
│ └── requirements.txt # Python 依赖
├── frontend/ # Vue 前端根目录
├── frontend/ # Vue 前端
│ ├── src/
│ │ ├── composables/ # 组合式函数
│ │ │ └── useChat.ts # 聊天逻辑封装 (SSE 处理)
│ │ ├── views/ # 页面组件
│ │ │ ├── AdminView.vue # 管理后台
│ │ │ ├── ChatView.vue # 对话界面
│ │ │ └── WorkspaceView.vue # 用户工作台
│ │ ├── router/ # 路由配置
│ │ └── main.ts # 入口文件
│ └── vite.config.ts # Vite 配置 (含代理设置)
├── docs/ # 项目文档
│ └── k_Enterprise_AI_Gateway_Architecture_*.md # 架构文档
└── scripts/ # 运维与测试脚本
├── mock_dify_server.py # 模拟 Dify 服务
└── test_chat_flow.py # 对话流程测试脚本
│ │ ├── composables/ # Hooks (useChat.ts)
│ │ ├── views/ # 页面 (Admin, Chat, Workspace)
│ │ └── i18n.ts # 国际化配置
│ └── vite.config.ts # Vite 配置
├── scripts/ # 运维与自动化脚本
│ ├── deploy.sh # 服务器部署脚本 (核心)
│ ├── nginx.conf # Nginx 生产配置
│ └── supervisord.conf # Supervisor 配置
└── docs/ # 项目文档
```
## 4. 🔄 核心业务流与架构设计
## 4. 🏗️ 部署架构 (Deployment Architecture)
### 4.1 前后端交互规范
- **API 前缀**: `/api` (如 `/api/chat/completions`, `/api/admin/agents`)
- **跨域处理**: 开发环境通过 Vite Proxy (`frontend/vite.config.ts`) 转发 `/api` 请求到后端端口 (5002)。
- **响应格式**: 标准 RESTful JSON,流式接口使用 Server-Sent Events (SSE)。
### 4.1 生产环境架构
为了满足高并发(500+ QPS)及稳定性要求,架构设计如下:
### 4.2 鉴权流程 (Simplified RBAC)
- **当前机制**: 基于 Header 的简易认证 (开发/网关模式)。
- **前端**: `useChat.ts` 或请求拦截器中自动注入 `X-User-Id`, `X-Username`, `X-Role` 头。
- **后端**: `app/decorators.py` 中的 `_get_current_user` 解析 Header,自动查找或创建(Lazy Create)数据库用户对象,并注入到 Flask全局变量 `g` 中。
1. **Nginx (接入层)**:
- 监听 80/443 端口。
- **关键配置**: `proxy_buffering off;` (必须关闭缓冲以支持 SSE 流式响应)。
- 提供前端静态资源 (`/dist`) 服务,开启 Gzip 压缩。
### 4.3 核心链路:AI 对话流
1. **用户提问**: 前端 `ChatView` 调用 `useChat.sendMessage`,发起 `POST /api/chat/completions`。
2. **权限校验**: 后端 `chat.py` 使用 `@require_agent_permission` 校验用户是否有权访问该 Agent。
3. **代理转发**: 调用 `DifyService.stream_chat`,使用 Agent 配置的 API Key 向 Dify 服务发起请求。
4. **流式响应**: Dify 返回 SSE 数据流,后端通过 Python生成器 (`yield`) 逐块透传给前端。
5. **审计记录**: 对话结束 (`message_end` 事件) 时,后端自动将完整问答、Token 消耗、耗时写入 `chat_logs` 表。
2. **Supervisor (进程管理)**:
- 守护 `hxops-backend` 进程,负责自动重启和日志管理。
3. **Gunicorn + Gevent (应用层)**:
- 运行 Flask 应用。
- **Worker**: `gevent` (异步模式)。
- **并发**: `workers = CPU * 2 + 1`, `worker_connections = 1000+`。
- 监听 `127.0.0.1:5002`。
4. **PostgreSQL (数据层)**:
- 存储用户、应用配置及审计日志。
### 4.2 CI/CD 工作流
采用 **本地开发 -> Gitee 托管 -> 服务器拉取** 的流程:
1. **本地开发 (Local)**:
- 代码修改 -> `git push origin super`。
- 仓库: `https://gitee.com/justop/hxops.git`
2. **服务器部署 (Server)**:
- 服务器 IP: `192.168.100.230`
- 执行脚本: `scripts/deploy.sh`
- 自动化步骤:
- 拉取最新代码 (`git pull`).
- 前端构建 (`npm install && npm run build`).
- 后端更新 (`pip install && flask db upgrade`).
- 服务重启 (`supervisorctl restart`).
## 5. 🗄️ 核心数据模型 (Database Models)
- **User**: 用户表 (id, username, role, department)。
- **Agent**: AI 应用配置表 (id, name, dify_app_id, dify_api_key, api_base_url)。
- *关键字段*: `type` (api/iframe), `is_active`。
- **user_agent_permissions**: 多对多关联表,控制 User 对 Agent 的访问权限。
- **ChatLog**: 审计日志表 (user_id, agent_id, query, answer, tokens_used, conversation_id)。
- **UserHomepageConfig**: 用户个性化配置 (收藏的 Agent, 首页布局)。
- **User**: 用户表 (RBAC 基础, 包含 `role`, `department_id`).
- **Agent**: AI 应用配置 (Dify App ID, API Key, 图标, 描述).
- **ChatLog**: 对话审计日志 (记录 `query`, `answer`, `tokens`, `duration`).
- **Department**: 部门表 (组织架构).
- **UserHomepageConfig**: 用户个性化配置 (常用应用, 快捷问题).
- **Conversation**: 对话会话记录 (关联 Dify Conversation ID).
## 6. 📝 待办事项与技术债 (TODOs)
## 6. 📝 常用维护命令 (Cheatsheet)
- [ ] **鉴权升级**: 目前使用 Header 透传用户信息,生产环境需对接 SSO (OAuth2/OIDC) 并发放真实 JWT。
- [ ] **网络连通性**: Dify 真实服务 (`192.168.100.230`) 目前不可达,暂时使用了本地 Mock Server (`127.0.0.1:5001`)。需解决网络/防火墙问题。
- [ ] **端口规范**: 后端已从 5000 迁至 5002 以避开 macOS 端口冲突,需确保部署脚本同步更新。
- [ ] **前端重构**: `fetch` 与 `axios` 混用,建议统一封装请求库。
### 后端开发
```bash
cd backend
source venv/bin/activate
# 启动开发服务器
python run.py
# 数据库迁移
flask db migrate -m "message"
flask db upgrade
```
## 7. 🤖 【重要】AI 接手专属 Context 提示词
### 前端开发
```bash
cd frontend
npm run dev
```
```text
你好,我需要你帮我开发/调试一个“企业级 AI 聚合网关”项目。
以下是项目的基础上下文,请阅读并记住,后续你的所有代码生成都必须遵循以下架构和规范:
### 服务器运维
```bash
# 一键部署
./scripts/deploy.sh
1. **技术栈**:
- 前端: Vue 3 + TypeScript + TailwindCSS + Vite。
- 后端: Flask + SQLAlchemy + PostgreSQL (端口 5002)。
2. **核心业务**:
- 这是一个 BFF (Backend for Frontend) 系统,代理用户请求转发给底层 LLM 服务 (如 Dify)。
- 核心功能是 SSE 流式对话、Agent 权限管理(RBAC)、审计日志记录。
3. **关键代码逻辑**:
- 对话逻辑: 前端 `useChat.ts` -> 后端 `api/chat.py` -> `services/dify.py`。
- 鉴权逻辑: 依赖 `X-User-Id` 请求头,通过 `decorators.py` 实现用户自动注入。
4. **数据模型**:
- `Agent` 表存储 Dify API Key 和 Base URL。
- `ChatLog` 表记录所有对话详情。
5. **注意事项**:
- 所有的 API 请求都必须通过 `/api` 前缀。
- 开发环境后端运行在 5002 端口 (5000 被 macOS 占用)。
- 当前连接的是本地 Mock Dify Server (5001),因远程服务网络不通。
- 修改数据库模型后必须生成并应用 Alembic 迁移。
# 查看后端日志
tail -f /opt/hxops/backend/logs/app.log
# 重启服务
sudo supervisorctl restart hxops-backend
```