Compare commits

...
24 Commits
Author SHA1 Message Date
Wu Clan a82e9b7b9d Fix data permission condition for filter data (#650) 2025-06-01 00:51:31 +08:00
Wu Clan 7bab8cc636 Update default value for role filter scopes (#649) 2025-05-31 23:53:47 +08:00
Wu Clan 7659b63d88 Add data permission condition for filter data (#648) 2025-05-31 23:40:59 +08:00
Wu Clan 33ebc5723f Add get all data scope rules interface (#647) 2025-05-31 23:09:26 +08:00
Wu Clan 86d9efd785 Update the server startup time to string (#646) 2025-05-31 17:26:07 +08:00
Wu Clan 57ae7f03a6 Refactor routes to better align with RESTful (#645) 2025-05-31 17:01:44 +08:00
Wu Clan 6ee3983846 Fix the filter of query all menus (#642) 2025-05-30 22:48:30 +08:00
Wu Clan f05ed5cdda Fix the menu delete interface arg description (#641) 2025-05-30 18:58:33 +08:00
Wu Clan 187dfa5344 Fix the role update business variables (#640) 2025-05-30 18:56:50 +08:00
Wu Clan 918c8a9d33 Update the changelog for v1.4.2 (#639) 2025-05-29 18:12:45 +08:00
Wu Clan ccfe35ea85 Simplify the user info update business (#638) 2025-05-29 18:09:50 +08:00
yzbf 4a118c166a Fix overwriting existing init files in code generator (#637) 2025-05-28 20:17:18 +08:00
Huyuwei 5f3823cb6d Fix auto-increment id for postgres init data (#632)
* fix: Reset auto-increment values for all tables based on max id

* refactor: Remove auto-increment reset for mysql

* remove unused code
2025-05-28 13:01:44 +08:00
Wu Clan 19ef52da9b Optimize install and build of plugin zip (#636)
* Optimiz install and build of plugin zip

* fix import
2025-05-27 11:46:17 +08:00
Wu Clan 39c3339a8d Optimize role-related data processing performance (#635) 2025-05-26 20:04:13 +08:00
Wu Clan 9f52629dcb Update the captcha invalidation error class (#634) 2025-05-26 19:16:56 +08:00
Wu Clan 1cddd6e2d5 Update non-linked sidebar support (#633)
* Update non-linked sidebar support

* fix typing
2025-05-26 15:52:45 +08:00
Wu Clan ed10e6ff47 Update the changelog for v1.4.1 (#630) 2025-05-25 14:19:41 +08:00
Wu Clan 48574fb50a Update the token decode for logout interface (#629) 2025-05-25 14:16:36 +08:00
Wu Clan ee7fe3087d Update the token check for logout interface (#625) 2025-05-23 22:05:26 +08:00
Wu Clan 270ac3d941 Refactor the system token to online users (#624) 2025-05-23 20:18:47 +08:00
Wu Clan 2f76988076 Add the deepwiki badge to README (#623) 2025-05-23 12:09:04 +08:00
Wu Clan b275481742 Update the menu path and type columns (#622)
* Update the menu path and type columns

* Update build vben5 tree

* Update data
2025-05-22 21:22:24 +08:00
Wu Clan f3f1ceb595 Update the changelog for v1.4.0 (#621) 2025-05-22 14:41:03 +08:00
42 changed files with 348 additions and 512 deletions
+62
View File
@@ -1,3 +1,62 @@
<a id="v1.4.2"></a>
# [v1.4.2](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.4.2) - 2025-05-29
## What's Changed
* Update changelog for v1.4.1 by [@wu-clan](https://github.com/wu-clan) in [#630](https://github.com/fastapi-practices/fastapi_best_architecture/pull/630)
* Update non-linked sidebar support by [@wu-clan](https://github.com/wu-clan) in [#633](https://github.com/fastapi-practices/fastapi_best_architecture/pull/633)
* Update the captcha invalidation error class by [@wu-clan](https://github.com/wu-clan) in [#634](https://github.com/fastapi-practices/fastapi_best_architecture/pull/634)
* Optimize role-related data processing performance by [@wu-clan](https://github.com/wu-clan) in [#635](https://github.com/fastapi-practices/fastapi_best_architecture/pull/635)
* Optimize install and build of plugin zip by [@wu-clan](https://github.com/wu-clan) in [#636](https://github.com/fastapi-practices/fastapi_best_architecture/pull/636)
* Fix auto-increment id for postgres init data by [@huyuwei1996](https://github.com/huyuwei1996) in [#632](https://github.com/fastapi-practices/fastapi_best_architecture/pull/632)
* Fix: prevent overwriting existing init files in code generator by [@lin-wu-1990](https://github.com/lin-wu-1990) in [#637](https://github.com/fastapi-practices/fastapi_best_architecture/pull/637)
* Simplify the user info update business by [@wu-clan](https://github.com/wu-clan) in [#638](https://github.com/fastapi-practices/fastapi_best_architecture/pull/638)
## New Contributors
* [@lin-wu-1990](https://github.com/lin-wu-1990) made their first contribution in [#637](https://github.com/fastapi-practices/fastapi_best_architecture/pull/637)
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.4.1...v1.4.2
[Changes][v1.4.2]
<a id="v1.4.1"></a>
# [v1.4.1](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.4.1) - 2025-05-25
## What's Changed
* Update changelog for v1.4.0 by [@wu-clan](https://github.com/wu-clan) in [#621](https://github.com/fastapi-practices/fastapi_best_architecture/pull/621)
* Update the menu path and type columns by [@wu-clan](https://github.com/wu-clan) in [#622](https://github.com/fastapi-practices/fastapi_best_architecture/pull/622)
* Add the deepwiki badge to README by [@wu-clan](https://github.com/wu-clan) in [#623](https://github.com/fastapi-practices/fastapi_best_architecture/pull/623)
* Refactor the system token to online users by [@wu-clan](https://github.com/wu-clan) in [#624](https://github.com/fastapi-practices/fastapi_best_architecture/pull/624)
* Update the token check for logout interface by [@wu-clan](https://github.com/wu-clan) in [#625](https://github.com/fastapi-practices/fastapi_best_architecture/pull/625)
* Update the token decode for logout interface by [@wu-clan](https://github.com/wu-clan) in [#629](https://github.com/fastapi-practices/fastapi_best_architecture/pull/629)
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.4.0...v1.4.1
[Changes][v1.4.1]
<a id="v1.4.0"></a>
# [v1.4.0](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.4.0) - 2025-05-22
## What's Changed
* Update changelog for v1.3.0 by [@wu-clan](https://github.com/wu-clan) in [#605](https://github.com/fastapi-practices/fastapi_best_architecture/pull/605)
* Add new plugin status check interface by [@wu-clan](https://github.com/wu-clan) in [#606](https://github.com/fastapi-practices/fastapi_best_architecture/pull/606)
* Update the new plugin status to changed by [@wu-clan](https://github.com/wu-clan) in [#607](https://github.com/fastapi-practices/fastapi_best_architecture/pull/607)
* Fix the task result schema param type by [@wu-clan](https://github.com/wu-clan) in [#611](https://github.com/fastapi-practices/fastapi_best_architecture/pull/611)
* Fix the plugin status update logic by [@wu-clan](https://github.com/wu-clan) in [#613](https://github.com/fastapi-practices/fastapi_best_architecture/pull/613)
* Update uninstall and build plugin api method by [@wu-clan](https://github.com/wu-clan) in [#614](https://github.com/fastapi-practices/fastapi_best_architecture/pull/614)
* Fix non-asyncio nested async IO by [@wu-clan](https://github.com/wu-clan) in [#610](https://github.com/fastapi-practices/fastapi_best_architecture/pull/610)
* Update the build plugin api params by [@wu-clan](https://github.com/wu-clan) in [#615](https://github.com/fastapi-practices/fastapi_best_architecture/pull/615)
* Update uv installation in docker deploy by [@wu-clan](https://github.com/wu-clan) in [#619](https://github.com/fastapi-practices/fastapi_best_architecture/pull/619)
* Update the OAuth2 module to plugin by [@wu-clan](https://github.com/wu-clan) in [#620](https://github.com/fastapi-practices/fastapi_best_architecture/pull/620)
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.3.0...v1.4.0
[Changes][v1.4.0]
<a id="v1.3.0"></a>
# [v1.3.0](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.3.0) - 2025-05-16
@@ -511,6 +570,9 @@
[Changes][v1.0.0]
[v1.4.2]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.4.1...v1.4.2
[v1.4.1]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.4.0...v1.4.1
[v1.4.0]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.3.0...v1.4.0
[v1.3.0]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.2.0...v1.3.0
[v1.2.0]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.1.2...v1.2.0
[v1.1.2]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.1.1...v1.1.2
+3 -43
View File
@@ -4,11 +4,9 @@
# FastAPI Best Architecture
English | [简体中文](./README.zh-CN.md)
Enterprise-level backend architecture solution
**🔥Continuously updated and maintained🔥**
English | [简体中文](./README.zh-CN.md)
[![GitHub](https://img.shields.io/github/license/fastapi-practices/fastapi_best_architecture)](https://github.com/fastapi-practices/fastapi_best_architecture/blob/master/LICENSE)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/downloads/)
@@ -21,12 +19,10 @@ Enterprise-level backend architecture solution
![Docker](https://img.shields.io/badge/Docker-%232496ED?logo=docker&logoColor=white)
[![Discord](https://img.shields.io/badge/Discord-%235865F2.svg?logo=discord&logoColor=white)](https://discord.com/invite/yNN3wTbVAC)
![Discord](https://img.shields.io/discord/1185035164577972344)
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/fastapi-practices/fastapi_best_architecture)
</div>
> [!NOTE]
> This repository as a template library open to any person or enterprise can be used for free!
## Pseudo 3-tier architecture
The mvc architecture is a common design pattern in python web, but the 3-tier architecture is even more fascinating
@@ -45,43 +41,7 @@ pattern, use templates to transform it to your heart's content!
| data access | dao / mapper | crud |
| model | model / entity | model |
## Features
- [x] Global FastAPI PEP 593 Annotated parameter style
- [x] Comprehensive async/await + asgiref asynchronous design
- [x] Adheres to RESTful API specifications
- [x] Uses SQLAlchemy 2.0 with new syntax
- [x] Uses Pydantic v2 version
- [x] Implements role-menu RBAC access control
- [x] Integrates Casbin RBAC access control
- [x] Supports Celery asynchronous tasks
- [x] Custom-developed JWT authentication middleware
- [x] Supports global custom time zones
- [x] Supports Docker / Docker-compose deployment
- [x] Integrates Pytest unit testing
## Built-in Functions
- [x] User Management: Assign roles and permissions
- [x] Department Management: Configure organizational structure (company, department, team, etc.)
- [x] Menu Management: Set up menus and button-level permissions
- [x] Role Management: Configure roles, assign menus and permissions
- [x] Dictionary Management: Maintain common parameters and configurations
- [x] Parameter Management: Dynamically configure commonly used system parameters
- [x] Notification Announcements: Publish and maintain system notification and announcement information
- [x] Token Management: Detect online status, support forced logout
- [x] Multi-device Login: Support one-click switching between multi-device login modes
- [x] OAuth 2.0: Built-in custom-developed OAuth 2.0 authorization login
- [x] Plugin System: Hot-swappable plugin design to reduce coupling
- [x] Scheduled Tasks: Support scheduled, asynchronous tasks, and function calls
- [x] Code Generation: Automatically generate code with preview, write, and download support
- [x] Operation Logs: Record and query normal and abnormal operations
- [x] Login Logs: Record and query normal and abnormal logins
- [x] Cache Monitoring: Query system cache information and command statistics
- [x] Service Monitoring: View server hardware information and status
- [x] API Documentation: Automatically generate online interactive API documentation
## Development and deployment
## Help
For more details, please check
the [official documentation](https://fastapi-practices.github.io/fastapi_best_architecture_docs/)
+3 -43
View File
@@ -4,11 +4,9 @@
# FastAPI Best Architecture
简体中文 | [English](./README.md)
企业级后端架构解决方案
**🔥持续更新维护中🔥**
简体中文 | [English](./README.md)
[![GitHub](https://img.shields.io/github/license/fastapi-practices/fastapi_best_architecture)](https://github.com/fastapi-practices/fastapi_best_architecture/blob/master/LICENSE)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/downloads/)
@@ -21,12 +19,10 @@
![Docker](https://img.shields.io/badge/Docker-%232496ED?logo=docker&logoColor=white)
[![Discord](https://img.shields.io/badge/Discord-%235865F2.svg?logo=discord&logoColor=white)](https://discord.com/invite/yNN3wTbVAC)
![Discord](https://img.shields.io/discord/1185035164577972344)
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/fastapi-practices/fastapi_best_architecture)
</div>
> [!NOTE]
> 此仓库作为模板库公开,任何人或企业均可免费使用!
## 伪三层架构
mvc 架构作为常规设计模式,在 python web 中也很常见,但是三层架构更令人着迷
@@ -43,43 +39,7 @@ mvc 架构作为常规设计模式,在 python web 中也很常见,但是三
| 数据访问 | dao / mapper | crud |
| 模型 | model / entity | model |
## 特性
- [x] 全局 FastAPI PEP 593 Annotated 参数风格
- [x] 全面 async/await + asgiref 异步设计
- [x] 遵循 RESTful API 规范
- [x] 使用 SQLAlchemy 2.0 全新语法
- [x] 使用 Pydantic v2 版本
- [x] 实现角色菜单 RBAC 访问控制
- [x] 集成 Casbin RBAC 访问控制
- [x] 支持 Celery 异步任务
- [x] 自研 JWT 认证中间件
- [x] 支持全局自定义时间时区
- [x] 支持 Docker / Docker-compose 部署
- [x] 集成 Pytest 单元测试
## 内置功能
- [x] 用户管理:分配角色和权限
- [x] 部门管理:配置组织架构(公司、部门、小组等)
- [x] 菜单管理:设置菜单及按钮级权限
- [x] 角色管理:配置角色、分配菜单和权限
- [x] 字典管理:维护常用参数和配置
- [x] 参数管理:系统常用参数动态配置
- [x] 通知公告:发布和维护系统通知公告信息
- [x] 令牌管理:检测在线状态,支持强制下线
- [x] 多端登录:支持一键切换多端登录模式
- [x] OAuth 2.0:内置自研 OAuth 2.0 授权登录
- [x] 插件系统:热插拔插件设计,降低耦合
- [x] 定时任务:支持定时,异步任务及函数调用
- [x] 代码生成:自动生成代码,支持预览、写入和下载
- [x] 操作日志:记录和查询正常和异常操作
- [x] 登录日志:记录和查询正常和异常登录
- [x] 缓存监控:查询系统缓存信息和命令统计
- [x] 服务监控:查看服务器硬件信息和状态
- [x] 接口文档:自动生成在线交互式 API 文档
## 开发部署
## 帮助
更多详情请查看 [官方文档](https://fastapi-practices.github.io/fastapi_best_architecture_docs/)
+3 -4
View File
@@ -11,7 +11,6 @@ from backend.app.admin.schema.token import GetLoginToken, GetNewToken, GetSwagge
from backend.app.admin.schema.user import AuthLoginParam
from backend.app.admin.service.auth_service import auth_service
from backend.common.response.response_schema import ResponseModel, ResponseSchemaModel, response_base
from backend.common.security.jwt import DependsJwtAuth
router = APIRouter()
@@ -35,13 +34,13 @@ async def user_login(
return response_base.success(data=data)
@router.post('/token/new', summary='创建新 token')
async def create_new_token(request: Request) -> ResponseSchemaModel[GetNewToken]:
@router.post('/tokens/refresh', summary='新 token')
async def refresh_token(request: Request) -> ResponseSchemaModel[GetNewToken]:
data = await auth_service.new_token(request=request)
return response_base.success(data=data)
@router.post('/logout', summary='用户登出', dependencies=[DependsJwtAuth])
@router.post('/logout', summary='用户登出')
async def user_logout(request: Request, response: Response) -> ResponseModel:
await auth_service.logout(request=request, response=response)
return response_base.success()
@@ -2,6 +2,7 @@
# -*- coding: utf-8 -*-
from fastapi import APIRouter
from backend.app.admin.api.v1.monitor.online import router as token_router
from backend.app.admin.api.v1.monitor.redis import router as redis_router
from backend.app.admin.api.v1.monitor.server import router as server_router
@@ -9,3 +10,4 @@ router = APIRouter(prefix='/monitors')
router.include_router(redis_router, prefix='/redis', tags=['redis监控'])
router.include_router(server_router, prefix='/server', tags=['服务器监控'])
router.include_router(token_router, prefix='/online', tags=['在线用户'])
@@ -6,7 +6,7 @@ from typing import Annotated
from fastapi import APIRouter, Depends, Path, Query, Request
from backend.app.admin.schema.token import GetTokenDetail, KickOutToken
from backend.app.admin.schema.token import GetTokenDetail
from backend.common.enums import StatusType
from backend.common.response.response_schema import ResponseModel, ResponseSchemaModel, response_base
from backend.common.security.jwt import DependsJwtAuth, jwt_decode, revoke_token, superuser_verify
@@ -18,8 +18,8 @@ from backend.database.redis import redis_client
router = APIRouter()
@router.get('', summary='获取令牌列表', dependencies=[DependsJwtAuth])
async def get_tokens(
@router.get('', summary='获取在线用户', dependencies=[DependsJwtAuth])
async def get_online(
username: Annotated[str | None, Query(description='用户名')] = None,
) -> ResponseSchemaModel[list[GetTokenDetail]]:
token_keys = await redis_client.keys(f'{settings.TOKEN_REDIS_PREFIX}:*')
@@ -82,8 +82,10 @@ async def get_tokens(
],
)
async def kick_out(
request: Request, pk: Annotated[int, Path(description='用户 ID')], obj: KickOutToken
request: Request,
pk: Annotated[int, Path(description='用户 ID')],
session_uuid: Annotated[str, Query(description='会话 UUID')],
) -> ResponseModel:
superuser_verify(request)
await revoke_token(str(pk), obj.session_uuid)
await revoke_token(str(pk), session_uuid)
return response_base.success()
+1 -3
View File
@@ -8,7 +8,6 @@ from backend.app.admin.api.v1.sys.dept import router as dept_router
from backend.app.admin.api.v1.sys.menu import router as menu_router
from backend.app.admin.api.v1.sys.plugin import router as plugin_router
from backend.app.admin.api.v1.sys.role import router as role_router
from backend.app.admin.api.v1.sys.token import router as token_router
from backend.app.admin.api.v1.sys.upload import router as upload_router
from backend.app.admin.api.v1.sys.user import router as user_router
@@ -20,6 +19,5 @@ router.include_router(role_router, prefix='/roles', tags=['系统角色'])
router.include_router(user_router, prefix='/users', tags=['系统用户'])
router.include_router(data_rule_router, prefix='/data-rules', tags=['系统数据规则'])
router.include_router(data_scope_router, prefix='/data-scopes', tags=['系统数据范围'])
router.include_router(token_router, prefix='/tokens', tags=['系统令牌'])
router.include_router(upload_router, prefix='/upload', tags=['系统上传'])
router.include_router(plugin_router, prefix='/plugin', tags=['系统插件'])
router.include_router(plugin_router, prefix='/plugins', tags=['系统插件'])
+1 -1
View File
@@ -27,7 +27,7 @@ async def get_data_rule_models() -> ResponseSchemaModel[list[str]]:
return response_base.success(data=models)
@router.get('/model/{model}/columns', summary='获取数据规则可用模型列', dependencies=[DependsJwtAuth])
@router.get('/models/{model}/columns', summary='获取数据规则可用模型列', dependencies=[DependsJwtAuth])
async def get_data_rule_model_columns(
model: Annotated[str, Path(description='模型名称')],
) -> ResponseSchemaModel[list[GetDataRuleColumnDetail]]:
@@ -22,6 +22,12 @@ from backend.database.db import CurrentSession
router = APIRouter()
@router.get('/all', summary='获取所有数据范围', dependencies=[DependsJwtAuth])
async def get_all_data_scope() -> ResponseSchemaModel[list[GetDataScopeDetail]]:
data = await data_scope_service.get_all()
return response_base.success(data=data)
@router.get('/{pk}', summary='获取数据范围详情', dependencies=[DependsJwtAuth])
async def get_data_scope(
pk: Annotated[int, Path(description='数据范围 ID')],
+3 -3
View File
@@ -15,8 +15,8 @@ router = APIRouter()
@router.get('/sidebar', summary='获取用户菜单侧边栏', description='适配 vben5', dependencies=[DependsJwtAuth])
async def get_user_sidebar(request: Request) -> ResponseSchemaModel[list[dict[str, Any]]]:
menu = await menu_service.get_user_menu_tree(request=request)
async def get_user_sidebar(request: Request) -> ResponseSchemaModel[list[dict[str, Any] | None]]:
menu = await menu_service.get_sidebar(request=request)
return response_base.success(data=menu)
@@ -71,7 +71,7 @@ async def update_menu(pk: Annotated[int, Path(description='菜单 ID')], obj: Up
DependsRBAC,
],
)
async def delete_menu(pk: Annotated[int, Path(description='菜单 ID 列表')]) -> ResponseModel:
async def delete_menu(pk: Annotated[int, Path(description='菜单 ID')]) -> ResponseModel:
count = await menu_service.delete(pk=pk)
if count > 0:
return response_base.success()
+12 -12
View File
@@ -22,18 +22,18 @@ async def get_all_plugins() -> ResponseSchemaModel[list[dict[str, Any]]]:
return response_base.success(data=plugins)
@router.get('/changed', summary='插件状态是否变更', dependencies=[DependsJwtAuth])
@router.get('/changes', summary='插件状态是否变更', dependencies=[DependsJwtAuth])
async def plugin_changed() -> ResponseSchemaModel[bool]:
plugins = await plugin_service.changed()
return response_base.success(data=bool(plugins))
@router.post(
'/install/zip',
'/zip',
summary='安装 zip 插件',
description='使用插件 zip 压缩包进行安装',
dependencies=[
Depends(RequestPermission('sys:plugin:install')),
Depends(RequestPermission('sys:plugin:zip')),
DependsRBAC,
],
)
@@ -43,11 +43,11 @@ async def install_zip_plugin(file: Annotated[UploadFile, File()]) -> ResponseMod
@router.post(
'/install/git',
'/git',
summary='安装 git 插件',
description='使用插件 git 仓库地址进行安装,不限制平台;如果需要凭证,需在 git 仓库地址中添加凭证信息',
dependencies=[
Depends(RequestPermission('sys:plugin:install')),
Depends(RequestPermission('sys:plugin:git')),
DependsRBAC,
],
)
@@ -57,35 +57,35 @@ async def install_git_plugin(repo_url: Annotated[str, Query(description='插件
@router.delete(
'/uninstall',
'/{plugin}',
summary='卸载插件',
description='此操作会直接删除插件依赖,但不会直接删除插件,而是将插件移动到备份目录',
dependencies=[
Depends(RequestPermission('sys:plugin:uninstall')),
Depends(RequestPermission('sys:plugin:del')),
DependsRBAC,
],
)
async def uninstall_plugin(plugin: Annotated[str, Query(description='插件名称')]) -> ResponseModel:
async def uninstall_plugin(plugin: Annotated[str, Path(description='插件名称')]) -> ResponseModel:
await plugin_service.uninstall(plugin=plugin)
return response_base.success(res=CustomResponseCode.PLUGIN_UNINSTALL_SUCCESS)
@router.post(
'/status',
'/{plugin}/status',
summary='更新插件状态',
dependencies=[
Depends(RequestPermission('sys:plugin:status')),
DependsRBAC,
],
)
async def update_plugin_status(plugin: Annotated[str, Query(description='插件名称')]) -> ResponseModel:
async def update_plugin_status(plugin: Annotated[str, Path(description='插件名称')]) -> ResponseModel:
await plugin_service.update_status(plugin=plugin)
return response_base.success()
@router.get(
'/zip/{plugin}',
summary='打包插件',
'/{plugin}',
summary='打包并下载插件',
dependencies=[
Depends(RequestPermission('sys:plugin:zip')),
DependsRBAC,
+3 -11
View File
@@ -29,18 +29,10 @@ async def get_all_roles() -> ResponseSchemaModel[list[GetRoleDetail]]:
return response_base.success(data=data)
@router.get('/{pk}/all', summary='获取用户所有角色', dependencies=[DependsJwtAuth])
async def get_user_all_roles(
pk: Annotated[int, Path(description='用户 ID')],
) -> ResponseSchemaModel[list[GetRoleDetail]]:
data = await role_service.get_users(pk=pk)
return response_base.success(data=data)
@router.get('/{pk}/menus', summary='获取角色所有菜单', dependencies=[DependsJwtAuth])
async def get_role_all_menus(
pk: Annotated[int, Path(description='角色 ID')],
) -> ResponseSchemaModel[list[dict[str, Any]]]:
) -> ResponseSchemaModel[list[dict[str, Any] | None]]:
menu = await role_service.get_menu_tree(pk=pk)
return response_base.success(data=menu)
@@ -106,7 +98,7 @@ async def update_role(pk: Annotated[int, Path(description='角色 ID')], obj: Up
@router.put(
'/{pk}/menu',
'/{pk}/menus',
summary='更新角色菜单',
dependencies=[
Depends(RequestPermission('sys:role:menu:edit')),
@@ -123,7 +115,7 @@ async def update_role_menus(
@router.put(
'/{pk}/scope',
'/{pk}/scopes',
summary='更新角色数据范围',
dependencies=[
Depends(RequestPermission('sys:role:scope:edit')),
+22 -38
View File
@@ -4,15 +4,14 @@ from typing import Annotated
from fastapi import APIRouter, Depends, Path, Query, Request
from backend.app.admin.schema.role import GetRoleDetail
from backend.app.admin.schema.user import (
AddUserParam,
AvatarParam,
GetCurrentUserInfoWithRelationDetail,
GetUserInfoWithRelationDetail,
RegisterUserParam,
ResetPasswordParam,
UpdateUserParam,
UpdateUserRoleParam,
)
from backend.app.admin.service.user_service import user_service
from backend.common.pagination import DependsPagination, PageData, paging_data
@@ -38,9 +37,11 @@ async def add_user(request: Request, obj: AddUserParam) -> ResponseSchemaModel[G
return response_base.success(data=data)
@router.post('/password/reset', summary='密码重置', dependencies=[DependsJwtAuth])
async def password_reset(request: Request, obj: ResetPasswordParam) -> ResponseModel:
count = await user_service.pwd_reset(request=request, obj=obj)
@router.post('/{username}/password', summary='密码重置', dependencies=[DependsJwtAuth])
async def password_reset(
username: Annotated[str, Path(description='用户名')], obj: ResetPasswordParam
) -> ResponseModel:
count = await user_service.pwd_reset(username=username, obj=obj)
if count > 0:
return response_base.success()
return response_base.fail()
@@ -60,39 +61,12 @@ async def get_user(
return response_base.success(data=data)
@router.put('/{username}', summary='更新用户信息', dependencies=[DependsJwtAuth])
async def update_user(
request: Request, username: Annotated[str, Path(description='用户名')], obj: UpdateUserParam
) -> ResponseModel:
count = await user_service.update(request=request, username=username, obj=obj)
if count > 0:
return response_base.success()
return response_base.fail()
@router.put(
'/{username}/role',
summary='更新用户角色',
dependencies=[
Depends(RequestPermission('sys:user:role:edit')),
DependsRBAC,
],
)
async def update_user_role(
request: Request, username: Annotated[str, Path(description='用户名')], obj: UpdateUserRoleParam
) -> ResponseModel:
await user_service.update_roles(request=request, username=username, obj=obj)
return response_base.success()
@router.put('/{username}/avatar', summary='更新头像', dependencies=[DependsJwtAuth])
async def update_avatar(
request: Request, username: Annotated[str, Path(description='用户名')], avatar: AvatarParam
) -> ResponseModel:
count = await user_service.update_avatar(request=request, username=username, avatar=avatar)
if count > 0:
return response_base.success()
return response_base.fail()
@router.get('/{username}/roles', summary='获取用户所有角色', dependencies=[DependsJwtAuth])
async def get_user_all_roles(
username: Annotated[str, Path(description='用户名')],
) -> ResponseSchemaModel[list[GetRoleDetail]]:
data = await user_service.get_roles(username=username)
return response_base.success(data=data)
@router.get(
@@ -115,6 +89,16 @@ async def get_pagination_users(
return response_base.success(data=page_data)
@router.put('/{username}', summary='更新用户信息', dependencies=[DependsJwtAuth])
async def update_user(
request: Request, username: Annotated[str, Path(description='用户名')], obj: UpdateUserParam
) -> ResponseModel:
count = await user_service.update(request=request, username=username, obj=obj)
if count > 0:
return response_base.success()
return response_base.fail()
@router.put('/{pk}/super', summary='修改用户超级权限', dependencies=[DependsRBAC])
async def super_set(request: Request, pk: Annotated[int, Path(description='用户 ID')]) -> ResponseModel:
count = await user_service.update_permission(request=request, pk=pk)
+11
View File
@@ -1,5 +1,7 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Sequence
from sqlalchemy import Select, and_, desc, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import noload, selectinload
@@ -44,6 +46,15 @@ class CRUDDataScope(CRUDPlus[DataScope]):
data_scope = await db.execute(stmt)
return data_scope.scalars().first()
async def get_all(self, db: AsyncSession) -> Sequence[DataScope]:
"""
获取所有数据范围
:param db: 数据库会话
:return:
"""
return await self.select_models(db)
async def get_list(self, name: str | None, status: int | None) -> Select:
"""
获取数据范围列表
+2 -2
View File
@@ -45,12 +45,12 @@ class CRUDMenu(CRUDPlus[Menu]):
"""
filters = {}
if title is not None:
filters.update(title=f'%{title}%')
filters.update(title__like=f'%{title}%')
if status is not None:
filters.update(status=status)
return await self.select_models_order(db, 'sort', **filters)
async def get_role_menus(self, db: AsyncSession, superuser: bool, menu_ids: list[int]) -> Sequence[Menu]:
async def get_sidebar(self, db: AsyncSession, superuser: bool, menu_ids: list[int | None]) -> Sequence[Menu]:
"""
获取角色菜单列表
+1 -13
View File
@@ -7,7 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import noload, selectinload
from sqlalchemy_crud_plus import CRUDPlus
from backend.app.admin.model import DataScope, Menu, Role, User
from backend.app.admin.model import DataScope, Menu, Role
from backend.app.admin.schema.role import (
CreateRoleParam,
UpdateRoleMenuParam,
@@ -54,18 +54,6 @@ class CRUDRole(CRUDPlus[Role]):
"""
return await self.select_models(db)
async def get_users(self, db: AsyncSession, user_id: int) -> Sequence[Role]:
"""
获取用户角色列表
:param db: 数据库会话
:param user_id: 用户 ID
:return:
"""
stmt = select(self.model).join(self.model.users).where(User.id == user_id)
roles = await db.execute(stmt)
return roles.scalars().all()
async def get_list(self, name: str | None, status: int | None) -> Select:
"""
获取角色列表
+11 -36
View File
@@ -11,10 +11,8 @@ from sqlalchemy_crud_plus import CRUDPlus
from backend.app.admin.model import Dept, Role, User
from backend.app.admin.schema.user import (
AddUserParam,
AvatarParam,
RegisterUserParam,
UpdateUserParam,
UpdateUserRoleParam,
)
from backend.common.security.jwt import get_hash_password
from backend.utils.timezone import timezone
@@ -97,14 +95,13 @@ class CRUDUser(CRUDPlus[User]):
dict_obj.update({'salt': salt})
new_user = self.model(**dict_obj)
role_list = []
for role_id in obj.roles:
role_list.append(await db.get(Role, role_id))
new_user.roles.extend(role_list)
stmt = select(Role).where(Role.id.in_(obj.roles))
roles = await db.execute(stmt)
new_user.roles = roles.scalars().all()
db.add(new_user)
async def update_userinfo(self, db: AsyncSession, input_user: int, obj: UpdateUserParam) -> int:
async def update(self, db: AsyncSession, input_user: User, obj: UpdateUserParam) -> int:
"""
更新用户信息
@@ -113,36 +110,14 @@ class CRUDUser(CRUDPlus[User]):
:param obj: 更新用户参数
:return:
"""
return await self.update_model(db, input_user, obj)
role_ids = obj.roles
del obj.roles
count = await self.update_model(db, input_user.id, obj)
@staticmethod
async def update_role(db: AsyncSession, input_user: User, obj: UpdateUserRoleParam) -> None:
"""
更新用户角色
:param db: 数据库会话
:param input_user: 用户对象
:param obj: 更新角色参数
:return:
"""
for i in list(input_user.roles):
input_user.roles.remove(i)
role_list = []
for role_id in obj.roles:
role_list.append(await db.get(Role, role_id))
input_user.roles.extend(role_list)
async def update_avatar(self, db: AsyncSession, input_user: int, avatar: AvatarParam) -> int:
"""
更新用户头像
:param db: 数据库会话
:param input_user: 用户 ID
:param avatar: 头像地址
:return:
"""
return await self.update_model(db, input_user, {'avatar': str(avatar.url)})
stmt = select(Role).where(Role.id.in_(role_ids))
roles = await db.execute(stmt)
input_user.roles = roles.scalars().all()
return count
async def delete(self, db: AsyncSession, user_id: int) -> int:
"""
+2 -2
View File
@@ -24,10 +24,10 @@ class Menu(Base):
id: Mapped[id_key] = mapped_column(init=False)
title: Mapped[str] = mapped_column(String(50), comment='菜单标题')
name: Mapped[str] = mapped_column(String(50), comment='菜单名称')
path: Mapped[str] = mapped_column(String(200), comment='路由地址')
path: Mapped[str | None] = mapped_column(String(200), comment='路由地址')
sort: Mapped[int] = mapped_column(default=0, comment='排序')
icon: Mapped[str | None] = mapped_column(String(100), default=None, comment='菜单图标')
type: Mapped[int] = mapped_column(default=0, comment='菜单类型(0目录 1菜单 2按钮)')
type: Mapped[int] = mapped_column(default=0, comment='菜单类型(0目录 1菜单 2按钮 3内嵌 4外链')
component: Mapped[str | None] = mapped_column(String(255), default=None, comment='组件路径')
perms: Mapped[str | None] = mapped_column(String(100), default=None, comment='权限标识')
status: Mapped[int] = mapped_column(default=1, comment='菜单状态(0停用 1正常)')
+5 -2
View File
@@ -4,9 +4,9 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from sqlalchemy import String
from sqlalchemy import Boolean, String
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import TEXT
from sqlalchemy.dialects.postgresql import INTEGER, TEXT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.app.admin.model.m2m import sys_role_data_scope, sys_role_menu, sys_user_role
@@ -24,6 +24,9 @@ class Role(Base):
id: Mapped[id_key] = mapped_column(init=False)
name: Mapped[str] = mapped_column(String(20), unique=True, comment='角色名称')
status: Mapped[int] = mapped_column(default=1, comment='角色状态(0停用 1正常)')
is_filter_scopes: Mapped[bool] = mapped_column(
Boolean().with_variant(INTEGER, 'postgresql'), default=True, comment='过滤数据权限(0否 1是)'
)
remark: Mapped[str | None] = mapped_column(
LONGTEXT().with_variant(TEXT, 'postgresql'), default=None, comment='备注'
)
+2 -2
View File
@@ -13,11 +13,11 @@ class MenuSchemaBase(SchemaBase):
title: str = Field(description='菜单标题')
name: str = Field(description='菜单名称')
path: str = Field(description='路由路径')
path: str | None = Field(None, description='路由地址')
parent_id: int | None = Field(None, description='菜单父级 ID')
sort: int = Field(0, ge=0, description='排序')
icon: str | None = Field(None, description='图标')
type: MenuType = Field(MenuType.directory, description='菜单类型(0目录 1菜单 2按钮)')
type: MenuType = Field(MenuType.directory, description='菜单类型(0目录 1菜单 2按钮 3内嵌 4外链')
component: str | None = Field(None, description='组件路径')
perms: str | None = Field(None, description='权限标识')
status: StatusType = Field(StatusType.enable, description='状态')
+1
View File
@@ -15,6 +15,7 @@ class RoleSchemaBase(SchemaBase):
name: str = Field(description='角色名称')
status: StatusType = Field(StatusType.enable, description='状态')
is_filter_scopes: bool = Field(True, description='过滤数据权限')
remark: str | None = Field(None, description='备注')
-6
View File
@@ -35,12 +35,6 @@ class GetLoginToken(AccessTokenBase):
user: GetUserInfoDetail = Field(description='用户信息')
class KickOutToken(SchemaBase):
"""踢出令牌"""
session_uuid: str = Field(description='会话 UUID')
class GetTokenDetail(SchemaBase):
"""令牌详情"""
+1 -10
View File
@@ -55,6 +55,7 @@ class UserInfoSchemaBase(SchemaBase):
dept_id: int | None = Field(None, description='部门 ID')
username: str = Field(description='用户名')
nickname: str = Field(description='昵称')
avatar: HttpUrl | None = Field(None, description='头像')
email: EmailStr = Field(examples=['user@example.com'], description='邮箱')
phone: CustomPhoneNumber | None = Field(None, description='手机号')
@@ -62,19 +63,9 @@ class UserInfoSchemaBase(SchemaBase):
class UpdateUserParam(UserInfoSchemaBase):
"""更新用户参数"""
class UpdateUserRoleParam(SchemaBase):
"""更新用户角色参数"""
roles: list[int] = Field(description='角色 ID 列表')
class AvatarParam(SchemaBase):
"""更新头像参数"""
url: HttpUrl = Field(description='头像 http 地址')
class GetUserInfoDetail(UserInfoSchemaBase):
"""用户信息详情"""
+14 -8
View File
@@ -92,7 +92,7 @@ class AuthService:
user = await self.user_verify(db, obj.username, obj.password)
captcha_code = await redis_client.get(f'{settings.CAPTCHA_LOGIN_REDIS_PREFIX}:{request.state.ip}')
if not captcha_code:
raise errors.AuthorizationError(msg='验证码失效,请重新获取')
raise errors.ForbiddenError(msg='验证码失效,请重新获取')
if captcha_code.lower() != obj.captcha.lower():
raise errors.CustomError(error=CustomErrorCode.CAPTCHA_ERROR)
await redis_client.delete(f'{settings.CAPTCHA_LOGIN_REDIS_PREFIX}:{request.state.ip}')
@@ -121,7 +121,7 @@ class AuthService:
except errors.NotFoundError as e:
log.error('登陆错误: 用户名不存在')
raise errors.NotFoundError(msg=e.msg)
except (errors.AuthorizationError, errors.CustomError) as e:
except (errors.ForbiddenError, errors.CustomError) as e:
if not user:
log.error('登陆错误: 用户密码有误')
task = BackgroundTask(
@@ -136,7 +136,7 @@ class AuthService:
msg=e.msg,
),
)
raise errors.AuthorizationError(msg=e.msg, background=task)
raise errors.RequestError(msg=e.msg, background=task)
except Exception as e:
log.error(f'登陆错误: {e}')
raise e
@@ -211,11 +211,17 @@ class AuthService:
:param response: FastAPI 响应对象
:return:
"""
token = get_token(request)
token_payload = jwt_decode(token)
user_id = token_payload.id
refresh_token = request.cookies.get(settings.COOKIE_REFRESH_TOKEN_KEY)
response.delete_cookie(settings.COOKIE_REFRESH_TOKEN_KEY)
try:
token = get_token(request)
token_payload = jwt_decode(token)
user_id = token_payload.id
refresh_token = request.cookies.get(settings.COOKIE_REFRESH_TOKEN_KEY)
except errors.TokenError:
return
finally:
response.delete_cookie(settings.COOKIE_REFRESH_TOKEN_KEY)
# 清理缓存
if request.user.is_multi_login:
await redis_client.delete(f'{settings.TOKEN_REDIS_PREFIX}:{user_id}:{token_payload.session_uuid}')
if refresh_token:
@@ -1,5 +1,7 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Sequence
from sqlalchemy import Select
from backend.app.admin.crud.crud_data_scope import data_scope_dao
@@ -28,6 +30,13 @@ class DataScopeService:
raise errors.NotFoundError(msg='数据范围不存在')
return data_scope
@staticmethod
async def get_all() -> Sequence[DataScope]:
"""获取所有数据范围"""
async with async_db_session() as db:
data_scopes = await data_scope_dao.get_all(db)
return data_scopes
@staticmethod
async def get_rules(*, pk: int) -> DataScope:
"""
+15 -8
View File
@@ -41,27 +41,34 @@ class MenuService:
:return:
"""
async with async_db_session() as db:
menu_select = await menu_dao.get_all(db, title=title, status=status)
menu_tree = get_tree_data(menu_select)
menu_data = await menu_dao.get_all(db, title=title, status=status)
menu_tree = get_tree_data(menu_data)
return menu_tree
@staticmethod
async def get_user_menu_tree(*, request: Request) -> list[dict[str, Any]]:
async def get_sidebar(*, request: Request) -> list[dict[str, Any] | None]:
"""
获取用户的菜单树形结构
获取用户的菜单侧边栏
:param request: FastAPI 请求对象
:return:
"""
async with async_db_session() as db:
roles = request.user.roles
menu_ids = []
menu_tree = []
if roles:
unique_menus = {}
for role in roles:
menu_ids.extend([menu.id for menu in role.menus])
menu_select = await menu_dao.get_role_menus(db, request.user.is_superuser, menu_ids)
menu_tree = get_vben5_tree_data(menu_select)
for menu in role.menus:
unique_menus[menu.id] = menu
all_ids = set(unique_menus.keys())
valid_menu_ids = [
menu_id
for menu_id, menu in unique_menus.items()
if menu.parent_id is None or menu.parent_id in all_ids
]
menu_data = await menu_dao.get_sidebar(db, request.user.is_superuser, valid_menu_ids)
menu_tree = get_vben5_tree_data(menu_data)
return menu_tree
@staticmethod
+9 -16
View File
@@ -58,21 +58,14 @@ class PluginService:
raise errors.ForbiddenError(msg='插件压缩包格式非法')
with zipfile.ZipFile(file_bytes) as zf:
# 校验压缩包
plugin_dir = file.filename[:-4]
members_in_plugin_dir = [name for name in zf.namelist() if name.startswith(plugin_dir)]
if not members_in_plugin_dir:
plugin_namelist = zf.namelist()
plugin_name = plugin_namelist[0].split('/')[0]
if not plugin_namelist or plugin_name not in file.filename:
raise errors.ForbiddenError(msg='插件压缩包内容非法')
plugin_name = (
members_in_plugin_dir[0]
.replace('/', '')
.replace('-master', '')
.replace('-main', '')
.replace('-dev', '')
)
if (
len(members_in_plugin_dir) <= 3
or f'{plugin_dir}/plugin.toml' not in members_in_plugin_dir
or f'{plugin_dir}/README.md' not in members_in_plugin_dir
len(plugin_namelist) <= 3
or f'{plugin_name}/plugin.toml' not in plugin_namelist
or f'{plugin_name}/README.md' not in plugin_namelist
):
raise errors.ForbiddenError(msg='插件压缩包内缺少必要文件')
@@ -86,8 +79,8 @@ class PluginService:
# 解压(安装)
members = []
for member in zf.infolist():
if member.filename.startswith(plugin_dir):
new_filename = member.filename.replace(plugin_dir, '')
if member.filename.startswith(plugin_name):
new_filename = member.filename.replace(plugin_name, '')
if new_filename:
member.filename = new_filename
members.append(member)
@@ -182,7 +175,7 @@ class PluginService:
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, start=plugin_dir)
zf.write(file_path, arcname)
zf.write(file_path, os.path.join(plugin, arcname))
bio.seek(0)
return bio
+4 -19
View File
@@ -45,18 +45,6 @@ class RoleService:
roles = await role_dao.get_all(db)
return roles
@staticmethod
async def get_users(*, pk: int) -> Sequence[Role]:
"""
获取用户的角色列表
:param pk: 用户 ID
:return:
"""
async with async_db_session() as db:
roles = await role_dao.get_users(db, user_id=pk)
return roles
@staticmethod
async def get_select(*, name: str | None, status: int | None) -> Select:
"""
@@ -69,7 +57,7 @@ class RoleService:
return await role_dao.get_list(name=name, status=status)
@staticmethod
async def get_menu_tree(*, pk: int) -> list[dict[str, Any]]:
async def get_menu_tree(*, pk: int) -> list[dict[str, Any] | None]:
"""
获取角色的菜单树形结构
@@ -80,9 +68,7 @@ class RoleService:
role = await role_dao.get_with_relation(db, pk)
if not role:
raise errors.NotFoundError(msg='角色不存在')
menu_ids = [menu.id for menu in role.menus]
menu_select = await menu_dao.get_role_menus(db, False, menu_ids)
menu_tree = get_tree_data(menu_select)
menu_tree = get_tree_data(role.menus) if role.menus else []
return menu_tree
@staticmethod
@@ -128,8 +114,7 @@ class RoleService:
if not role:
raise errors.NotFoundError(msg='角色不存在')
if role.name != obj.name:
role = await role_dao.get_by_name(db, obj.name)
if role:
if await role_dao.get_by_name(db, obj.name):
raise errors.ForbiddenError(msg='角色已存在')
count = await role_dao.update(db, pk, obj)
for user in await role.awaitable_attrs.users:
@@ -146,7 +131,7 @@ class RoleService:
:return:
"""
async with async_db_session.begin() as db:
role = await role_dao.get_with_relation(db, pk)
role = await role_dao.get(db, pk)
if not role:
raise errors.NotFoundError(msg='角色不存在')
for menu_id in menu_ids.menus:
+38 -63
View File
@@ -2,20 +2,20 @@
# -*- coding: utf-8 -*-
import random
from typing import Sequence
from fastapi import Request
from sqlalchemy import Select
from backend.app.admin.crud.crud_dept import dept_dao
from backend.app.admin.crud.crud_role import role_dao
from backend.app.admin.crud.crud_user import user_dao
from backend.app.admin.model import User
from backend.app.admin.model import Role, User
from backend.app.admin.schema.user import (
AddUserParam,
AvatarParam,
RegisterUserParam,
ResetPasswordParam,
UpdateUserParam,
UpdateUserRoleParam,
)
from backend.common.exception import errors
from backend.common.security.jwt import get_hash_password, get_token, jwt_decode, password_verify, superuser_verify
@@ -83,16 +83,16 @@ class UserService:
await user_dao.add(db, obj)
@staticmethod
async def pwd_reset(*, request: Request, obj: ResetPasswordParam) -> int:
async def pwd_reset(*, username: str, obj: ResetPasswordParam) -> int:
"""
重置用户密码
:param request: FastAPI 请求对象
:param username: 用户名
:param obj: 密码重置参数
:return:
"""
async with async_db_session.begin() as db:
user = await user_dao.get(db, request.user.id)
user = await user_dao.get_by_username(db, username)
if not user:
raise errors.NotFoundError(msg='用户不存在')
if not password_verify(obj.old_password, user.password):
@@ -100,11 +100,11 @@ class UserService:
if obj.new_password != obj.confirm_password:
raise errors.ForbiddenError(msg='密码输入不一致')
new_pwd = get_hash_password(obj.new_password, user.salt)
count = await user_dao.reset_password(db, request.user.id, new_pwd)
count = await user_dao.reset_password(db, user.id, new_pwd)
key_prefix = [
f'{settings.TOKEN_REDIS_PREFIX}:{request.user.id}',
f'{settings.TOKEN_REFRESH_REDIS_PREFIX}:{request.user.id}',
f'{settings.JWT_USER_REDIS_PREFIX}:{request.user.id}',
f'{settings.TOKEN_REDIS_PREFIX}:{user.id}',
f'{settings.TOKEN_REFRESH_REDIS_PREFIX}:{user.id}',
f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}',
]
for prefix in key_prefix:
await redis_client.delete_prefix(prefix)
@@ -124,6 +124,33 @@ class UserService:
raise errors.NotFoundError(msg='用户不存在')
return user
@staticmethod
async def get_roles(*, username: str) -> Sequence[Role]:
"""
获取用户所有角色
:param username: 用户名
:return:
"""
async with async_db_session() as db:
user = await user_dao.get_with_relation(db, username=username)
if not user:
raise errors.NotFoundError(msg='用户不存在')
return user.roles
@staticmethod
async def get_select(*, dept: int, username: str, phone: str, status: int) -> Select:
"""
获取用户列表查询条件
:param dept: 部门 ID
:param username: 用户名
:param phone: 手机号
:param status: 状态
:return:
"""
return await user_dao.get_list(dept=dept, username=username, phone=phone, status=status)
@staticmethod
async def update(*, request: Request, username: str, obj: UpdateUserParam) -> int:
"""
@@ -152,66 +179,14 @@ class UserService:
email = await user_dao.check_email(db, obj.email)
if email:
raise errors.ForbiddenError(msg='邮箱已注册')
count = await user_dao.update_userinfo(db, user.id, obj)
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
return count
@staticmethod
async def update_roles(*, request: Request, username: str, obj: UpdateUserRoleParam) -> None:
"""
更新用户角色
:param request: FastAPI 请求对象
:param username: 用户名
:param obj: 角色更新参数
:return:
"""
async with async_db_session.begin() as db:
if not request.user.is_superuser and request.user.username != username:
raise errors.ForbiddenError(msg='你只能修改自己的信息')
input_user = await user_dao.get_with_relation(db, username=username)
if not input_user:
raise errors.NotFoundError(msg='用户不存在')
for role_id in obj.roles:
role = await role_dao.get(db, role_id)
if not role:
raise errors.NotFoundError(msg='角色不存在')
await user_dao.update_role(db, input_user, obj)
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{input_user.id}')
@staticmethod
async def update_avatar(*, request: Request, username: str, avatar: AvatarParam) -> int:
"""
更新用户头像
:param request: FastAPI 请求对象
:param username: 用户名
:param avatar: 头像参数
:return:
"""
async with async_db_session.begin() as db:
if request.user.username != username:
raise errors.AuthorizationError(msg='你只能修改自己的信息')
user = await user_dao.get_by_username(db, username)
if not user:
raise errors.NotFoundError(msg='用户不存在')
count = await user_dao.update_avatar(db, user.id, avatar)
count = await user_dao.update(db, user, obj)
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
return count
@staticmethod
async def get_select(*, dept: int, username: str, phone: str, status: int) -> Select:
"""
获取用户列表查询条件
:param dept: 部门 ID
:param username: 用户名
:param phone: 手机号
:param status: 状态
:return:
"""
return await user_dao.get_list(dept=dept, username=username, phone=phone, status=status)
@staticmethod
async def update_permission(*, request: Request, pk: int) -> int:
"""
+2
View File
@@ -44,6 +44,8 @@ class MenuType(IntEnum):
directory = 0
menu = 1
button = 2
embedded = 3
link = 4
class RoleDataRuleOperatorType(IntEnum):
+22 -19
View File
@@ -1,6 +1,5 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import TYPE_CHECKING
from fastapi import Request
from sqlalchemy import ColumnElement, and_, or_
@@ -13,9 +12,6 @@ from backend.common.exception.errors import ServerError
from backend.core.conf import settings
from backend.utils.import_parse import dynamic_import_data_model
if TYPE_CHECKING:
from backend.app.admin.model import DataRule
class RequestPermission:
"""
@@ -60,35 +56,42 @@ async def filter_data_permission(db: AsyncSession, request: Request) -> ColumnEl
:param request: FastAPI 请求对象
:return:
"""
# 获取用户角色和数据范围
data_scopes = []
# 是否过滤数据权限
if request.user.is_superuser:
return or_(1 == 1)
for role in request.user.roles:
if not role.is_filter_scopes:
return or_(1 == 1)
# 获取数据范围
unique_data_scopes = {}
for role in request.user.roles:
for scope in role.scopes:
if scope.status:
data_scopes.append(scope)
unique_data_scopes[scope.id] = scope
# 超级管理员和无规则用户不做过滤
if request.user.is_superuser or not data_scopes:
# 转换为列表
data_scopes = list(unique_data_scopes.values())
# 无规则用户不做过滤
if not data_scopes:
return or_(1 == 1)
# 获取数据范围规则
data_rule_list: list[DataRule] = []
unique_data_rules = {}
for data_scope in data_scopes:
data_scope_with_relation = await data_scope_dao.get_with_relation(db, data_scope.id)
data_rule_list.extend(data_scope_with_relation.rules)
for rule in data_scope_with_relation.rules:
unique_data_rules[rule.id] = rule
# 去重
seen_data_rule_ids = set()
new_data_rule_list = []
for rule in data_rule_list:
if rule.id not in seen_data_rule_ids:
seen_data_rule_ids.add(rule.id)
new_data_rule_list.append(rule)
# 转换为列表
data_rule_list = list(unique_data_rules.values())
where_and_list = []
where_or_list = []
for data_rule in new_data_rule_list:
for data_rule in data_rule_list:
# 验证规则模型
rule_model = data_rule.model
if rule_model not in settings.DATA_PERMISSION_MODELS:
+9 -4
View File
@@ -60,12 +60,17 @@ async def rbac_verify(request: Request, _token: str = DependsJwtAuth) -> None:
if path_auth_perm in settings.RBAC_ROLE_MENU_EXCLUDE:
return
# 已分配菜单权限校验
allow_perms = []
# 菜单去重
unique_menus = {}
for role in user_roles:
for menu in role.menus:
if menu.perms and menu.status == StatusType.enable:
allow_perms.extend(menu.perms.split(','))
unique_menus[menu.id] = menu
# 已分配菜单权限校验
allow_perms = []
for menu in list(unique_menus.values()):
if menu.perms and menu.status == StatusType.enable:
allow_perms.extend(menu.perms.split(','))
if path_auth_perm not in allow_perms:
raise AuthorizationError
else:
+1 -1
View File
@@ -9,6 +9,6 @@ from backend.plugin.code_generator.api.v1.gen import router as gen_router
v1 = APIRouter(prefix=f'{settings.FASTAPI_API_V1_PATH}/gen', tags=['代码生成'])
v1.include_router(gen_router)
v1.include_router(gen_router, prefix='/tables')
v1.include_router(business_router, prefix='/businesses')
v1.include_router(model_router, prefix='/models')
+5 -5
View File
@@ -16,7 +16,7 @@ from backend.plugin.code_generator.service.gen_service import gen_service
router = APIRouter()
@router.get('/tables', summary='获取数据库表')
@router.get('', summary='获取数据库表')
async def get_all_tables(
table_schema: Annotated[str, Query(description='数据库名')] = 'fba',
) -> ResponseSchemaModel[list[str]]:
@@ -37,20 +37,20 @@ async def import_table(obj: ImportParam) -> ResponseModel:
return response_base.success()
@router.get('/preview/{pk}', summary='生成代码预览', dependencies=[DependsJwtAuth])
@router.get('/{pk}/preview', summary='生成代码预览', dependencies=[DependsJwtAuth])
async def preview_code(pk: Annotated[int, Path(description='业务 ID')]) -> ResponseSchemaModel[dict[str, bytes]]:
data = await gen_service.preview(pk=pk)
return response_base.success(data=data)
@router.get('/generate/{pk}/path', summary='获取代码生成路径', dependencies=[DependsJwtAuth])
@router.get('/{pk}/code/path', summary='获取代码生成路径', dependencies=[DependsJwtAuth])
async def generate_path(pk: Annotated[int, Path(description='业务 ID')]) -> ResponseSchemaModel[list[str]]:
data = await gen_service.get_generate_path(pk=pk)
return response_base.success(data=data)
@router.post(
'/generate/{pk}',
'/{pk}/code',
summary='代码生成',
description='文件磁盘写入,请谨慎操作',
dependencies=[
@@ -63,7 +63,7 @@ async def generate_code(pk: Annotated[int, Path(description='业务 ID')]) -> Re
return response_base.success()
@router.get('/download/{pk}', summary='下载代码', dependencies=[DependsJwtAuth])
@router.get('/{pk}', summary='下载代码', dependencies=[DependsJwtAuth])
async def download_code(pk: Annotated[int, Path(description='业务 ID')]):
bio = await gen_service.download(pk=pk)
return StreamingResponse(
@@ -175,8 +175,9 @@ class GenService:
code_folder.mkdir(parents=True, exist_ok=True)
init_filepath = code_folder.joinpath('__init__.py')
async with aiofiles.open(init_filepath, 'w', encoding='utf-8') as f:
await f.write(gen_template.init_content)
if not os.path.exists(init_filepath):
async with aiofiles.open(init_filepath, 'w', encoding='utf-8') as f:
await f.write(gen_template.init_content)
# api __init__.py
if 'api' in str_code_filepath:
+7 -6
View File
@@ -288,13 +288,14 @@ create index ix_sys_opera_log_id
create table sys_role
(
id int auto_increment comment '主键 ID'
id int auto_increment comment '主键 ID'
primary key,
name varchar(20) not null comment '角色名称',
status int not null comment '角色状态(0停用 1正常)',
remark longtext null comment '备注',
created_time datetime not null comment '创建时间',
updated_time datetime null comment '更新时间',
name varchar(20) not null comment '角色名称',
status int not null comment '角色状态(0停用 1正常)',
is_filter_scopes tinyint(1) not null comment '过滤数据权限(0否 1是)',
remark longtext null comment '备注',
created_time datetime not null comment '创建时间',
updated_time datetime null comment '更新时间',
constraint name
unique (name)
)
+12 -11
View File
@@ -2,36 +2,37 @@ insert into sys_dept (id, name, sort, leader, phone, email, status, del_flag, pa
values (1, 'test', 0, null, null, null, 1, 0, null, '2023-06-26 17:13:45', null);
insert into fba.sys_menu (id, title, name, path, sort, icon, type, component, perms, status, display, cache, link, remark, parent_id, created_time, updated_time)
values (1, '测试', 'Test', 'test', 0, null, 0, null, null, 0, 0, 1, null, null, null, '2023-07-27 19:14:10', null),
(2, '仪表盘', 'Dashboard', 'dashboard', 0, 'material-symbols:dashboard', 0, null, null, 1, 1, 1, null, null, null, '2023-07-27 19:15:45', null),
values (1, '测试', 'Test', 'test', 0, null, 0, null, null, 0, 0, 0, null, null, null, '2023-07-27 19:14:10', null),
(2, '仪表盘', 'Dashboard', 'dashboard', 0, 'material-symbols:dashboard', 0, null, null, 1, 1, 0, null, null, null, '2023-07-27 19:15:45', null),
(3, '工作台', 'Workspace', 'workspace', 0, null, 1, '/dashboard/workspace/index.vue', null, 1, 1, 1, null, null, 2, '2023-07-27 19:17:59', null),
(4, '数据分析', 'Analytics', 'analytics', 0, null, 1, '/dashboard/analytics/index.vue', null, 1, 1, 1, null, null, 2, '2023-07-27 19:17:59', null),
(5, '系统管理', 'System', 'system', 0, 'eos-icons:admin', 0, null, null, 1, 1, 1, null, null, null, '2023-07-27 19:23:00', null),
(5, '系统管理', 'System', 'system', 0, 'eos-icons:admin', 0, null, null, 1, 1, 0, null, null, null, '2023-07-27 19:23:00', null),
(6, '部门管理', 'SysDept', 'sys-dept', 0, null, 1, '/system/dept/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:23:42', null),
(7, '用户管理', 'SysUser', 'sys-user', 0, null, 1, '/system/user/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:25:13', null),
(8, '角色管理', 'SysRole', 'sys-role', 0, null, 1, '/system/role/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:25:45', null),
(9, '菜单管理', 'SysMenu', 'sys-menu', 0, null, 1, '/system/menu/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:45:29', null),
(10, '插件管理', 'SysPlugin', 'sys-plugin', 0, null, 1, '/system/plugin/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:24:12', null),
(11, '数据权限', 'SysDataPermission', 'sys-data-permission', 0, null, 1, '/system/data-permission/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:24:12', null),
(12, '系统自动化', 'Automation', 'automation', 0, 'material-symbols:automation', 0, null, null, 1, 1, 1, null, null, null, '2024-07-27 02:06:20', null),
(12, '系统自动化', 'Automation', 'automation', 0, 'material-symbols:automation', 0, null, null, 1, 1, 0, null, null, null, '2024-07-27 02:06:20', null),
(13, '代码生成', 'CodeGenerator', 'code-generator', 0, null, 1, '/automation/code-generator/index.vue', null, 1, 1, 1, null, null, 12, '2024-07-27 12:24:54', null),
(14, '系统监控', 'Monitor', 'monitor', 0, 'mdi:monitor-eye', 0, null, null, 1, 1, 1, null, null, null, '2023-07-27 19:27:08', null),
(14, '系统监控', 'Monitor', 'monitor', 0, 'mdi:monitor-eye', 0, null, null, 1, 1, 0, null, null, null, '2023-07-27 19:27:08', null),
(15, 'Redis 监控', 'Redis', 'redis', 0, null, 1, '/monitor/redis/index.vue', null, 1, 1, 1, null, null, 14, '2023-07-27 19:28:03', null),
(16, '服务器监控', 'Server', 'server', 0, null, 1, '/monitor/server/index.vue', null, 1, 1, 1, null, null, 14, '2023-07-27 19:28:29', null),
(17, '日志', 'Log', 'log', 0, 'carbon:cloud-logging', 0, null, null, 1, 1, 1, null, null, null, '2023-07-27 19:19:59', null),
(17, '日志', 'Log', 'log', 0, 'carbon:cloud-logging', 0, null, null, 1, 1, 0, null, null, null, '2023-07-27 19:19:59', null),
(18, '登录日志', 'Login', 'login', 0, null, 1, '/log/login/index.vue', null, 1, 1, 1, null, null, 17, '2023-07-27 19:20:56', null),
(19, '操作日志', 'Opera', 'opera', 0, null, 1, '/log/opera/index.vue', null, 1, 1, 1, null, null, 17, '2023-07-27 19:21:28', null),
(20, '官网', 'Site', '', 998, 'dashicons:admin-site', 1, null, null, 1, 1, 1, 'https://fastapi-practices.github.io/fastapi_best_architecture_docs/', null, null, '2023-07-27 19:22:24', null),
(21, '赞助', 'Sponsor', '', 999, 'material-icon-theme:github-sponsors', 1, null, null, 1, 1, 1, 'https://wu-clan.github.io/sponsor/', null, null, '2024-07-27 12:39:57', null);
(20, 'Apifox', 'Apifox', 'apifox', 997, 'simple-icons:apifox', 3, null, null, 1, 1, 0, 'https://apifox.com/apidoc/shared-28a93f02-730b-4f33-bb5e-4dad92058cc0', null, null, '2024-05-22 16:27:00', null),
(21, '官网', 'Site', '', 998, 'dashicons:admin-site', 4, null, null, 1, 1, 0, 'https://fastapi-practices.github.io/fastapi_best_architecture_docs/', null, null, '2024-07-27 19:22:24', null),
(22, '赞助', 'Sponsor', '', 999, 'material-icon-theme:github-sponsors', 4, null, null, 1, 1, 0, 'https://wu-clan.github.io/sponsor/', null, null, '2024-07-27 12:39:57', null);
insert into sys_role (id, name, status, remark, created_time, updated_time)
values (1, 'test', 1, null, '2023-06-26 17:13:45', null);
insert into sys_role (id, name, status, is_filter_scopes, remark, created_time, updated_time)
values (1, 'test', 1, 1, null, '2023-06-26 17:13:45', null);
insert into sys_role_menu (id, role_id, menu_id)
values (1, 1, 1);
insert into sys_user (id, uuid, username, nickname, password, salt, email, is_superuser, is_staff, status, is_multi_login, avatar, phone, join_time, last_login_time, dept_id, created_time, updated_time)
values (1, 'af4c804f-3966-4949-ace2-3bb7416ea926', 'admin', '用户88888', '$2b$12$8y2eNucX19VjmZ3tYhBLcOsBwy9w1IjBQE4SSqwMDL5bGQVp2wqS.', 0x24326224313224387932654E7563583139566A6D5A33745968424C634F, 'admin@example.com', 1, 1, 1, 0, null, null, '2023-06-26 17:13:45', '2024-11-18 13:53:57', 1, '2023-06-26 17:13:45', '2024-11-18 13:53:57');
values (1, 'af4c804f-3966-4949-ace2-3bb7416ea926', 'admin', '用户88888', '$2b$12$8y2eNucX19VjmZ3tYhBLcOsBwy9w1IjBQE4SSqwMDL5bGQVp2wqS.', 0x24326224313224387932654E7563583139566A6D5A33745968424C634F, 'admin@example.com', 1, 1, 1, 1, null, null, '2023-06-26 17:13:45', '2024-11-18 13:53:57', 1, '2023-06-26 17:13:45', '2024-11-18 13:53:57');
insert into sys_user_role (id, user_id, role_id)
values (1, 1, 1);
+9 -6
View File
@@ -268,14 +268,15 @@ create index ix_sys_opera_log_id
create table sys_role
(
id serial
id serial
primary key,
name varchar(20) not null
name varchar(20) not null
unique,
status integer not null,
remark text,
created_time timestamp with time zone not null,
updated_time timestamp with time zone
status integer not null,
is_filter_scopes integer not null,
remark text,
created_time timestamp with time zone not null,
updated_time timestamp with time zone
);
comment on table sys_role is '角色表';
@@ -286,6 +287,8 @@ comment on column sys_role.name is '角色名称';
comment on column sys_role.status is '角色状态(0停用 1正常)';
comment on column sys_role.is_filter_scopes is '过滤数据权限(0否 1是)';
comment on column sys_role.remark is '备注';
comment on column sys_role.created_time is '创建时间';
+20 -11
View File
@@ -2,36 +2,45 @@ insert into sys_dept (id, name, sort, leader, phone, email, status, del_flag, pa
values (1, 'test', 0, null, null, null, 1, 0, null, '2023-06-26 17:13:45', null);
insert into fba.sys_menu (id, title, name, path, sort, icon, type, component, perms, status, display, cache, link, remark, parent_id, created_time, updated_time)
values (1, '测试', 'Test', 'test', 0, null, 0, null, null, 0, 0, 1, null, null, null, '2023-07-27 19:14:10', null),
(2, '仪表盘', 'Dashboard', 'dashboard', 0, 'material-symbols:dashboard', 0, null, null, 1, 1, 1, null, null, null, '2023-07-27 19:15:45', null),
values (1, '测试', 'Test', 'test', 0, null, 0, null, null, 0, 0, 0, null, null, null, '2023-07-27 19:14:10', null),
(2, '仪表盘', 'Dashboard', 'dashboard', 0, 'material-symbols:dashboard', 0, null, null, 1, 1, 0, null, null, null, '2023-07-27 19:15:45', null),
(3, '工作台', 'Workspace', 'workspace', 0, null, 1, '/dashboard/workspace/index.vue', null, 1, 1, 1, null, null, 2, '2023-07-27 19:17:59', null),
(4, '数据分析', 'Analytics', 'analytics', 0, null, 1, '/dashboard/analytics/index.vue', null, 1, 1, 1, null, null, 2, '2023-07-27 19:17:59', null),
(5, '系统管理', 'System', 'system', 0, 'eos-icons:admin', 0, null, null, 1, 1, 1, null, null, null, '2023-07-27 19:23:00', null),
(5, '系统管理', 'System', 'system', 0, 'eos-icons:admin', 0, null, null, 1, 1, 0, null, null, null, '2023-07-27 19:23:00', null),
(6, '部门管理', 'SysDept', 'sys-dept', 0, null, 1, '/system/dept/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:23:42', null),
(7, '用户管理', 'SysUser', 'sys-user', 0, null, 1, '/system/user/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:25:13', null),
(8, '角色管理', 'SysRole', 'sys-role', 0, null, 1, '/system/role/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:25:45', null),
(9, '菜单管理', 'SysMenu', 'sys-menu', 0, null, 1, '/system/menu/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:45:29', null),
(10, '插件管理', 'SysPlugin', 'sys-plugin', 0, null, 1, '/system/plugin/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:24:12', null),
(11, '数据权限', 'SysDataPermission', 'sys-data-permission', 0, null, 1, '/system/data-permission/index.vue', null, 1, 1, 1, null, null, 5, '2023-07-27 19:24:12', null),
(12, '系统自动化', 'Automation', 'automation', 0, 'material-symbols:automation', 0, null, null, 1, 1, 1, null, null, null, '2024-07-27 02:06:20', null),
(12, '系统自动化', 'Automation', 'automation', 0, 'material-symbols:automation', 0, null, null, 1, 1, 0, null, null, null, '2024-07-27 02:06:20', null),
(13, '代码生成', 'CodeGenerator', 'code-generator', 0, null, 1, '/automation/code-generator/index.vue', null, 1, 1, 1, null, null, 12, '2024-07-27 12:24:54', null),
(14, '系统监控', 'Monitor', 'monitor', 0, 'mdi:monitor-eye', 0, null, null, 1, 1, 1, null, null, null, '2023-07-27 19:27:08', null),
(14, '系统监控', 'Monitor', 'monitor', 0, 'mdi:monitor-eye', 0, null, null, 1, 1, 0, null, null, null, '2023-07-27 19:27:08', null),
(15, 'Redis 监控', 'Redis', 'redis', 0, null, 1, '/monitor/redis/index.vue', null, 1, 1, 1, null, null, 14, '2023-07-27 19:28:03', null),
(16, '服务器监控', 'Server', 'server', 0, null, 1, '/monitor/server/index.vue', null, 1, 1, 1, null, null, 14, '2023-07-27 19:28:29', null),
(17, '日志', 'Log', 'log', 0, 'carbon:cloud-logging', 0, null, null, 1, 1, 1, null, null, null, '2023-07-27 19:19:59', null),
(17, '日志', 'Log', 'log', 0, 'carbon:cloud-logging', 0, null, null, 1, 1, 0, null, null, null, '2023-07-27 19:19:59', null),
(18, '登录日志', 'Login', 'login', 0, null, 1, '/log/login/index.vue', null, 1, 1, 1, null, null, 17, '2023-07-27 19:20:56', null),
(19, '操作日志', 'Opera', 'opera', 0, null, 1, '/log/opera/index.vue', null, 1, 1, 1, null, null, 17, '2023-07-27 19:21:28', null),
(20, '官网', 'Site', '', 998, 'dashicons:admin-site', 1, null, null, 1, 1, 1, 'https://fastapi-practices.github.io/fastapi_best_architecture_docs/', null, null, '2023-07-27 19:22:24', null),
(21, '赞助', 'Sponsor', '', 999, 'material-icon-theme:github-sponsors', 1, null, null, 1, 1, 1, 'https://wu-clan.github.io/sponsor/', null, null, '2024-07-27 12:39:57', null);
(20, 'Apifox', 'Apifox', 'apifox', 997, 'simple-icons:apifox', 3, null, null, 1, 1, 0, 'https://apifox.com/apidoc/shared-28a93f02-730b-4f33-bb5e-4dad92058cc0', null, null, '2024-05-22 16:27:00', null),
(21, '官网', 'Site', '', 998, 'dashicons:admin-site', 4, null, null, 1, 1, 0, 'https://fastapi-practices.github.io/fastapi_best_architecture_docs/', null, null, '2024-07-27 19:22:24', null),
(22, '赞助', 'Sponsor', '', 999, 'material-icon-theme:github-sponsors', 4, null, null, 1, 1, 0, 'https://wu-clan.github.io/sponsor/', null, null, '2024-07-27 12:39:57', null);
insert into sys_role (id, name, status, remark, created_time, updated_time)
values (1, 'test', 1, null, '2023-06-26 17:13:45', null);
insert into sys_role (id, name, status, is_filter_scopes, remark, created_time, updated_time)
values (1, 'test', 1, 1, null, '2023-06-26 17:13:45', null);
insert into sys_role_menu (id, role_id, menu_id)
values (1, 1, 1);
insert into sys_user (id, uuid, username, nickname, password, salt, email, is_superuser, is_staff, status, is_multi_login, avatar, phone, join_time, last_login_time, dept_id, created_time, updated_time)
values (1, 'af4c804f-3966-4949-ace2-3bb7416ea926', 'admin', '用户88888', '$2b$12$8y2eNucX19VjmZ3tYhBLcOsBwy9w1IjBQE4SSqwMDL5bGQVp2wqS.', '0x24326224313224387932654E7563583139566A6D5A33745968424C634F', 'admin@example.com', 1, 1, 1, 0, null, null, '2023-06-26 17:13:45', '2024-11-18 13:53:57', 1, '2023-06-26 17:13:45', '2024-11-18 13:53:57');
values (1, 'af4c804f-3966-4949-ace2-3bb7416ea926', 'admin', '用户88888', '$2b$12$8y2eNucX19VjmZ3tYhBLcOsBwy9w1IjBQE4SSqwMDL5bGQVp2wqS.', '0x24326224313224387932654E7563583139566A6D5A33745968424C634F', 'admin@example.com', 1, 1, 1, 1, null, null, '2023-06-26 17:13:45', '2024-11-18 13:53:57', 1, '2023-06-26 17:13:45', '2024-11-18 13:53:57');
insert into sys_user_role (id, user_id, role_id)
values (1, 1, 1);
-- Reset auto-increment values for each table based on max id
SELECT setval(pg_get_serial_sequence('sys_dept', 'id'),COALESCE(MAX(id), 0) + 1, true) FROM sys_dept;
SELECT setval(pg_get_serial_sequence('sys_menu', 'id'),COALESCE(MAX(id), 0) + 1, true) FROM sys_menu;
SELECT setval(pg_get_serial_sequence('sys_role', 'id'),COALESCE(MAX(id), 0) + 1, true) FROM sys_role;
SELECT setval(pg_get_serial_sequence('sys_role_menu', 'id'),COALESCE(MAX(id), 0) + 1, true) FROM sys_role_menu;
SELECT setval(pg_get_serial_sequence('sys_user', 'id'),COALESCE(MAX(id), 0) + 1, true) FROM sys_user;
SELECT setval(pg_get_serial_sequence('sys_user_role', 'id'),COALESCE(MAX(id), 0) + 1, true) FROM sys_user_role;
-92
View File
@@ -1,92 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.IO Task Notifications</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
#notifications {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
max-height: 300px;
overflow-y: auto;
}
.notification {
padding: 10px;
margin-bottom: 10px;
background-color: #f9f9f9;
border: 1px solid #ddd;
border-radius: 4px;
}
.notification.new {
background-color: #d3f9d8;
}
</style>
</head>
<body>
<h1>Task Notifications</h1>
<p>Waiting for task notifications...</p>
<div id="notifications"></div>
<!-- Load Socket.IO client -->
<script src="https://cdn.socket.io/4.5.1/socket.io.min.js"></script>
<script>
// Establish a connection to the server
const socket = io('http://127.0.0.1:8000', {
autoConnect: true,
path: '/ws/socket.io',
reconnection: true,
reconnectionAttempts: 3,
reconnectionDelay: 1000,
transports: ['websocket'],
auth: {
session_uuid: 'da985430-43b3-4860-a20a-97cc8e8e0b76',
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXNzaW9uX3V1aWQiOiJkYTk4NTQzMC00M2IzLTQ4NjAtYTIwYS05N2NjOGU4ZTBiNzYiLCJleHAiOjE3Mzc2MzQwODUsInN1YiI6IjEifQ.QeXNtXhHG4cm5GRzOtv2wqZXi6HdqACmW_UjC4JLPsk'
}
});
// Handle 'task_notification' event
socket.on('task_notification', (data) => {
// Get the notifications container
const notificationsContainer = document.getElementById('notifications');
// Create a new div for the notification
const notificationDiv = document.createElement('div');
notificationDiv.classList.add('notification', 'new');
notificationDiv.innerHTML = `
<strong>Task Notification:</strong>
<p>${data.msg}</p>
<small>Received at: ${new Date().toLocaleTimeString()}</small>
`;
// Append the new notification to the container
notificationsContainer.appendChild(notificationDiv);
// Scroll to the bottom to show the latest notification
notificationsContainer.scrollTop = notificationsContainer.scrollHeight;
});
// Handle connection errors
socket.on('connect_error', (error) => {
console.error('Connection error:', error);
alert('Unable to connect to the server. Please check your connection.');
});
socket.on('connect', () => {
console.log('Connected to server');
});
socket.on('disconnect', () => {
console.log('Disconnected from server');
});
</script>
</body>
</html>
+4 -4
View File
@@ -93,16 +93,16 @@ def get_vben5_tree_data(row: Sequence[RowData]) -> list[dict[str, Any]]:
:param row: 原始数据行序列
:return:
"""
# 需要移除的原始字段
remove_keys = {'title', 'icon', 'link', 'cache', 'display', 'status'}
meta_keys = {'title', 'icon', 'link', 'cache', 'display', 'status'}
vben5_nodes = [
{
**{k: v for k, v in node.items() if k not in remove_keys},
**{k: v for k, v in node.items() if k not in meta_keys},
'meta': {
'title': node['title'],
'icon': node['icon'],
'link': node['link'],
'iframeSrc': node['link'] if node['type'] == 3 else '',
'link': node['link'] if node['type'] == 4 else '',
'keepAlive': node['cache'],
'hideInMenu': not bool(node['display']),
'menuVisibleWithForbidden': not bool(node['status']),
+1 -1
View File
@@ -164,7 +164,7 @@ class ServerInfo:
'mem_vms': ServerInfo.format_bytes(mem_info.vms),
'mem_rss': ServerInfo.format_bytes(mem_info.rss),
'mem_free': ServerInfo.format_bytes(mem_info.vms - mem_info.rss),
'startup': start_time,
'startup': timezone.t_str(start_time),
'elapsed': elapsed,
}