feat: 重构项目为前后端分离架构并添加RBAC系统
- 将项目重构为前后端分离架构,前端使用Vue 3 + Element Plus,后端使用Flask - 实现基于JWT的身份认证系统,提供登录/登出和用户信息获取API - 引入基于角色的访问控制(RBAC)系统,支持角色继承和权限管理 - 添加数据隔离机制,研究员只能访问自己的数据,管理员拥有全局权限 - 实现数据时间控制功能,支持设置开始时间和永久性标记 - 创建前端管理界面,包括用户管理、角色管理、权限管理和操作日志 - 重构项目结构,分离前后端代码,更新README说明文档 - 添加数据库迁移脚本,支持RBAC相关表的创建和更新 - 集成Vue Router和Pinia状态管理,构建完整的前端应用架构 - 提供字体文件管理和静态资源缓存优化
This commit is contained in:
1 parent
355709fec0
commit
587b36a7fa
188 files changed
+7852
-105
No files matched your search
@@ -1,4 +0,0 @@
|
||||
# .env
|
||||
FLASK_APP=run.py
|
||||
FLASK_CONFIG=development
|
||||
DATABASE_URL=mysql+pymysql://root:LOpl23!!qq@rm-uf6r6oxm005vmy9flho.mysql.rds.aliyuncs.com/rct
|
||||
+19
-91
@@ -1,96 +1,24 @@
|
||||
# === OS Generated Files ===
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# === IDE and Editors ===
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.project
|
||||
.settings/
|
||||
.classpath
|
||||
.factorypath
|
||||
|
||||
# === Python and Flask ===
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
.venv/
|
||||
venv/
|
||||
ENV/
|
||||
env/
|
||||
.env/
|
||||
.conda/
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
.toast
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
instance/
|
||||
.webassets-cache
|
||||
.flaskenv
|
||||
|
||||
# === Database ===
|
||||
*.db
|
||||
*.sqlite3
|
||||
|
||||
# === Environment Files ===
|
||||
.env
|
||||
.env.local
|
||||
.env.dev
|
||||
.env.test
|
||||
.env.prod
|
||||
|
||||
# === Logs ===
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# === Project Specific Storage (User Data) ===
|
||||
uploads/
|
||||
raw_data_storage/
|
||||
processed_data_output/
|
||||
temp_extract_*/
|
||||
|
||||
# === Node.js (If applicable) ===
|
||||
node_modules/
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.npm
|
||||
.yarn-integrity
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# === Fonts and Assets (Optional Source) ===
|
||||
sans/
|
||||
__MACOSX/
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,234 @@
|
||||
# 下一阶段计划:完成全部 API 迁移与对应页面构建
|
||||
|
||||
## 0. 范围与目标
|
||||
本阶段目标是让系统具备“纯前后端分离”可用性:前端 Vue 覆盖现有功能页面;后端 Flask 提供等价能力的 `/api` 接口(JSON + 文件下载),并以 JWT 作为鉴权基础。
|
||||
|
||||
覆盖范围以现有 Flask SSR 功能为准(main/auth/admin 三个蓝图),对应代码主要在:
|
||||
- [main/routes.py](file:///c:/Users/Administrator/Desktop/rct/backend/app/main/routes.py)
|
||||
- [auth/routes.py](file:///c:/Users/Administrator/Desktop/rct/backend/app/auth/routes.py)
|
||||
- [admin/routes.py](file:///c:/Users/Administrator/Desktop/rct/backend/app/admin/routes.py)
|
||||
|
||||
现有 API 端点(已完成但不完整)在:
|
||||
- [app/api](file:///c:/Users/Administrator/Desktop/rct/backend/app/api)
|
||||
|
||||
## 1. 后端:API 迁移设计
|
||||
|
||||
### 1.1 API 基础规范(统一约定)
|
||||
1) 路由前缀与版本
|
||||
- 继续使用 `/api` 作为前缀;如需版本化,采用 `/api/v1`(本阶段可先不引入版本,预留目录结构即可)。
|
||||
|
||||
2) 返回格式
|
||||
- 成功:直接返回业务 JSON(列表/对象/分页结构)
|
||||
- 失败:`{"msg": "...", "code": "...", "details": {...}}`(至少保证 `msg`)
|
||||
|
||||
3) 分页/排序/过滤
|
||||
- 通用查询参数:`page`、`per_page`、`q`、`sort`、`order`
|
||||
- 统一分页返回:
|
||||
- `{"items": [...], "page": 1, "per_page": 20, "total": 123}`
|
||||
|
||||
4) 权限与鉴权
|
||||
- 鉴权:JWT(现状已支持,见 [api/auth.py](file:///c:/Users/Administrator/Desktop/rct/backend/app/api/auth.py))
|
||||
- 权限:复用现有 RBAC 能力(`User.has_permission()` / `User.get_all_permissions()`),见 [models.py](file:///c:/Users/Administrator/Desktop/rct/backend/app/models.py)
|
||||
- 需要补齐 API 侧的装饰器/校验逻辑(参考 SSR 的 [decorators.py](file:///c:/Users/Administrator/Desktop/rct/backend/app/decorators.py)),提供:
|
||||
- `admin_required_jwt`
|
||||
- `permission_required_jwt(permission_name)`
|
||||
- `data_access_required_jwt(model, id_param=...)`(用于 DataEntry/Attachment/RawDataFolder 等资源)
|
||||
|
||||
5) 文件下载
|
||||
- 附件下载、CSV 导出、处理产物 ZIP 下载、推理结果 CSV 下载统一走 `send_from_directory` / `send_file`,前端以 `blob` 方式下载。
|
||||
|
||||
### 1.2 需要补齐的 API 清单(按模块)
|
||||
|
||||
#### A. Auth(认证)
|
||||
- `POST /api/auth/login`(已存在)
|
||||
- `GET /api/auth/me`(已存在)
|
||||
- 可选增强(视需求决定是否实现):
|
||||
- `POST /api/auth/logout`(前端仅清 token 也可)
|
||||
- `POST /api/auth/refresh`(Access/Refresh 机制)
|
||||
|
||||
#### B. Main(仪表盘/通知)
|
||||
- `GET /api/dashboard`(已存在,但建议分页/字段裁剪)
|
||||
- `GET /api/notifications`(已存在,建议增加分页)
|
||||
- 建议补齐:
|
||||
- `GET /api/data-entries/:id`(数据详情;供 Dashboard 点击查看)
|
||||
|
||||
#### C. Search(搜索与建议)
|
||||
将 SSR 的 `/search` 与 `/search/suggestions` 迁移为 API:
|
||||
- `GET /api/search?q=...&scope=data|notification|folder`(或 `POST`,返回结构含 3 类结果)
|
||||
- 逻辑参考 [main/routes.py search](file:///c:/Users/Administrator/Desktop/rct/backend/app/main/routes.py#L14-L91)
|
||||
- `GET /api/search/suggestions?q=...`(返回最多 10 条)
|
||||
- 逻辑参考 [main/routes.py search_suggestions](file:///c:/Users/Administrator/Desktop/rct/backend/app/main/routes.py#L93-L195)
|
||||
|
||||
#### D. Admin - Users(用户管理)
|
||||
现有仅 `GET/POST /api/admin/users`(见 [api/admin.py](file:///c:/Users/Administrator/Desktop/rct/backend/app/api/admin.py)),需补齐:
|
||||
- `GET /api/admin/users/:id`
|
||||
- `PATCH /api/admin/users/:id`(编辑用户:username/email/role/roles/password)
|
||||
- `POST /api/admin/users/:id/toggle-status`(启用/禁用)
|
||||
- `DELETE /api/admin/users/:id`
|
||||
|
||||
#### E. Admin - RBAC(角色/权限/审计日志)
|
||||
对齐 SSR 功能(见 [admin/routes.py RBAC](file:///c:/Users/Administrator/Desktop/rct/backend/app/admin/routes.py)):
|
||||
- Roles
|
||||
- `GET /api/admin/roles`
|
||||
- `POST /api/admin/roles`
|
||||
- `GET /api/admin/roles/:id`
|
||||
- `PATCH /api/admin/roles/:id`(含 parent_id/permissions)
|
||||
- `DELETE /api/admin/roles/:id`(需要校验 children)
|
||||
- Permissions
|
||||
- `GET /api/admin/permissions`
|
||||
- `POST /api/admin/permissions`
|
||||
- `DELETE /api/admin/permissions/:id`
|
||||
- Permission Logs
|
||||
- `GET /api/admin/permission-logs?page=&per_page=`
|
||||
|
||||
#### F. Admin - DataEntry(数据条目/可见性/附件/导出)
|
||||
这是前端管理端最核心的一块(SSR 对应 [manage_data](file:///c:/Users/Administrator/Desktop/rct/backend/app/admin/routes.py#L125-L189) 等):
|
||||
- `GET /api/admin/data-entries?page=&per_page=&q=&researcher_id=...`
|
||||
- `POST /api/admin/data-entries`
|
||||
- 支持 multipart:`csv_file`、`attachments[]`、基础字段(title/content/is_permanent/start_date/expiration_date/researcher_id/visible_user_ids[])
|
||||
- `GET /api/admin/data-entries/:id`
|
||||
- `PATCH /api/admin/data-entries/:id`
|
||||
- `DELETE /api/admin/data-entries/:id`
|
||||
- `POST /api/admin/data-entries/batch-delete`(ids[])
|
||||
- 附件/CSV/导出
|
||||
- `GET /api/attachments/:id/download`
|
||||
- `GET /api/admin/data-entries/:id/csv`(下载原 CSV,或返回解析后的 table 数据)
|
||||
- `GET /api/admin/data-entries/export?format=csv`(返回文件)
|
||||
|
||||
#### G. Admin - Uploads(批量上传/预览/历史)
|
||||
现有 API 仅单文件上传(`POST /api/admin/upload`),需对齐 SSR:
|
||||
- `POST /api/admin/uploads/archives`(多文件上传 zip/rar/7z 并写 UploadLog)
|
||||
- `POST /api/admin/uploads/preview-archive`(预览 zip 内容)
|
||||
- `GET /api/admin/uploads/history?page=&per_page=`(上传历史列表)
|
||||
|
||||
#### H. Admin - Integration(整合任务:文件夹/作业/summary/产物下载)
|
||||
对齐 SSR integration-manager(见 [integration_manager](file:///c:/Users/Administrator/Desktop/rct/backend/app/admin/routes.py#L227-L311)):
|
||||
- `GET /api/admin/integration/folders?page=&per_page=&status=&researcher_id=`
|
||||
- `PATCH /api/admin/integration/folders/:id`(分配 researcher)
|
||||
- `POST /api/admin/integration/jobs`(触发整合:folder_id)
|
||||
- `GET /api/admin/integration/jobs?page=&per_page=`(作业列表/状态/日志)
|
||||
- `GET /api/admin/integration/folders/:id/summary`(segments/summary JSON;参考 [view_summary](file:///c:/Users/Administrator/Desktop/rct/backend/app/admin/routes.py#L362-L390))
|
||||
- `GET /api/admin/integration/folders/:id/download-processed`(ZIP 下载;参考 [download_processed_folder](file:///c:/Users/Administrator/Desktop/rct/backend/app/admin/routes.py#L392-L422))
|
||||
- `POST /api/admin/integration/folders/batch-assign-researcher`
|
||||
|
||||
#### I. Admin - Inference(推理任务/历史/结果)
|
||||
对齐 SSR inference-manager(见 [inference_manager](file:///c:/Users/Administrator/Desktop/rct/backend/app/admin/routes.py#L470-L483)):
|
||||
- `GET /api/admin/inference/folders`(可推理文件夹:status=completed)
|
||||
- `POST /api/admin/inference/jobs`(触发推理:folder_id)
|
||||
- `GET /api/admin/inference/results?page=&per_page=`(推理历史)
|
||||
- `GET /api/admin/inference/results/:id/download`(下载结果 CSV;若存储在本地)
|
||||
|
||||
### 1.3 后端实现策略(避免重复造轮子)
|
||||
1) 代码组织
|
||||
- 在 [app/api](file:///c:/Users/Administrator/Desktop/rct/backend/app/api) 下按领域拆分模块:`auth.py/search.py/admin_users.py/admin_rbac.py/admin_data.py/admin_uploads.py/admin_integration.py/admin_inference.py/main.py`。
|
||||
|
||||
2) 复用既有业务逻辑
|
||||
- 将 SSR 路由中“数据库查询/权限过滤/文件生成”的代码抽到可复用函数(例如 `services/` 或 `app/*/service.py`),API 与 SSR 同时调用,减少分叉。
|
||||
|
||||
3) 权限校验统一化
|
||||
- API 层使用 JWT identity 获取 User,再调用与 SSR 一致的 `is_admin()/has_permission()/data_access` 逻辑。
|
||||
|
||||
4) 数据模型与文件系统的一致性
|
||||
- integration/inference 涉及本地文件(processed_data_output、attachments、uploads),API 端点需要明确返回“文件名/下载 URL/状态字段”,并且为前端轮询提供稳定的 job/status 查询能力。
|
||||
|
||||
## 2. 前端:页面构建计划(Vue)
|
||||
|
||||
### 2.1 关键修正(先决条件)
|
||||
- 将 [App.vue](file:///c:/Users/Administrator/Desktop/rct/frontend/src/App.vue) 改为仅承载路由容器(`<router-view/>`),否则所有页面路由无法生效。
|
||||
|
||||
### 2.2 路由与菜单规划
|
||||
现有路由很少(见 [router/index.js](file:///c:/Users/Administrator/Desktop/rct/frontend/src/router/index.js)),本阶段扩展为三类:
|
||||
|
||||
1) 公共
|
||||
- `/login`
|
||||
|
||||
2) 登录后主应用(Layout:沿用 [MainLayout.vue](file:///c:/Users/Administrator/Desktop/rct/frontend/src/layout/MainLayout.vue))
|
||||
- `/dashboard`(数据列表)
|
||||
- `/notifications`(公告列表)
|
||||
- `/search`(全局搜索/建议)
|
||||
- `/profile`(展示 `/api/auth/me` 返回的权限/信息)
|
||||
- `/data/:id`(数据详情:content/附件/CSV)
|
||||
|
||||
3) 管理端(仅管理员或具备权限的用户可见)
|
||||
- `/admin/users`
|
||||
- `/admin/roles`
|
||||
- `/admin/permissions`
|
||||
- `/admin/permission-logs`
|
||||
- `/admin/data-entries`
|
||||
- `/admin/notifications`
|
||||
- `/admin/uploads`
|
||||
- `/admin/integration`
|
||||
- `/admin/inference`
|
||||
|
||||
守卫策略:
|
||||
- 在路由 meta 中支持 `requiresAuth`、`requiresAdmin`、`requiredPerms`。
|
||||
- 登录后优先调用 `/api/auth/me` 拉取 `permissions`,以 permissions 细粒度控制菜单可见性与路由访问。
|
||||
|
||||
### 2.3 页面清单与对应 API
|
||||
1) 登录页
|
||||
- 调用:`POST /api/auth/login`,保存 token/user(现状已做)
|
||||
|
||||
2) 仪表盘
|
||||
- 调用:`GET /api/dashboard`(建议分页化后对应更新)
|
||||
- 交互:点击进入 `/data/:id`
|
||||
|
||||
3) 通知列表页
|
||||
- 调用:`GET /api/notifications`
|
||||
|
||||
4) 搜索页
|
||||
- 调用:`GET /api/search/suggestions`(输入联想)
|
||||
- 调用:`GET /api/search`(结果)
|
||||
|
||||
5) 用户管理页(升级现有 [Users.vue](file:///c:/Users/Administrator/Desktop/rct/frontend/src/views/admin/Users.vue))
|
||||
- 调用:users CRUD + toggle-status
|
||||
|
||||
6) 角色/权限/审计
|
||||
- 调用:roles CRUD、permissions CRUD、permission-logs 列表
|
||||
|
||||
7) 数据条目管理页
|
||||
- 调用:data-entries 列表/创建/编辑/删除/批量删除/导出
|
||||
- 上传:multipart(CSV + 附件)
|
||||
- 下载:附件/CSV/导出文件(blob)
|
||||
|
||||
8) 上传与历史
|
||||
- 调用:批量上传、预览压缩包、历史分页
|
||||
|
||||
9) 数据整合
|
||||
- 调用:folders 列表(分页/过滤)、分配 researcher、创建 job、job 列表轮询、summary 展示、processed 下载
|
||||
|
||||
10) AI 推理
|
||||
- 调用:可推理 folders、触发推理、历史查询、结果下载
|
||||
|
||||
### 2.4 前端工程化约定
|
||||
- API baseURL 由环境变量提供(例如 `VITE_API_BASE_URL`),替代硬编码(当前 [api/index.js](file:///c:/Users/Administrator/Desktop/rct/frontend/src/api/index.js) 写死 `http://localhost:5000/api`)。
|
||||
- 统一请求封装:
|
||||
- 列表请求支持分页参数与标准返回结构
|
||||
- 统一错误提示(401 已处理,403/500 需要 UI 提示)
|
||||
- 通用组件:
|
||||
- 表格 + 分页、表单弹窗、文件上传组件、下载按钮组件
|
||||
|
||||
## 3. 迁移顺序(执行时的推进路径)
|
||||
为保证“可运行、可验证、逐步替换 SSR”,执行顺序建议如下:
|
||||
1) 后端:补齐权限装饰器(JWT 版)+ 统一分页响应 + Search API
|
||||
2) 前端:修正 App.vue 路由承载 + 完成 Notifications/Search/Profile
|
||||
3) 后端:Users/RBAC API 完整化
|
||||
4) 前端:Users/RBAC 页面完成(含权限控制)
|
||||
5) 后端:DataEntry/Attachment/Export API 完整化
|
||||
6) 前端:数据条目管理 + 详情/附件/CSV
|
||||
7) 后端:Uploads/Integration/Inference API 完整化
|
||||
8) 前端:Uploads/Integration/Inference 页面与轮询状态
|
||||
|
||||
## 4. 验证与回归(完成定义)
|
||||
后端:
|
||||
- 为新增 API 增加最小单元测试(沿用现有测试风格:[tests](file:///c:/Users/Administrator/Desktop/rct/backend/tests)),至少覆盖:
|
||||
- 登录成功/失败/禁用账号
|
||||
- 403(无权限)与数据隔离(DataEntry/Attachment)
|
||||
- integration/inference 触发与状态查询端点返回结构
|
||||
|
||||
前端:
|
||||
- 手工验收路径(至少):
|
||||
- 登录 -> 仪表盘加载 -> 数据详情查看
|
||||
- 通知列表加载
|
||||
- 搜索建议与结果
|
||||
- 管理员进入 Users/RBAC/DataEntry/Integration/Inference 页面并完成最小操作(列表可见 + 触发动作 + 状态刷新)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# 清理无用资源文件计划
|
||||
|
||||
## 目标
|
||||
清理项目中未使用的资源文件,减少项目体积,保持代码整洁。
|
||||
|
||||
## 分析结果
|
||||
经过对项目的扫描和引用检查,发现以下文件未被使用:
|
||||
|
||||
### Frontend
|
||||
1. **`frontend/src/assets/vue.svg`**
|
||||
- 该文件是 Vue 项目模板自带的 logo 文件。
|
||||
- 经检查,代码中无任何引用(`grep` 搜索无结果)。
|
||||
- `frontend/src/App.vue` 和 `frontend/src/main.js` 中均未引入。
|
||||
|
||||
2. **`frontend/src/components/HelloWorld.vue`**
|
||||
- 该文件是 Vue 项目模板自带的示例组件。
|
||||
- 经检查,`frontend/src/App.vue` 中未引用该组件(通常模板代码会引用,但已被移除)。
|
||||
- 代码中无其他引用。
|
||||
|
||||
### Backend
|
||||
- 对 `backend/app/static` 目录下的 CSS、JS 和字体文件进行了检查。
|
||||
- `style.css` 和 `main.js` 在 `base.html` 模板中被引用,且包含实际业务逻辑和样式。
|
||||
- `HarmonyOS_Sans_SC` 字体文件在 `style.css` 中均被 `@font-face` 引用。
|
||||
- 未发现明显的无用资源文件。
|
||||
|
||||
## 执行计划
|
||||
1. 删除 `frontend/src/assets/vue.svg` [已完成]
|
||||
2. 删除 `frontend/src/components/HelloWorld.vue` [已完成]
|
||||
|
||||
## 验证
|
||||
- 删除后,重新构建或运行前端项目,确保没有因缺失文件导致的报错(虽然已确认为未使用,但需防范动态引用)。
|
||||
@@ -0,0 +1,109 @@
|
||||
# 项目重构计划:前后端分离 (Flask + Vue)
|
||||
|
||||
## 1. 目标
|
||||
将现有的 Flask 单体应用重构为前后端分离架构。
|
||||
- **后端**: Flask (提供 RESTful API)
|
||||
- **前端**: Vue 3 + Vite (单页应用 SPA)
|
||||
|
||||
## 2. 架构设计
|
||||
|
||||
### 2.1 目录结构
|
||||
我们将项目目录重组为以下结构:
|
||||
```
|
||||
rct/
|
||||
├── backend/ # 现有的 Flask 代码移动到这里
|
||||
│ ├── app/
|
||||
│ │ ├── api/ # 新增:RESTful API 蓝图
|
||||
│ │ ├── models.py # 保留:数据库模型
|
||||
│ │ └── ...
|
||||
│ ├── run.py
|
||||
│ └── requirements.txt
|
||||
├── frontend/ # 新增:Vue 3 项目
|
||||
│ ├── src/
|
||||
│ ├── package.json
|
||||
│ └── vite.config.js
|
||||
└── README.md
|
||||
```
|
||||
|
||||
### 2.2 技术栈
|
||||
- **后端**:
|
||||
- 框架: Flask
|
||||
- 接口: Flask-RESTful 或原生 Blueprint
|
||||
- 认证: Flask-JWT-Extended (替代 Flask-Login 进行 Token 认证)
|
||||
- 跨域: Flask-CORS
|
||||
- 数据库: SQLAlchemy (沿用现有)
|
||||
- **前端**:
|
||||
- 框架: Vue 3 (Composition API)
|
||||
- 构建工具: Vite
|
||||
- 路由: Vue Router
|
||||
- 状态管理: Pinia
|
||||
- UI 组件库: Element Plus (适合后台管理系统)
|
||||
- HTTP 客户端: Axios
|
||||
|
||||
## 3. 实施步骤
|
||||
|
||||
### 第一阶段:后端重构 (Backend Refactoring)
|
||||
1. **环境准备**:
|
||||
- 安装 `flask-jwt-extended` 和 `flask-cors`。
|
||||
- 移动现有代码到 `backend/` 目录。
|
||||
2. **API 蓝图创建**:
|
||||
- 创建 `app/api` 模块。
|
||||
- 配置 CORS 支持。
|
||||
3. **认证机制迁移**:
|
||||
- 实现 `/api/auth/login` 接口,返回 JWT Access Token。
|
||||
- 实现 `/api/auth/me` 接口,获取当前用户信息。
|
||||
- 替换 `login_required` 为 `jwt_required`。
|
||||
4. **业务接口迁移**:
|
||||
- **Dashboard**: 将 `main.dashboard` 逻辑转换为 API,返回 JSON 数据。
|
||||
- **Admin**: 将用户管理、角色管理、数据上传等功能转换为 API。
|
||||
- **Integration/Inference**: 暴露触发后台任务和查询状态的 API。
|
||||
|
||||
### 第二阶段:前端开发 (Frontend Development)
|
||||
1. **项目初始化**:
|
||||
- 使用 `npm create vite@latest` 创建 `frontend` 项目。
|
||||
- 安装依赖: `vue-router`, `pinia`, `axios`, `element-plus`, `sass`。
|
||||
2. **基础架构搭建**:
|
||||
- 配置 Axios 拦截器 (自动携带 Token,处理 401 过期)。
|
||||
- 配置 Vue Router (定义路由表,添加导航守卫)。
|
||||
- 配置 Pinia User Store (管理登录状态)。
|
||||
3. **页面开发**:
|
||||
- **登录页**: 实现登录逻辑。
|
||||
- **主布局 (Layout)**: 侧边栏导航、顶部用户信息。
|
||||
- **仪表盘 (Dashboard)**: 展示数据概览。
|
||||
- **管理页面**:
|
||||
- 用户/角色管理 (表格 + 弹窗表单)。
|
||||
- 数据上传与管理。
|
||||
- 整合与推理任务管理 (实时刷新状态)。
|
||||
4. **组件复用**:
|
||||
- 封装通用的表格组件、搜索组件。
|
||||
|
||||
### 第三阶段:联调与部署 (Integration & Deployment)
|
||||
1. **联调**:
|
||||
- 前端连接本地后端进行测试。
|
||||
- 修复接口字段不匹配问题。
|
||||
2. **部署方案**:
|
||||
- **开发环境**: 前端 Vite Server (3000) -> 代理 -> 后端 Flask (5000)。
|
||||
- **生产环境**: 前端构建为静态文件 (`dist/`),由 Flask 托管或 Nginx 独立托管。
|
||||
|
||||
## 4. 待办事项清单 (Todo List)
|
||||
|
||||
### Backend
|
||||
- [ ] 移动现有代码到 `backend/` 文件夹
|
||||
- [ ] 安装 `flask-jwt-extended`, `flask-cors`
|
||||
- [ ] 创建 `app/api` 蓝图并注册
|
||||
- [ ] 实现 JWT 登录接口 (`POST /api/login`)
|
||||
- [ ] 迁移 Dashboard 数据接口 (`GET /api/dashboard`)
|
||||
- [ ] 迁移 Admin 用户管理接口 (CRUD)
|
||||
- [ ] 迁移 Admin 角色/权限管理接口
|
||||
- [ ] 迁移 数据管理/上传接口
|
||||
- [ ] 迁移 整合与推理任务接口
|
||||
|
||||
### Frontend
|
||||
- [ ] 初始化 Vue 3 + Vite 项目
|
||||
- [ ] 安装 Element Plus, Axios, Pinia, Vue Router
|
||||
- [ ] 搭建项目骨架 (Layout, Router, Store)
|
||||
- [ ] 开发登录页面
|
||||
- [ ] 开发仪表盘页面
|
||||
- [ ] 开发用户/权限管理页面
|
||||
- [ ] 开发数据/任务管理页面
|
||||
- [ ] 联调测试
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,96 @@
|
||||
# === OS Generated Files ===
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# === IDE and Editors ===
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.project
|
||||
.settings/
|
||||
.classpath
|
||||
.factorypath
|
||||
|
||||
# === Python and Flask ===
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
.venv/
|
||||
venv/
|
||||
ENV/
|
||||
env/
|
||||
.env/
|
||||
.conda/
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
.toast
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
instance/
|
||||
.webassets-cache
|
||||
.flaskenv
|
||||
|
||||
# === Database ===
|
||||
*.db
|
||||
*.sqlite3
|
||||
|
||||
# === Environment Files ===
|
||||
.env
|
||||
.env.local
|
||||
.env.dev
|
||||
.env.test
|
||||
.env.prod
|
||||
|
||||
# === Logs ===
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# === Project Specific Storage (User Data) ===
|
||||
uploads/
|
||||
raw_data_storage/
|
||||
processed_data_output/
|
||||
temp_extract_*/
|
||||
|
||||
# === Node.js (If applicable) ===
|
||||
node_modules/
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.npm
|
||||
.yarn-integrity
|
||||
|
||||
# === Fonts and Assets (Optional Source) ===
|
||||
sans/
|
||||
__MACOSX/
|
||||
File renamed without changes.
@@ -0,0 +1 @@
|
||||
|
||||
@@ -5,7 +5,12 @@ from flask_login import LoginManager
|
||||
from flask_migrate import Migrate
|
||||
from flask_wtf.csrf import CSRFProtect
|
||||
from flask_compress import Compress
|
||||
from config import config
|
||||
from flask_jwt_extended import JWTManager
|
||||
from flask_cors import CORS
|
||||
try:
|
||||
from ..config import config
|
||||
except ImportError:
|
||||
from config import config
|
||||
|
||||
db = SQLAlchemy()
|
||||
login_manager = LoginManager()
|
||||
@@ -13,6 +18,7 @@ login_manager.login_view = 'auth.login' # 未登录用户访问保护页面时
|
||||
migrate = Migrate()
|
||||
csrf = CSRFProtect()
|
||||
compress = Compress()
|
||||
jwt = JWTManager()
|
||||
|
||||
def create_app(config_name):
|
||||
app = Flask(__name__)
|
||||
@@ -23,6 +29,8 @@ def create_app(config_name):
|
||||
migrate.init_app(app, db)
|
||||
csrf.init_app(app)
|
||||
compress.init_app(app)
|
||||
jwt.init_app(app)
|
||||
CORS(app, resources={r"/api/*": {"origins": "*"}})
|
||||
|
||||
# 注册蓝图
|
||||
from .main import main as main_blueprint
|
||||
@@ -34,6 +42,12 @@ def create_app(config_name):
|
||||
from .admin import admin as admin_blueprint
|
||||
app.register_blueprint(admin_blueprint, url_prefix='/admin')
|
||||
|
||||
from .api import api as api_blueprint
|
||||
app.register_blueprint(api_blueprint, url_prefix='/api')
|
||||
|
||||
# Disable CSRF for API routes
|
||||
csrf.exempt(api_blueprint)
|
||||
|
||||
# 字体文件强缓存策略
|
||||
@app.after_request
|
||||
def add_header(response):
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,16 @@
|
||||
from flask import Blueprint
|
||||
|
||||
api = Blueprint('api', __name__)
|
||||
|
||||
from . import (
|
||||
admin,
|
||||
admin_notifications,
|
||||
admin_rbac,
|
||||
auth,
|
||||
data_entries,
|
||||
inference,
|
||||
integration,
|
||||
routes,
|
||||
search,
|
||||
uploads,
|
||||
)
|
||||
@@ -0,0 +1,183 @@
|
||||
from flask import jsonify, request
|
||||
from flask_jwt_extended import jwt_required
|
||||
|
||||
from .. import db
|
||||
from ..models import Role, User
|
||||
from ..rbac_utils import log_permission_change
|
||||
from . import api
|
||||
from .security import admin_required_jwt, get_current_user, get_pagination_args, permission_required_jwt
|
||||
|
||||
|
||||
@api.route("/admin/users", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_users")
|
||||
def list_users():
|
||||
page, per_page = get_pagination_args(default_per_page=20)
|
||||
q = request.args.get("q", "").strip()
|
||||
|
||||
query = User.query
|
||||
if q:
|
||||
like = f"%{q}%"
|
||||
query = query.filter((User.username.ilike(like)) | (User.email.ilike(like)))
|
||||
|
||||
query = query.order_by(User.id.desc())
|
||||
pagination = query.paginate(page=page, per_page=per_page, error_out=False)
|
||||
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": u.id,
|
||||
"username": u.username,
|
||||
"email": u.email,
|
||||
"role": u.role,
|
||||
"is_active": u.is_active_account,
|
||||
"roles": [{"id": r.id, "name": r.name} for r in u.roles],
|
||||
}
|
||||
for u in pagination.items
|
||||
],
|
||||
"page": pagination.page,
|
||||
"per_page": pagination.per_page,
|
||||
"total": pagination.total,
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/admin/users", methods=["POST"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_users")
|
||||
def create_user():
|
||||
data = request.get_json() or {}
|
||||
username = (data.get("username") or "").strip()
|
||||
email = (data.get("email") or "").strip()
|
||||
password = data.get("password")
|
||||
role_name = (data.get("role") or "user").strip()
|
||||
role_ids = data.get("role_ids") or []
|
||||
|
||||
if not username or not email or not password:
|
||||
return jsonify({"msg": "Missing username/email/password"}), 400
|
||||
|
||||
if User.query.filter((User.username == username) | (User.email == email)).first():
|
||||
return jsonify({"msg": "Username or email already exists"}), 400
|
||||
|
||||
user = User(username=username, email=email, role=role_name)
|
||||
user.set_password(password)
|
||||
|
||||
if role_ids:
|
||||
roles = Role.query.filter(Role.id.in_(role_ids)).all()
|
||||
user.roles = roles
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
operator = get_current_user()
|
||||
log_permission_change((operator.id if operator else user.id), f"Created user {user.username}", "User", user.id)
|
||||
|
||||
return jsonify({"id": user.id}), 201
|
||||
|
||||
|
||||
@api.route("/admin/users/<int:user_id>", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_users")
|
||||
def get_user(user_id):
|
||||
user = User.query.get(user_id)
|
||||
if not user:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"email": user.email,
|
||||
"role": user.role,
|
||||
"is_active": user.is_active_account,
|
||||
"roles": [{"id": r.id, "name": r.name} for r in user.roles],
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/admin/users/<int:user_id>", methods=["PATCH"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_users")
|
||||
def update_user(user_id):
|
||||
user = User.query.get(user_id)
|
||||
if not user:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
data = request.get_json() or {}
|
||||
|
||||
if "username" in data:
|
||||
new_username = (data.get("username") or "").strip()
|
||||
if not new_username:
|
||||
return jsonify({"msg": "Invalid username"}), 400
|
||||
exists = User.query.filter(User.username == new_username, User.id != user.id).first()
|
||||
if exists:
|
||||
return jsonify({"msg": "Username already exists"}), 400
|
||||
user.username = new_username
|
||||
|
||||
if "email" in data:
|
||||
new_email = (data.get("email") or "").strip()
|
||||
if not new_email:
|
||||
return jsonify({"msg": "Invalid email"}), 400
|
||||
exists = User.query.filter(User.email == new_email, User.id != user.id).first()
|
||||
if exists:
|
||||
return jsonify({"msg": "Email already exists"}), 400
|
||||
user.email = new_email
|
||||
|
||||
if "role" in data:
|
||||
user.role = (data.get("role") or "").strip() or user.role
|
||||
|
||||
if "password" in data and data.get("password"):
|
||||
user.set_password(data.get("password"))
|
||||
|
||||
if "role_ids" in data:
|
||||
role_ids = data.get("role_ids") or []
|
||||
roles = Role.query.filter(Role.id.in_(role_ids)).all() if role_ids else []
|
||||
user.roles = roles
|
||||
|
||||
db.session.commit()
|
||||
operator = get_current_user()
|
||||
log_permission_change((operator.id if operator else user.id), f"Updated user {user.username}", "User", user.id)
|
||||
return jsonify({"msg": "ok"}), 200
|
||||
|
||||
|
||||
@api.route("/admin/users/<int:user_id>/toggle-status", methods=["POST"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_users")
|
||||
def toggle_user_status(user_id):
|
||||
user = User.query.get(user_id)
|
||||
if not user:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
user.is_active_account = not user.is_active_account
|
||||
db.session.commit()
|
||||
operator = get_current_user()
|
||||
log_permission_change((operator.id if operator else user.id), f"Toggled user {user.username}", "User", user.id)
|
||||
|
||||
return jsonify({"id": user.id, "is_active": user.is_active_account}), 200
|
||||
|
||||
|
||||
@api.route("/admin/users/<int:user_id>", methods=["DELETE"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_users")
|
||||
def delete_user(user_id):
|
||||
user = User.query.get(user_id)
|
||||
if not user:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
db.session.delete(user)
|
||||
db.session.commit()
|
||||
operator = get_current_user()
|
||||
log_permission_change((operator.id if operator else user.id), f"Deleted user {user.username}", "User", user.id)
|
||||
|
||||
return jsonify({"msg": "deleted"}), 200
|
||||
@@ -0,0 +1,119 @@
|
||||
from flask import jsonify, request
|
||||
from flask_jwt_extended import jwt_required
|
||||
|
||||
from .. import db
|
||||
from ..models import Notification
|
||||
from . import api
|
||||
from .security import admin_required_jwt, permission_required_jwt, get_current_user, get_pagination_args, paginate_query
|
||||
|
||||
|
||||
@api.route("/admin/notifications", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def list_notifications():
|
||||
page, per_page = get_pagination_args(default_per_page=20)
|
||||
q = request.args.get("q", "").strip()
|
||||
|
||||
query = Notification.query
|
||||
if q:
|
||||
like = f"%{q}%"
|
||||
query = query.filter((Notification.title.ilike(like)) | (Notification.content.ilike(like)))
|
||||
|
||||
query = query.order_by(Notification.timestamp.desc())
|
||||
paged = paginate_query(query, page, per_page)
|
||||
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": n.id,
|
||||
"title": n.title,
|
||||
"content": n.content,
|
||||
"timestamp": n.timestamp.isoformat(),
|
||||
"is_published": n.is_published,
|
||||
"author": n.author.username if n.author else None,
|
||||
}
|
||||
for n in paged["items"]
|
||||
],
|
||||
"page": paged["page"],
|
||||
"per_page": paged["per_page"],
|
||||
"total": paged["total"],
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/admin/notifications", methods=["POST"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def create_notification():
|
||||
user = get_current_user()
|
||||
data = request.get_json() or {}
|
||||
title = (data.get("title") or "").strip()
|
||||
content = (data.get("content") or "").strip()
|
||||
is_published = bool(data.get("is_published", False))
|
||||
|
||||
if not title or not content:
|
||||
return jsonify({"msg": "Missing title or content"}), 400
|
||||
|
||||
notif = Notification(title=title, content=content, author=user)
|
||||
notif.is_published = is_published
|
||||
|
||||
db.session.add(notif)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({"id": notif.id}), 201
|
||||
|
||||
|
||||
@api.route("/admin/notifications/<int:notification_id>", methods=["PATCH"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def update_notification(notification_id):
|
||||
notif = Notification.query.get(notification_id)
|
||||
if not notif:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
data = request.get_json() or {}
|
||||
if "title" in data:
|
||||
notif.title = (data.get("title") or "").strip()
|
||||
if "content" in data:
|
||||
notif.content = (data.get("content") or "").strip()
|
||||
if "is_published" in data:
|
||||
notif.is_published = bool(data.get("is_published"))
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({"msg": "ok"}), 200
|
||||
|
||||
|
||||
@api.route("/admin/notifications/<int:notification_id>/toggle-publish", methods=["POST"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def toggle_publish(notification_id):
|
||||
notif = Notification.query.get(notification_id)
|
||||
if not notif:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
notif.is_published = not notif.is_published
|
||||
db.session.commit()
|
||||
return jsonify({"id": notif.id, "is_published": notif.is_published}), 200
|
||||
|
||||
|
||||
@api.route("/admin/notifications/<int:notification_id>", methods=["DELETE"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def delete_notification(notification_id):
|
||||
notif = Notification.query.get(notification_id)
|
||||
if not notif:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
db.session.delete(notif)
|
||||
db.session.commit()
|
||||
return jsonify({"msg": "deleted"}), 200
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
from flask import jsonify, request
|
||||
from flask_jwt_extended import jwt_required
|
||||
|
||||
from .. import db
|
||||
from ..models import Permission, PermissionLog, Role
|
||||
from ..rbac_utils import check_circular_inheritance, log_permission_change
|
||||
from . import api
|
||||
from .security import admin_required_jwt, get_current_user, get_pagination_args, permission_required_jwt
|
||||
|
||||
|
||||
@api.route("/admin/roles", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_roles")
|
||||
def list_roles():
|
||||
roles = Role.query.order_by(Role.name).all()
|
||||
return (
|
||||
jsonify(
|
||||
[
|
||||
{
|
||||
"id": r.id,
|
||||
"name": r.name,
|
||||
"description": r.description,
|
||||
"parent_id": r.parent_id,
|
||||
"permissions": [{"id": p.id, "name": p.name} for p in r.permissions],
|
||||
}
|
||||
for r in roles
|
||||
]
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/admin/roles", methods=["POST"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_roles")
|
||||
def create_role():
|
||||
data = request.get_json() or {}
|
||||
name = (data.get("name") or "").strip()
|
||||
description = (data.get("description") or "").strip() or None
|
||||
parent_id = data.get("parent_id")
|
||||
permission_ids = data.get("permission_ids") or []
|
||||
|
||||
if not name:
|
||||
return jsonify({"msg": "Missing name"}), 400
|
||||
|
||||
if Role.query.filter_by(name=name).first():
|
||||
return jsonify({"msg": "Role name already exists"}), 400
|
||||
|
||||
if parent_id == 0:
|
||||
parent_id = None
|
||||
|
||||
new_role = Role(name=name, description=description, parent_id=parent_id)
|
||||
if permission_ids:
|
||||
perms = Permission.query.filter(Permission.id.in_(permission_ids)).all()
|
||||
new_role.permissions = perms
|
||||
|
||||
db.session.add(new_role)
|
||||
db.session.commit()
|
||||
|
||||
operator = get_current_user()
|
||||
log_permission_change(operator.id, f"Created role {new_role.name}", "Role", new_role.id)
|
||||
|
||||
return jsonify({"id": new_role.id}), 201
|
||||
|
||||
|
||||
@api.route("/admin/roles/<int:role_id>", methods=["PATCH"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_roles")
|
||||
def update_role(role_id):
|
||||
role = Role.query.get(role_id)
|
||||
if not role:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
data = request.get_json() or {}
|
||||
|
||||
if "name" in data:
|
||||
name = (data.get("name") or "").strip()
|
||||
if not name:
|
||||
return jsonify({"msg": "Invalid name"}), 400
|
||||
exists = Role.query.filter(Role.name == name, Role.id != role.id).first()
|
||||
if exists:
|
||||
return jsonify({"msg": "Role name already exists"}), 400
|
||||
role.name = name
|
||||
|
||||
if "description" in data:
|
||||
role.description = (data.get("description") or "").strip() or None
|
||||
|
||||
if "parent_id" in data:
|
||||
parent_id = data.get("parent_id")
|
||||
if parent_id == 0:
|
||||
parent_id = None
|
||||
if parent_id and check_circular_inheritance(role.id, parent_id):
|
||||
return jsonify({"msg": "Circular inheritance detected"}), 400
|
||||
role.parent_id = parent_id
|
||||
|
||||
if "permission_ids" in data:
|
||||
permission_ids = data.get("permission_ids") or []
|
||||
perms = Permission.query.filter(Permission.id.in_(permission_ids)).all() if permission_ids else []
|
||||
role.permissions = perms
|
||||
|
||||
db.session.commit()
|
||||
|
||||
operator = get_current_user()
|
||||
log_permission_change(operator.id, f"Updated role {role.name}", "Role", role.id)
|
||||
|
||||
return jsonify({"msg": "ok"}), 200
|
||||
|
||||
|
||||
@api.route("/admin/roles/<int:role_id>", methods=["DELETE"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_roles")
|
||||
def delete_role(role_id):
|
||||
role = Role.query.get(role_id)
|
||||
if not role:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
if role.children:
|
||||
return jsonify({"msg": "Role has child roles"}), 400
|
||||
|
||||
role_name = role.name
|
||||
db.session.delete(role)
|
||||
db.session.commit()
|
||||
|
||||
operator = get_current_user()
|
||||
log_permission_change(operator.id, f"Deleted role {role_name}", "Role", role_id)
|
||||
|
||||
return jsonify({"msg": "deleted"}), 200
|
||||
|
||||
|
||||
@api.route("/admin/permissions", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_roles")
|
||||
def list_permissions():
|
||||
perms = Permission.query.order_by(Permission.name).all()
|
||||
return jsonify([{"id": p.id, "name": p.name, "description": p.description} for p in perms]), 200
|
||||
|
||||
|
||||
@api.route("/admin/permissions", methods=["POST"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_roles")
|
||||
def create_permission():
|
||||
data = request.get_json() or {}
|
||||
name = (data.get("name") or "").strip()
|
||||
description = (data.get("description") or "").strip() or None
|
||||
|
||||
if not name:
|
||||
return jsonify({"msg": "Missing name"}), 400
|
||||
if Permission.query.filter_by(name=name).first():
|
||||
return jsonify({"msg": "Permission already exists"}), 400
|
||||
|
||||
perm = Permission(name=name, description=description)
|
||||
db.session.add(perm)
|
||||
db.session.commit()
|
||||
|
||||
operator = get_current_user()
|
||||
log_permission_change(operator.id, f"Created permission {perm.name}", "Permission", perm.id)
|
||||
|
||||
return jsonify({"id": perm.id}), 201
|
||||
|
||||
|
||||
@api.route("/admin/permissions/<int:permission_id>", methods=["DELETE"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_roles")
|
||||
def delete_permission(permission_id):
|
||||
perm = Permission.query.get(permission_id)
|
||||
if not perm:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
perm_name = perm.name
|
||||
db.session.delete(perm)
|
||||
db.session.commit()
|
||||
|
||||
operator = get_current_user()
|
||||
log_permission_change(operator.id, f"Deleted permission {perm_name}", "Permission", permission_id)
|
||||
|
||||
return jsonify({"msg": "deleted"}), 200
|
||||
|
||||
|
||||
@api.route("/admin/permission-logs", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("view_audit_logs")
|
||||
def permission_logs():
|
||||
page, per_page = get_pagination_args(default_per_page=20)
|
||||
query = PermissionLog.query.order_by(PermissionLog.timestamp.desc())
|
||||
pagination = query.paginate(page=page, per_page=per_page, error_out=False)
|
||||
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": l.id,
|
||||
"timestamp": l.timestamp.isoformat(),
|
||||
"user_id": l.user_id,
|
||||
"operator": l.operator.username if l.operator else None,
|
||||
"action": l.action,
|
||||
"target_type": l.target_type,
|
||||
"target_id": l.target_id,
|
||||
"details": l.details,
|
||||
}
|
||||
for l in pagination.items
|
||||
],
|
||||
"page": pagination.page,
|
||||
"per_page": pagination.per_page,
|
||||
"total": pagination.total,
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
@@ -0,0 +1,57 @@
|
||||
from flask import jsonify, request
|
||||
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
|
||||
from ..models import User
|
||||
from . import api
|
||||
|
||||
@api.route('/auth/login', methods=['POST'])
|
||||
def login():
|
||||
if not request.is_json:
|
||||
return jsonify({"msg": "Missing JSON in request"}), 400
|
||||
|
||||
data = request.get_json()
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
|
||||
if not username or not password:
|
||||
return jsonify({"msg": "Missing username or password"}), 400
|
||||
|
||||
user = User.query.filter_by(username=username).first()
|
||||
|
||||
if user and user.check_password(password):
|
||||
if not user.is_active:
|
||||
return jsonify({"msg": "Account is disabled"}), 403
|
||||
|
||||
# Create token with user ID as identity
|
||||
access_token = create_access_token(identity=str(user.id))
|
||||
|
||||
return jsonify({
|
||||
"access_token": access_token,
|
||||
"user": {
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"role": user.role,
|
||||
"is_admin": user.is_admin(),
|
||||
"is_researcher": user.is_researcher()
|
||||
}
|
||||
}), 200
|
||||
|
||||
return jsonify({"msg": "Bad username or password"}), 401
|
||||
|
||||
@api.route('/auth/me', methods=['GET'])
|
||||
@jwt_required()
|
||||
def me():
|
||||
current_user_id = get_jwt_identity()
|
||||
user = User.query.get(int(current_user_id))
|
||||
|
||||
if not user:
|
||||
return jsonify({"msg": "User not found"}), 404
|
||||
|
||||
return jsonify({
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"email": user.email,
|
||||
"role": user.role,
|
||||
"is_admin": user.is_admin(),
|
||||
"is_researcher": user.is_researcher(),
|
||||
"permissions": list(user.get_all_permissions())
|
||||
}), 200
|
||||
@@ -0,0 +1,324 @@
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
import pandas as pd
|
||||
from flask import Response, current_app, jsonify, request, send_from_directory
|
||||
from flask_jwt_extended import jwt_required
|
||||
from sqlalchemy import or_
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
from .. import db
|
||||
from ..models import Attachment, DataEntry, User
|
||||
from . import api
|
||||
from .security import (
|
||||
admin_required_jwt,
|
||||
data_access_required_jwt,
|
||||
get_current_user,
|
||||
get_pagination_args,
|
||||
permission_required_jwt,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/data-entries/<int:entry_id>", methods=["GET"])
|
||||
@jwt_required()
|
||||
@data_access_required_jwt(DataEntry, id_param="entry_id")
|
||||
def get_data_entry(entry_id):
|
||||
entry = DataEntry.query.get(entry_id)
|
||||
if not entry:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"id": entry.id,
|
||||
"title": entry.title,
|
||||
"content": entry.content,
|
||||
"timestamp": entry.timestamp.isoformat(),
|
||||
"is_permanent": entry.is_permanent,
|
||||
"start_date": entry.start_date.isoformat() if entry.start_date else None,
|
||||
"expiration_date": entry.expiration_date.isoformat() if entry.expiration_date else None,
|
||||
"researcher_id": entry.researcher_id,
|
||||
"researcher": entry.researcher.username if entry.researcher else None,
|
||||
"associated_filename": entry.associated_filename,
|
||||
"visible_user_ids": [u.id for u in entry.visible_to_users],
|
||||
"attachments": [
|
||||
{"id": a.id, "original_name": a.original_name, "filename": a.filename, "upload_time": a.upload_time.isoformat()}
|
||||
for a in entry.attachments
|
||||
],
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/attachments/<int:attachment_id>/download", methods=["GET"])
|
||||
@jwt_required()
|
||||
@data_access_required_jwt(Attachment, id_param="attachment_id")
|
||||
def download_attachment(attachment_id):
|
||||
attachment = Attachment.query.get(attachment_id)
|
||||
if not attachment:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
directory = current_app.config["ATTACHMENTS_FOLDER"]
|
||||
return send_from_directory(directory, attachment.filename, as_attachment=True, download_name=attachment.original_name)
|
||||
|
||||
|
||||
@api.route("/admin/data-entries", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def list_data_entries():
|
||||
page, per_page = get_pagination_args(default_per_page=20)
|
||||
q = request.args.get("q", "").strip()
|
||||
researcher_id = request.args.get("researcher_id", type=int)
|
||||
|
||||
query = DataEntry.query
|
||||
if q:
|
||||
like = f"%{q}%"
|
||||
query = query.filter(or_(DataEntry.title.ilike(like), DataEntry.content.ilike(like)))
|
||||
if researcher_id:
|
||||
query = query.filter(DataEntry.researcher_id == researcher_id)
|
||||
|
||||
query = query.order_by(DataEntry.timestamp.desc())
|
||||
pagination = query.paginate(page=page, per_page=per_page, error_out=False)
|
||||
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": e.id,
|
||||
"title": e.title,
|
||||
"timestamp": e.timestamp.isoformat(),
|
||||
"researcher_id": e.researcher_id,
|
||||
"researcher": e.researcher.username if e.researcher else None,
|
||||
"is_permanent": e.is_permanent,
|
||||
"start_date": e.start_date.isoformat() if e.start_date else None,
|
||||
"expiration_date": e.expiration_date.isoformat() if e.expiration_date else None,
|
||||
"visible_user_count": e.visible_to_users.count() if hasattr(e.visible_to_users, "count") else len(e.visible_to_users),
|
||||
"attachment_count": e.attachments.count() if hasattr(e.attachments, "count") else len(e.attachments),
|
||||
"associated_filename": e.associated_filename,
|
||||
}
|
||||
for e in pagination.items
|
||||
],
|
||||
"page": pagination.page,
|
||||
"per_page": pagination.per_page,
|
||||
"total": pagination.total,
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/admin/data-entries", methods=["POST"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def create_data_entry():
|
||||
form = request.form
|
||||
title = (form.get("title") or "").strip()
|
||||
content = (form.get("content") or "").strip()
|
||||
|
||||
if not title or not content:
|
||||
return jsonify({"msg": "Missing title or content"}), 400
|
||||
|
||||
is_permanent = (form.get("is_permanent", "true").lower() in ("true", "1", "yes", "on"))
|
||||
start_date = form.get("start_date")
|
||||
expiration_date = form.get("expiration_date")
|
||||
researcher_id = form.get("researcher_id", type=int)
|
||||
|
||||
start_dt = datetime.fromisoformat(start_date) if start_date else None
|
||||
exp_dt = datetime.fromisoformat(expiration_date) if expiration_date else None
|
||||
|
||||
csv_file = request.files.get("csv_file")
|
||||
associated_filename = None
|
||||
if csv_file and csv_file.filename:
|
||||
associated_filename = secure_filename(csv_file.filename)
|
||||
csv_path = os.path.join(current_app.config["UPLOAD_FOLDER"], associated_filename)
|
||||
csv_file.save(csv_path)
|
||||
|
||||
entry = DataEntry(
|
||||
title=title,
|
||||
content=content,
|
||||
associated_filename=associated_filename,
|
||||
is_permanent=is_permanent,
|
||||
start_date=start_dt,
|
||||
expiration_date=exp_dt,
|
||||
researcher_id=researcher_id if researcher_id else None,
|
||||
)
|
||||
|
||||
visible_user_ids = form.getlist("visible_user_ids")
|
||||
if visible_user_ids:
|
||||
ids = [int(x) for x in visible_user_ids if str(x).isdigit()]
|
||||
if ids:
|
||||
users = User.query.filter(User.id.in_(ids)).all()
|
||||
for u in users:
|
||||
entry.visible_to_users.append(u)
|
||||
|
||||
attachment_files = request.files.getlist("attachments")
|
||||
if attachment_files:
|
||||
for f in attachment_files:
|
||||
if not f or not f.filename:
|
||||
continue
|
||||
original_name = secure_filename(f.filename)
|
||||
timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S_%f")
|
||||
filename = f"{timestamp}_{original_name}"
|
||||
filepath = os.path.join(current_app.config["ATTACHMENTS_FOLDER"], filename)
|
||||
f.save(filepath)
|
||||
|
||||
attachment = Attachment(filename=filename, original_name=original_name, data_entry=entry)
|
||||
db.session.add(attachment)
|
||||
|
||||
db.session.add(entry)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({"id": entry.id}), 201
|
||||
|
||||
|
||||
@api.route("/admin/data-entries/<int:entry_id>", methods=["PATCH"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def update_data_entry(entry_id):
|
||||
entry = DataEntry.query.get(entry_id)
|
||||
if not entry:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
data = request.get_json() or {}
|
||||
if "title" in data:
|
||||
entry.title = (data.get("title") or "").strip()
|
||||
if "content" in data:
|
||||
entry.content = (data.get("content") or "").strip()
|
||||
if "is_permanent" in data:
|
||||
entry.is_permanent = bool(data.get("is_permanent"))
|
||||
if "start_date" in data:
|
||||
entry.start_date = datetime.fromisoformat(data.get("start_date")) if data.get("start_date") else None
|
||||
if "expiration_date" in data:
|
||||
entry.expiration_date = datetime.fromisoformat(data.get("expiration_date")) if data.get("expiration_date") else None
|
||||
if "researcher_id" in data:
|
||||
entry.researcher_id = data.get("researcher_id") or None
|
||||
|
||||
if "visible_user_ids" in data:
|
||||
ids = data.get("visible_user_ids") or []
|
||||
users = User.query.filter(User.id.in_(ids)).all() if ids else []
|
||||
entry.visible_to_users = users
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({"msg": "ok"}), 200
|
||||
|
||||
|
||||
@api.route("/admin/data-entries/<int:entry_id>", methods=["DELETE"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def delete_data_entry(entry_id):
|
||||
entry = DataEntry.query.get(entry_id)
|
||||
if not entry:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
for attachment in entry.attachments:
|
||||
try:
|
||||
filepath = os.path.join(current_app.config["ATTACHMENTS_FOLDER"], attachment.filename)
|
||||
if os.path.exists(filepath):
|
||||
os.remove(filepath)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if entry.associated_filename:
|
||||
try:
|
||||
csv_path = os.path.join(current_app.config["UPLOAD_FOLDER"], entry.associated_filename)
|
||||
if os.path.exists(csv_path):
|
||||
os.remove(csv_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
db.session.delete(entry)
|
||||
db.session.commit()
|
||||
return jsonify({"msg": "deleted"}), 200
|
||||
|
||||
|
||||
@api.route("/admin/data-entries/batch-delete", methods=["POST"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def batch_delete_data_entries():
|
||||
data = request.get_json() or {}
|
||||
ids = data.get("ids") or []
|
||||
if not ids:
|
||||
return jsonify({"msg": "No ids"}), 400
|
||||
|
||||
deleted = 0
|
||||
for entry_id in ids:
|
||||
entry = DataEntry.query.get(entry_id)
|
||||
if not entry:
|
||||
continue
|
||||
|
||||
for attachment in entry.attachments:
|
||||
try:
|
||||
filepath = os.path.join(current_app.config["ATTACHMENTS_FOLDER"], attachment.filename)
|
||||
if os.path.exists(filepath):
|
||||
os.remove(filepath)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if entry.associated_filename:
|
||||
try:
|
||||
csv_path = os.path.join(current_app.config["UPLOAD_FOLDER"], entry.associated_filename)
|
||||
if os.path.exists(csv_path):
|
||||
os.remove(csv_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
db.session.delete(entry)
|
||||
deleted += 1
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({"deleted": deleted}), 200
|
||||
|
||||
|
||||
@api.route("/admin/data-entries/<int:entry_id>/csv", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def download_data_entry_csv(entry_id):
|
||||
entry = DataEntry.query.get(entry_id)
|
||||
if not entry:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
if not entry.associated_filename:
|
||||
return jsonify({"msg": "No csv"}), 404
|
||||
|
||||
directory = current_app.config["UPLOAD_FOLDER"]
|
||||
return send_from_directory(directory, entry.associated_filename, as_attachment=True, download_name=entry.associated_filename)
|
||||
|
||||
|
||||
@api.route("/admin/data-entries/export", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("manage_data")
|
||||
def export_data_entries():
|
||||
data_entries = DataEntry.query.all()
|
||||
data = []
|
||||
for entry in data_entries:
|
||||
data.append(
|
||||
{
|
||||
"ID": entry.id,
|
||||
"Title": entry.title,
|
||||
"Content": entry.content,
|
||||
"Researcher": entry.researcher.username if entry.researcher else "N/A",
|
||||
"Created At": entry.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"Is Permanent": "Yes" if entry.is_permanent else "No",
|
||||
"Start Date": entry.start_date.strftime("%Y-%m-%d %H:%M:%S") if entry.start_date else "N/A",
|
||||
"Expiration Date": entry.expiration_date.strftime("%Y-%m-%d %H:%M:%S") if entry.expiration_date else "N/A",
|
||||
"Visible To Users": ", ".join([u.username for u in entry.visible_to_users]),
|
||||
}
|
||||
)
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
output = df.to_csv(index=False, encoding="utf-8-sig")
|
||||
|
||||
filename = f"data_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.csv"
|
||||
return Response(
|
||||
output,
|
||||
mimetype="text/csv",
|
||||
headers={"Content-disposition": f"attachment; filename={filename}"},
|
||||
)
|
||||
@@ -0,0 +1,150 @@
|
||||
import os
|
||||
import threading
|
||||
from datetime import datetime
|
||||
|
||||
from flask import current_app, jsonify, request, send_from_directory
|
||||
from flask_jwt_extended import jwt_required
|
||||
|
||||
from .. import db
|
||||
from ..inference_engine import run_inference_on_folder
|
||||
from ..models import InferenceResult, RawDataFolder
|
||||
from . import api
|
||||
from .security import admin_required_jwt, get_current_user, get_pagination_args, permission_required_jwt
|
||||
|
||||
|
||||
def run_inference_in_background(app, folder_id):
|
||||
with app.app_context():
|
||||
folder = RawDataFolder.query.get(folder_id)
|
||||
if not folder:
|
||||
return
|
||||
|
||||
try:
|
||||
input_path = os.path.join(app.config["PROCESSED_DATA_OUTPUT_FOLDER"], folder.folder_name)
|
||||
results_dir = os.path.join(app.config["PROCESSED_DATA_OUTPUT_FOLDER"], "_inference_results")
|
||||
os.makedirs(results_dir, exist_ok=True)
|
||||
|
||||
timestamp_str = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
|
||||
output_csv_filename = f"inference_{folder.folder_name}_{timestamp_str}.csv"
|
||||
output_csv_path = os.path.join(results_dir, output_csv_filename)
|
||||
|
||||
result_dict = run_inference_on_folder(app, folder.id, output_csv_path)
|
||||
|
||||
new_result = InferenceResult(
|
||||
folder_id=folder.id,
|
||||
total_windows=result_dict["Total_Windows"][0],
|
||||
valid_windows=result_dict["Valid_Windows"][0],
|
||||
sqa_pass_rate=result_dict["SQA_Pass_Rate"][0],
|
||||
positive_count=result_dict["Positive_Count"][0],
|
||||
positive_density=result_dict["Positive_Density"][0],
|
||||
diagnosis=result_dict["Diagnosis"][0],
|
||||
result_csv_filename=output_csv_filename,
|
||||
)
|
||||
db.session.add(new_result)
|
||||
|
||||
folder.inference_status = "inferred"
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
folder.inference_status = "none"
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@api.route("/admin/inference/folders", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("run_inference")
|
||||
def list_inference_folders():
|
||||
folders = RawDataFolder.query.filter(RawDataFolder.status == "completed").order_by(RawDataFolder.folder_name).all()
|
||||
return (
|
||||
jsonify(
|
||||
[
|
||||
{
|
||||
"id": f.id,
|
||||
"folder_name": f.folder_name,
|
||||
"status": f.status,
|
||||
"inference_status": f.inference_status,
|
||||
"researcher_id": f.researcher_id,
|
||||
}
|
||||
for f in folders
|
||||
]
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/admin/inference/jobs", methods=["POST"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("run_inference")
|
||||
def create_inference_job():
|
||||
data = request.get_json() or {}
|
||||
folder_id = data.get("folder_id")
|
||||
if not folder_id:
|
||||
return jsonify({"msg": "Missing folder_id"}), 400
|
||||
|
||||
folder = RawDataFolder.query.get(int(folder_id))
|
||||
if not folder:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
if folder.inference_status == "inferencing":
|
||||
return jsonify({"msg": "Folder is inferencing"}), 400
|
||||
|
||||
folder.inference_status = "inferencing"
|
||||
db.session.commit()
|
||||
|
||||
app_instance = current_app._get_current_object()
|
||||
thread = threading.Thread(target=run_inference_in_background, args=(app_instance, folder.id))
|
||||
thread.start()
|
||||
|
||||
return jsonify({"msg": "started", "folder_id": folder.id}), 201
|
||||
|
||||
|
||||
@api.route("/admin/inference/results", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("run_inference")
|
||||
def list_inference_results():
|
||||
page, per_page = get_pagination_args(default_per_page=20)
|
||||
query = InferenceResult.query.order_by(InferenceResult.timestamp.desc())
|
||||
pagination = query.paginate(page=page, per_page=per_page, error_out=False)
|
||||
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": r.id,
|
||||
"folder_id": r.folder_id,
|
||||
"folder_name": r.folder.folder_name if r.folder else None,
|
||||
"timestamp": r.timestamp.isoformat(),
|
||||
"total_windows": r.total_windows,
|
||||
"valid_windows": r.valid_windows,
|
||||
"sqa_pass_rate": r.sqa_pass_rate,
|
||||
"positive_count": r.positive_count,
|
||||
"positive_density": r.positive_density,
|
||||
"diagnosis": r.diagnosis,
|
||||
"result_csv_filename": r.result_csv_filename,
|
||||
}
|
||||
for r in pagination.items
|
||||
],
|
||||
"page": pagination.page,
|
||||
"per_page": pagination.per_page,
|
||||
"total": pagination.total,
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/admin/inference/results/<int:result_id>/download", methods=["GET"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
@permission_required_jwt("run_inference")
|
||||
def download_inference_result(result_id):
|
||||
result = InferenceResult.query.get(result_id)
|
||||
if not result:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
if not result.result_csv_filename:
|
||||
return jsonify({"msg": "No result file"}), 404
|
||||
|
||||
results_dir = os.path.join(current_app.config["PROCESSED_DATA_OUTPUT_FOLDER"], "_inference_results")
|
||||
return send_from_directory(results_dir, result.result_csv_filename, as_attachment=True, download_name=result.result_csv_filename)
|
||||
@@ -0,0 +1,308 @@
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
from datetime import datetime
|
||||
|
||||
from flask import after_this_request, current_app, jsonify, request, send_from_directory
|
||||
from flask_jwt_extended import jwt_required
|
||||
from sqlalchemy import or_
|
||||
|
||||
from .. import db
|
||||
from ..integrator_pipeline import run_integration_pipeline
|
||||
from ..models import ProcessingJob, ProcessedSegment, RawDataFolder, UploadLog, User
|
||||
from . import api
|
||||
from .security import admin_required_jwt, data_access_required_jwt, get_current_user, get_pagination_args
|
||||
|
||||
|
||||
def run_integration_in_background(app, job_id):
|
||||
with app.app_context():
|
||||
run_integration_pipeline(app, job_id)
|
||||
|
||||
|
||||
@api.route("/admin/integration/sync", methods=["POST"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
def sync_integration_folders():
|
||||
storage_root = current_app.config["RAW_DATA_STORAGE_FOLDER"]
|
||||
|
||||
db_folders = RawDataFolder.query.all()
|
||||
db_folder_map = {f.folder_name: f for f in db_folders}
|
||||
db_set = set(db_folder_map.keys())
|
||||
|
||||
try:
|
||||
disk_set = {d for d in os.listdir(storage_root) if os.path.isdir(os.path.join(storage_root, d))}
|
||||
except FileNotFoundError:
|
||||
disk_set = set()
|
||||
|
||||
folders_to_add = disk_set - db_set
|
||||
folders_to_delete = db_set - disk_set
|
||||
|
||||
changed = 0
|
||||
if folders_to_add:
|
||||
for folder_name in folders_to_add:
|
||||
uploader_log = (
|
||||
UploadLog.query.filter(
|
||||
or_(
|
||||
UploadLog.filename == f"{folder_name}.zip",
|
||||
UploadLog.filename == f"{folder_name}.rar",
|
||||
UploadLog.filename == f"{folder_name}.7z",
|
||||
)
|
||||
)
|
||||
.order_by(UploadLog.upload_time.desc())
|
||||
.first()
|
||||
)
|
||||
researcher_id = uploader_log.researcher_id if uploader_log else None
|
||||
db.session.add(RawDataFolder(folder_name=folder_name, researcher_id=researcher_id))
|
||||
changed += 1
|
||||
|
||||
if folders_to_delete:
|
||||
for folder_name in folders_to_delete:
|
||||
db.session.delete(db_folder_map[folder_name])
|
||||
changed += 1
|
||||
|
||||
if changed:
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({"changed": changed}), 200
|
||||
|
||||
|
||||
@api.route("/admin/integration/folders", methods=["GET"])
|
||||
@jwt_required()
|
||||
def list_integration_folders():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"msg": "Unauthorized"}), 401
|
||||
|
||||
page, per_page = get_pagination_args(default_per_page=20)
|
||||
status = request.args.get("status")
|
||||
researcher_id = request.args.get("researcher_id", type=int)
|
||||
|
||||
query = RawDataFolder.query
|
||||
if user.is_admin():
|
||||
if researcher_id:
|
||||
query = query.filter(RawDataFolder.researcher_id == researcher_id)
|
||||
elif user.is_researcher():
|
||||
query = query.filter(RawDataFolder.researcher_id == user.id)
|
||||
else:
|
||||
return jsonify({"msg": "Forbidden"}), 403
|
||||
|
||||
if status:
|
||||
query = query.filter(RawDataFolder.status == status)
|
||||
|
||||
query = query.order_by(RawDataFolder.folder_name)
|
||||
pagination = query.paginate(page=page, per_page=per_page, error_out=False)
|
||||
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": f.id,
|
||||
"folder_name": f.folder_name,
|
||||
"status": f.status,
|
||||
"last_processed": f.last_processed.isoformat() if f.last_processed else None,
|
||||
"researcher_id": f.researcher_id,
|
||||
"inference_status": f.inference_status,
|
||||
}
|
||||
for f in pagination.items
|
||||
],
|
||||
"page": pagination.page,
|
||||
"per_page": pagination.per_page,
|
||||
"total": pagination.total,
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/admin/integration/folders/<int:folder_id>", methods=["PATCH"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
def assign_folder_researcher(folder_id):
|
||||
folder = RawDataFolder.query.get(folder_id)
|
||||
if not folder:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
data = request.get_json() or {}
|
||||
researcher_id = data.get("researcher_id")
|
||||
if researcher_id in (0, "0", None, ""):
|
||||
folder.researcher_id = None
|
||||
else:
|
||||
researcher_id = int(researcher_id)
|
||||
user = User.query.get(researcher_id)
|
||||
if not user or not (user.is_researcher() or user.is_admin()):
|
||||
return jsonify({"msg": "Invalid researcher_id"}), 400
|
||||
folder.researcher_id = researcher_id
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({"id": folder.id, "researcher_id": folder.researcher_id}), 200
|
||||
|
||||
|
||||
@api.route("/admin/integration/folders/batch-assign-researcher", methods=["POST"])
|
||||
@jwt_required()
|
||||
@admin_required_jwt
|
||||
def batch_assign_folder_researcher():
|
||||
data = request.get_json() or {}
|
||||
folder_ids = data.get("folder_ids") or []
|
||||
researcher_id = data.get("researcher_id")
|
||||
|
||||
if not folder_ids:
|
||||
return jsonify({"msg": "No folder_ids"}), 400
|
||||
|
||||
if researcher_id in (0, "0", None, ""):
|
||||
researcher_id = None
|
||||
else:
|
||||
researcher_id = int(researcher_id)
|
||||
researcher = User.query.get(researcher_id)
|
||||
if not researcher or not (researcher.is_researcher() or researcher.is_admin()):
|
||||
return jsonify({"msg": "Invalid researcher_id"}), 400
|
||||
|
||||
updated = 0
|
||||
for folder_id in folder_ids:
|
||||
folder = RawDataFolder.query.get(folder_id)
|
||||
if folder:
|
||||
folder.researcher_id = researcher_id
|
||||
updated += 1
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({"updated": updated}), 200
|
||||
|
||||
|
||||
@api.route("/admin/integration/jobs", methods=["POST"])
|
||||
@jwt_required()
|
||||
def create_integration_job():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"msg": "Unauthorized"}), 401
|
||||
|
||||
data = request.get_json() or {}
|
||||
folder_id = data.get("folder_id")
|
||||
if not folder_id:
|
||||
return jsonify({"msg": "Missing folder_id"}), 400
|
||||
|
||||
folder = RawDataFolder.query.get(int(folder_id))
|
||||
if not folder:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
if not user.is_admin():
|
||||
if not user.is_researcher() or folder.researcher_id != user.id:
|
||||
return jsonify({"msg": "Forbidden"}), 403
|
||||
|
||||
if folder.status == "processing":
|
||||
return jsonify({"msg": "Folder is processing"}), 400
|
||||
|
||||
job = ProcessingJob(folder_id=folder.id, status="queued")
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
app_instance = current_app._get_current_object()
|
||||
thread = threading.Thread(target=run_integration_in_background, args=(app_instance, job.id))
|
||||
thread.start()
|
||||
|
||||
return jsonify({"id": job.id, "status": job.status}), 201
|
||||
|
||||
|
||||
@api.route("/admin/integration/jobs", methods=["GET"])
|
||||
@jwt_required()
|
||||
def list_integration_jobs():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"msg": "Unauthorized"}), 401
|
||||
|
||||
page, per_page = get_pagination_args(default_per_page=20)
|
||||
|
||||
query = ProcessingJob.query.join(RawDataFolder)
|
||||
if user.is_admin():
|
||||
pass
|
||||
elif user.is_researcher():
|
||||
query = query.filter(RawDataFolder.researcher_id == user.id)
|
||||
else:
|
||||
return jsonify({"msg": "Forbidden"}), 403
|
||||
|
||||
query = query.order_by(ProcessingJob.start_time.desc())
|
||||
pagination = query.paginate(page=page, per_page=per_page, error_out=False)
|
||||
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": j.id,
|
||||
"folder_id": j.folder_id,
|
||||
"folder_name": j.folder.folder_name if j.folder else None,
|
||||
"start_time": j.start_time.isoformat() if j.start_time else None,
|
||||
"end_time": j.end_time.isoformat() if j.end_time else None,
|
||||
"status": j.status,
|
||||
"log": j.log,
|
||||
}
|
||||
for j in pagination.items
|
||||
],
|
||||
"page": pagination.page,
|
||||
"per_page": pagination.per_page,
|
||||
"total": pagination.total,
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/admin/integration/folders/<int:folder_id>/summary", methods=["GET"])
|
||||
@jwt_required()
|
||||
@data_access_required_jwt(RawDataFolder, id_param="folder_id")
|
||||
def folder_summary(folder_id):
|
||||
folder = RawDataFolder.query.get(folder_id)
|
||||
if not folder:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
segments = folder.processed_segments.order_by(ProcessedSegment.start_time).all()
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"folder_id": folder.id,
|
||||
"folder_name": folder.folder_name,
|
||||
"segments": [
|
||||
{
|
||||
"id": s.id,
|
||||
"uid": s.uid,
|
||||
"light_type": s.light_type,
|
||||
"start_time": s.start_time.isoformat() if s.start_time else None,
|
||||
"end_time": s.end_time.isoformat() if s.end_time else None,
|
||||
"filename": s.filename,
|
||||
"fs": s.fs,
|
||||
"inverted": s.inverted,
|
||||
"timestamp": s.timestamp.isoformat() if s.timestamp else None,
|
||||
}
|
||||
for s in segments
|
||||
],
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/admin/integration/folders/<int:folder_id>/download-processed", methods=["GET"])
|
||||
@jwt_required()
|
||||
@data_access_required_jwt(RawDataFolder, id_param="folder_id")
|
||||
def download_processed_folder(folder_id):
|
||||
folder = RawDataFolder.query.get(folder_id)
|
||||
if not folder:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
output_folder_path = os.path.join(current_app.config["PROCESSED_DATA_OUTPUT_FOLDER"], folder.folder_name)
|
||||
if not os.path.isdir(output_folder_path):
|
||||
return jsonify({"msg": "Processed folder not found"}), 404
|
||||
|
||||
temp_dir = os.path.join(current_app.config["PROCESSED_DATA_OUTPUT_FOLDER"], "temp_zips")
|
||||
os.makedirs(temp_dir, exist_ok=True)
|
||||
archive_path_base = os.path.join(temp_dir, f"processed_{folder.folder_name}")
|
||||
archive_path_full = shutil.make_archive(archive_path_base, "zip", output_folder_path)
|
||||
|
||||
@after_this_request
|
||||
def cleanup(response):
|
||||
try:
|
||||
os.remove(archive_path_full)
|
||||
except OSError:
|
||||
pass
|
||||
return response
|
||||
|
||||
return send_from_directory(temp_dir, os.path.basename(archive_path_full), as_attachment=True)
|
||||
@@ -0,0 +1,81 @@
|
||||
from flask import jsonify
|
||||
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||
from datetime import datetime
|
||||
from sqlalchemy import or_, and_
|
||||
from ..models import User, DataEntry, Notification
|
||||
from . import api
|
||||
|
||||
@api.route('/dashboard', methods=['GET'])
|
||||
@jwt_required()
|
||||
def dashboard():
|
||||
current_user_id = get_jwt_identity()
|
||||
current_user = User.query.get(int(current_user_id))
|
||||
|
||||
if not current_user:
|
||||
return jsonify({"msg": "User not found"}), 404
|
||||
|
||||
visible_data = []
|
||||
|
||||
if current_user.is_admin():
|
||||
visible_data = DataEntry.query.order_by(DataEntry.timestamp.desc()).all()
|
||||
else:
|
||||
now = datetime.utcnow()
|
||||
# 构建基础查询
|
||||
query = DataEntry.query.filter(
|
||||
or_(
|
||||
DataEntry.researcher_id == current_user.id,
|
||||
DataEntry.visible_to_users.any(id=current_user.id)
|
||||
)
|
||||
)
|
||||
|
||||
# 应用时间过滤
|
||||
query = query.filter(
|
||||
or_(
|
||||
DataEntry.is_permanent == True,
|
||||
and_(
|
||||
or_(DataEntry.start_date == None, DataEntry.start_date <= now),
|
||||
or_(DataEntry.expiration_date == None, DataEntry.expiration_date >= now)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
visible_data = query.order_by(DataEntry.timestamp.desc()).all()
|
||||
|
||||
data_list = [{
|
||||
"id": d.id,
|
||||
"title": d.title,
|
||||
"content": d.content,
|
||||
"timestamp": d.timestamp.isoformat(),
|
||||
"is_permanent": d.is_permanent,
|
||||
"start_date": d.start_date.isoformat() if d.start_date else None,
|
||||
"expiration_date": d.expiration_date.isoformat() if d.expiration_date else None,
|
||||
"researcher": d.researcher.username if d.researcher else None,
|
||||
"associated_filename": d.associated_filename
|
||||
} for d in visible_data]
|
||||
|
||||
return jsonify({"data_entries": data_list}), 200
|
||||
|
||||
@api.route('/notifications', methods=['GET'])
|
||||
def notifications():
|
||||
# Public notifications, maybe no auth required? Or minimal auth.
|
||||
# For now let's make it public or consistent with dashboard.
|
||||
# The original app allowed public index to see notifications.
|
||||
from flask import request
|
||||
limit = request.args.get('limit', type=int)
|
||||
|
||||
query = Notification.query.filter_by(is_published=True).order_by(Notification.timestamp.desc())
|
||||
|
||||
if limit:
|
||||
published_notifications = query.limit(limit).all()
|
||||
else:
|
||||
published_notifications = query.all()
|
||||
|
||||
notif_list = [{
|
||||
"id": n.id,
|
||||
"title": n.title,
|
||||
"content": n.content,
|
||||
"timestamp": n.timestamp.isoformat(),
|
||||
"author": n.author.username if n.author else None
|
||||
} for n in published_notifications]
|
||||
|
||||
return jsonify({"notifications": notif_list}), 200
|
||||
@@ -0,0 +1,212 @@
|
||||
from datetime import datetime
|
||||
|
||||
from flask import jsonify, request
|
||||
from sqlalchemy import and_, or_
|
||||
from flask_jwt_extended import jwt_required
|
||||
|
||||
from ..models import DataEntry, Notification, RawDataFolder
|
||||
from . import api
|
||||
from .security import get_current_user
|
||||
|
||||
|
||||
@api.route("/search", methods=["GET"])
|
||||
@jwt_required()
|
||||
def search():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"msg": "Unauthorized"}), 401
|
||||
|
||||
query = request.args.get("q", "").strip()
|
||||
scope = request.args.get("scope")
|
||||
|
||||
if not query:
|
||||
return jsonify({"data_entries": [], "notifications": [], "raw_folders": []}), 200
|
||||
|
||||
search_term = f"%{query}%"
|
||||
now = datetime.utcnow()
|
||||
|
||||
data_entry_results = []
|
||||
notification_results = []
|
||||
raw_folder_results = []
|
||||
|
||||
if user.is_admin():
|
||||
if scope in (None, "", "data"):
|
||||
data_entry_results = (
|
||||
DataEntry.query.filter(
|
||||
or_(DataEntry.title.ilike(search_term), DataEntry.content.ilike(search_term))
|
||||
)
|
||||
.order_by(DataEntry.timestamp.desc())
|
||||
.all()
|
||||
)
|
||||
if scope in (None, "", "notification"):
|
||||
notification_results = (
|
||||
Notification.query.filter(
|
||||
or_(Notification.title.ilike(search_term), Notification.content.ilike(search_term))
|
||||
)
|
||||
.order_by(Notification.timestamp.desc())
|
||||
.all()
|
||||
)
|
||||
if scope in (None, "", "folder"):
|
||||
raw_folder_results = (
|
||||
RawDataFolder.query.filter(RawDataFolder.folder_name.ilike(search_term))
|
||||
.order_by(RawDataFolder.folder_name)
|
||||
.all()
|
||||
)
|
||||
else:
|
||||
if scope in (None, "", "data"):
|
||||
data_query = (
|
||||
DataEntry.query.filter(
|
||||
or_(
|
||||
DataEntry.researcher_id == user.id,
|
||||
DataEntry.visible_to_users.any(id=user.id),
|
||||
)
|
||||
)
|
||||
.filter(
|
||||
and_(
|
||||
or_(
|
||||
DataEntry.is_permanent == True,
|
||||
and_(
|
||||
or_(DataEntry.start_date == None, DataEntry.start_date <= now),
|
||||
or_(DataEntry.expiration_date == None, DataEntry.expiration_date >= now),
|
||||
),
|
||||
),
|
||||
or_(DataEntry.title.ilike(search_term), DataEntry.content.ilike(search_term)),
|
||||
)
|
||||
)
|
||||
)
|
||||
data_entry_results = data_query.order_by(DataEntry.timestamp.desc()).all()
|
||||
|
||||
if scope in (None, "", "notification"):
|
||||
notification_results = (
|
||||
Notification.query.filter(
|
||||
and_(
|
||||
Notification.is_published == True,
|
||||
or_(Notification.title.ilike(search_term), Notification.content.ilike(search_term)),
|
||||
)
|
||||
)
|
||||
.order_by(Notification.timestamp.desc())
|
||||
.all()
|
||||
)
|
||||
|
||||
if scope in (None, "", "folder") and user.is_researcher():
|
||||
raw_folder_results = (
|
||||
RawDataFolder.query.filter(
|
||||
and_(RawDataFolder.researcher_id == user.id, RawDataFolder.folder_name.ilike(search_term))
|
||||
)
|
||||
.order_by(RawDataFolder.folder_name)
|
||||
.all()
|
||||
)
|
||||
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"query": query,
|
||||
"data_entries": [
|
||||
{
|
||||
"id": e.id,
|
||||
"title": e.title,
|
||||
"timestamp": e.timestamp.isoformat(),
|
||||
}
|
||||
for e in data_entry_results
|
||||
],
|
||||
"notifications": [
|
||||
{
|
||||
"id": n.id,
|
||||
"title": n.title,
|
||||
"timestamp": n.timestamp.isoformat(),
|
||||
"is_published": n.is_published,
|
||||
}
|
||||
for n in notification_results
|
||||
],
|
||||
"raw_folders": [
|
||||
{
|
||||
"id": f.id,
|
||||
"folder_name": f.folder_name,
|
||||
"status": f.status,
|
||||
"researcher_id": f.researcher_id,
|
||||
}
|
||||
for f in raw_folder_results
|
||||
],
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
|
||||
@api.route("/search/suggestions", methods=["GET"])
|
||||
@jwt_required()
|
||||
def search_suggestions():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify([]), 200
|
||||
|
||||
query = request.args.get("q", "").strip().lower()
|
||||
if len(query) < 1:
|
||||
return jsonify([]), 200
|
||||
|
||||
suggestions = []
|
||||
|
||||
features = [
|
||||
{"name": "仪表盘", "url": "/dashboard", "keywords": ["dashboard", "home", "主页", "仪表盘"]},
|
||||
{"name": "系统通知", "url": "/notifications", "keywords": ["notification", "notice", "通知", "公告"]},
|
||||
{"name": "搜索", "url": "/search", "keywords": ["search", "find", "检索", "搜索"]},
|
||||
{"name": "我的资料", "url": "/profile", "keywords": ["profile", "me", "我的", "资料", "权限"]},
|
||||
]
|
||||
if user.is_admin():
|
||||
features.extend(
|
||||
[
|
||||
{"name": "用户管理", "url": "/admin/users", "keywords": ["user", "account", "用户", "账号"]},
|
||||
{"name": "数据管理", "url": "/admin/data-entries", "keywords": ["data", "entry", "数据"]},
|
||||
{"name": "通知管理", "url": "/admin/notifications", "keywords": ["notice", "通知", "公告"]},
|
||||
{"name": "上传与历史", "url": "/admin/uploads", "keywords": ["upload", "上传", "history", "历史"]},
|
||||
{"name": "数据整合", "url": "/admin/integration", "keywords": ["integration", "整合", "处理"]},
|
||||
{"name": "AI推理", "url": "/admin/inference", "keywords": ["ai", "inference", "推理", "诊断"]},
|
||||
{"name": "角色管理", "url": "/admin/roles", "keywords": ["role", "角色", "rbac"]},
|
||||
{"name": "权限管理", "url": "/admin/permissions", "keywords": ["permission", "权限"]},
|
||||
{"name": "权限日志", "url": "/admin/permission-logs", "keywords": ["audit", "log", "日志", "审计"]},
|
||||
]
|
||||
)
|
||||
|
||||
for feature in features:
|
||||
for kw in feature["keywords"]:
|
||||
if kw in query or query in kw.lower():
|
||||
suggestions.append(
|
||||
{"type": "功能", "title": feature["name"], "url": feature["url"], "icon": "compass"}
|
||||
)
|
||||
break
|
||||
|
||||
search_term = f"%{query}%"
|
||||
|
||||
if user.is_admin():
|
||||
entries = DataEntry.query.filter(DataEntry.title.ilike(search_term)).limit(5).all()
|
||||
for e in entries:
|
||||
suggestions.append({"type": "数据", "title": e.title, "url": f"/data/{e.id}", "icon": "database"})
|
||||
|
||||
notifs = Notification.query.filter(Notification.title.ilike(search_term)).limit(3).all()
|
||||
for n in notifs:
|
||||
suggestions.append({"type": "通知", "title": n.title, "url": "/notifications", "icon": "bullhorn"})
|
||||
|
||||
folders = RawDataFolder.query.filter(RawDataFolder.folder_name.ilike(search_term)).limit(3).all()
|
||||
for f in folders:
|
||||
suggestions.append({"type": "原始文件", "title": f.folder_name, "url": "/admin/integration", "icon": "folder"})
|
||||
else:
|
||||
entries = (
|
||||
DataEntry.query.filter(DataEntry.visible_to_users.any(id=user.id))
|
||||
.filter(DataEntry.title.ilike(search_term))
|
||||
.limit(5)
|
||||
.all()
|
||||
)
|
||||
for e in entries:
|
||||
suggestions.append({"type": "数据", "title": e.title, "url": f"/data/{e.id}", "icon": "database"})
|
||||
|
||||
notifs = (
|
||||
Notification.query.filter(Notification.is_published == True)
|
||||
.filter(Notification.title.ilike(search_term))
|
||||
.limit(3)
|
||||
.all()
|
||||
)
|
||||
for n in notifs:
|
||||
suggestions.append({"type": "通知", "title": n.title, "url": "/notifications", "icon": "bullhorn"})
|
||||
|
||||
return jsonify(suggestions[:10]), 200
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
from functools import wraps
|
||||
|
||||
from flask import jsonify, request
|
||||
from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request
|
||||
|
||||
from ..models import User
|
||||
|
||||
|
||||
def get_current_user():
|
||||
verify_jwt_in_request()
|
||||
user_id = get_jwt_identity()
|
||||
if user_id is None:
|
||||
return None
|
||||
try:
|
||||
user_id_int = int(user_id)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return User.query.get(user_id_int)
|
||||
|
||||
|
||||
def admin_required_jwt(fn):
|
||||
@wraps(fn)
|
||||
def wrapper(*args, **kwargs):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin():
|
||||
return jsonify({"msg": "Admins only"}), 403
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def permission_required_jwt(permission_name):
|
||||
def decorator(fn):
|
||||
@wraps(fn)
|
||||
def wrapper(*args, **kwargs):
|
||||
user = get_current_user()
|
||||
if not user or not user.has_permission(permission_name):
|
||||
return jsonify({"msg": "Permission denied", "permission": permission_name}), 403
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def data_access_required_jwt(model_class, id_param="id"):
|
||||
def decorator(fn):
|
||||
@wraps(fn)
|
||||
def wrapper(*args, **kwargs):
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"msg": "Unauthorized"}), 401
|
||||
|
||||
resource_id = kwargs.get(id_param)
|
||||
if not resource_id:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
resource = model_class.query.get(resource_id)
|
||||
if not resource:
|
||||
return jsonify({"msg": "Not found"}), 404
|
||||
|
||||
if user.is_admin():
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
is_authorized = False
|
||||
|
||||
if hasattr(resource, "researcher_id") and resource.researcher_id == user.id:
|
||||
is_authorized = True
|
||||
|
||||
if not is_authorized and hasattr(resource, "visible_to_users"):
|
||||
try:
|
||||
if resource.visible_to_users.filter_by(id=user.id).first() is not None:
|
||||
is_authorized = True
|
||||
except Exception:
|
||||
if user in resource.visible_to_users:
|
||||
is_authorized = True
|
||||
|
||||
if not is_authorized and model_class.__name__ == "Attachment":
|
||||
if resource.data_entry.researcher_id == user.id:
|
||||
is_authorized = True
|
||||
else:
|
||||
try:
|
||||
if resource.data_entry.visible_to_users.filter_by(id=user.id).first() is not None:
|
||||
is_authorized = True
|
||||
except Exception:
|
||||
if user in resource.data_entry.visible_to_users:
|
||||
is_authorized = True
|
||||
|
||||
if not is_authorized:
|
||||
return jsonify({"msg": "Forbidden"}), 403
|
||||
|
||||
check_resource = resource
|
||||
if model_class.__name__ == "Attachment":
|
||||
check_resource = resource.data_entry
|
||||
|
||||
if hasattr(check_resource, "is_visible_now") and not check_resource.is_visible_now():
|
||||
return jsonify({"msg": "Forbidden"}), 403
|
||||
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def get_pagination_args(default_per_page=20, max_per_page=100):
|
||||
try:
|
||||
page = int(request.args.get("page", 1))
|
||||
except ValueError:
|
||||
page = 1
|
||||
try:
|
||||
per_page = int(request.args.get("per_page", default_per_page))
|
||||
except ValueError:
|
||||
per_page = default_per_page
|
||||
page = max(page, 1)
|
||||
per_page = min(max(per_page, 1), max_per_page)
|
||||
return page, per_page
|
||||
|
||||
|
||||
def paginate_query(query, page, per_page):
|
||||
pagination = query.paginate(page=page, per_page=per_page, error_out=False)
|
||||
return {
|
||||
"items": pagination.items,
|
||||
"page": pagination.page,
|
||||
"per_page": pagination.per_page,
|
||||
"total": pagination.total,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import os
|
||||
import zipfile
|
||||
|
||||
from flask import current_app, jsonify, request
|
||||
from flask_jwt_extended import jwt_required
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
from .. import db
|
||||
from ..models import UploadLog, User
|
||||
from . import api
|
||||
from .security import admin_required_jwt, get_current_user, get_pagination_args
|
||||
|
||||
|
||||
@api.route("/admin/uploads/archives", methods=["POST"])
|
||||
@jwt_required()
|
||||
def upload_archives():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"msg": "Unauthorized"}), 401
|
||||
|
||||
if not (user.is_admin() or user.is_researcher()):
|
||||
return jsonify({"msg": "Forbidden"}), 403
|
||||
|
||||
files = request.files.getlist("raw_files") or request.files.getlist("files")
|
||||
if not files:
|
||||
return jsonify({"msg": "No files"}), 400
|
||||
|
||||
if user.is_admin():
|
||||
researcher_id = request.form.get("researcher_id", type=int) or user.id
|
||||
else:
|
||||
researcher_id = user.id
|
||||
|
||||
results = []
|
||||
storage_root = current_app.config["RAW_DATA_STORAGE_FOLDER"]
|
||||
|
||||
for f in files:
|
||||
if not f or not f.filename:
|
||||
continue
|
||||
|
||||
original_filename = secure_filename(f.filename)
|
||||
ext = os.path.splitext(original_filename)[1].lower()
|
||||
if ext not in [".zip", ".rar", ".7z"]:
|
||||
results.append({"filename": original_filename, "status": "failed", "error": "不支持的格式"})
|
||||
continue
|
||||
|
||||
try:
|
||||
storage_path = os.path.join(storage_root, original_filename)
|
||||
f.save(storage_path)
|
||||
file_size = os.path.getsize(storage_path)
|
||||
|
||||
log = UploadLog(
|
||||
filename=original_filename,
|
||||
file_size=file_size,
|
||||
researcher_id=researcher_id,
|
||||
uploader_id=user.id,
|
||||
status="success",
|
||||
)
|
||||
db.session.add(log)
|
||||
results.append({"filename": original_filename, "status": "success", "size": file_size})
|
||||
except Exception as e:
|
||||
log = UploadLog(
|
||||
filename=original_filename,
|
||||
file_size=0,
|
||||
researcher_id=researcher_id,
|
||||
uploader_id=user.id,
|
||||
status="failed",
|
||||
error_msg=str(e),
|
||||
)
|
||||
db.session.add(log)
|
||||
results.append({"filename": original_filename, "status": "failed", "error": str(e)})
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({"researcher_id": researcher_id, "results": results}), 200
|
||||
|
||||
|
||||
@api.route("/admin/uploads/preview-archive", methods=["POST"])
|
||||
@jwt_required()
|
||||
def preview_archive():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"msg": "Unauthorized"}), 401
|
||||
if not user.is_admin():
|
||||
return jsonify({"msg": "Forbidden"}), 403
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"msg": "未选择文件"}), 400
|
||||
|
||||
f = request.files["file"]
|
||||
if not f or not f.filename:
|
||||
return jsonify({"msg": "未选择文件"}), 400
|
||||
if not f.filename.endswith(".zip"):
|
||||
return jsonify({"msg": "目前仅支持预览 .zip 格式"}), 400
|
||||
|
||||
try:
|
||||
with zipfile.ZipFile(f) as z:
|
||||
file_list = [info.filename for info in z.infolist()]
|
||||
return jsonify({"files": file_list}), 200
|
||||
except Exception as e:
|
||||
return jsonify({"msg": f"无法读取压缩包: {str(e)}"}), 500
|
||||
|
||||
|
||||
@api.route("/admin/uploads/history", methods=["GET"])
|
||||
@jwt_required()
|
||||
def upload_history():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({"msg": "Unauthorized"}), 401
|
||||
|
||||
page, per_page = get_pagination_args(default_per_page=20)
|
||||
|
||||
if user.is_admin():
|
||||
query = UploadLog.query
|
||||
elif user.is_researcher():
|
||||
query = UploadLog.query.filter_by(researcher_id=user.id)
|
||||
else:
|
||||
return jsonify({"msg": "Forbidden"}), 403
|
||||
|
||||
pagination = query.order_by(UploadLog.upload_time.desc()).paginate(page=page, per_page=per_page, error_out=False)
|
||||
logs = pagination.items
|
||||
|
||||
user_map = {}
|
||||
uploader_ids = {l.uploader_id for l in logs}
|
||||
if uploader_ids:
|
||||
for u in User.query.filter(User.id.in_(list(uploader_ids))).all():
|
||||
user_map[u.id] = u.username
|
||||
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": l.id,
|
||||
"filename": l.filename,
|
||||
"file_size": l.file_size,
|
||||
"upload_time": l.upload_time.isoformat(),
|
||||
"status": l.status,
|
||||
"error_msg": l.error_msg,
|
||||
"researcher_id": l.researcher_id,
|
||||
"uploader_id": l.uploader_id,
|
||||
"uploader": user_map.get(l.uploader_id),
|
||||
}
|
||||
for l in logs
|
||||
],
|
||||
"page": pagination.page,
|
||||
"per_page": pagination.per_page,
|
||||
"total": pagination.total,
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -7,9 +7,7 @@ load_dotenv(os.path.join(basedir, '.env'))
|
||||
|
||||
class Config:
|
||||
SECRET_KEY = os.environ.get('SECRET_KEY') or 'a-very-secret-key'
|
||||
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
|
||||
if not SQLALCHEMY_DATABASE_URI:
|
||||
raise ValueError("DATABASE_URL 环境变量未设置")
|
||||
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or f"sqlite:///{os.path.join(basedir, 'app.db')}"
|
||||
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
UPLOAD_FOLDER = os.path.join(basedir, 'uploads')
|
||||
@@ -56,4 +54,4 @@ config = {
|
||||
'testing': TestingConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -173,3 +173,6 @@ win32-setctime==1.1.0
|
||||
WTForms==3.2.1
|
||||
xxhash==3.4.1
|
||||
zstandard==0.23.0
|
||||
|
||||
Flask-JWT-Extended
|
||||
Flask-Cors
|
||||
File renamed without changes.
File renamed without changes.
Whitespace-only changes.
@@ -1,7 +1,7 @@
|
||||
import unittest
|
||||
from datetime import datetime, timedelta
|
||||
from app import create_app, db
|
||||
from app.models import User, DataEntry, Role
|
||||
from backend.app import create_app, db
|
||||
from backend.app.models import User, DataEntry, Role
|
||||
|
||||
class DataIsolationTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
@@ -1,7 +1,7 @@
|
||||
import unittest
|
||||
from app import create_app, db
|
||||
from app.models import User, Role, Permission
|
||||
from app.rbac_utils import check_circular_inheritance
|
||||
from backend.app import create_app, db
|
||||
from backend.app.models import User, Role, Permission
|
||||
from backend.app.rbac_utils import check_circular_inheritance
|
||||
|
||||
class RBACModelTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
File renamed without changes.
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["Vue.volar"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Vue 3 + Vite
|
||||
|
||||
This template should help get you started developing with Vue 3 in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
|
||||
|
||||
Learn more about IDE Support for Vue in the [Vue Docs Scaling up Guide](https://vuejs.org/guide/scaling-up/tooling.html#ide-support).
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>frontend</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2917
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"axios": "^1.13.5",
|
||||
"echarts": "^6.0.0",
|
||||
"element-plus": "^2.13.2",
|
||||
"pinia": "^3.0.4",
|
||||
"sass": "^1.97.3",
|
||||
"vue": "^3.5.25",
|
||||
"vue-i18n": "^11.2.8",
|
||||
"vue-router": "^5.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^6.0.2",
|
||||
"vite": "^7.3.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,18 @@
|
||||
<template>
|
||||
<el-config-provider :locale="locale">
|
||||
<router-view />
|
||||
</el-config-provider>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import en from 'element-plus/es/locale/lang/en'
|
||||
|
||||
const { locale: currentLocale } = useI18n()
|
||||
|
||||
const locale = computed(() => {
|
||||
return currentLocale.value === 'zh' ? zhCn : en
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,31 @@
|
||||
import axios from 'axios'
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api',
|
||||
timeout: 10000
|
||||
})
|
||||
|
||||
api.interceptors.request.use(config => {
|
||||
const token = localStorage.getItem('token')
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
}, error => {
|
||||
return Promise.reject(error)
|
||||
})
|
||||
|
||||
api.interceptors.response.use(
|
||||
response => response,
|
||||
error => {
|
||||
if (error.response && error.response.status === 401) {
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('user')
|
||||
localStorage.removeItem('permissions')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export default api
|
||||
@@ -0,0 +1,15 @@
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import en from './locales/en'
|
||||
import zh from './locales/zh'
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false, // usage with Composition API
|
||||
locale: localStorage.getItem('lang') || 'en', // set locale
|
||||
fallbackLocale: 'en', // set fallback locale
|
||||
messages: {
|
||||
en,
|
||||
zh
|
||||
}
|
||||
})
|
||||
|
||||
export default i18n
|
||||
Loaded 100 of 188 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user