mirror of
https://github.com/jeecgboot/JeecgBoot.git
synced 2025-12-08 17:12:28 +08:00
Compare commits
97 Commits
springboot
...
v3.8.0last
| Author | SHA1 | Date | |
|---|---|---|---|
| 64b3c9e42e | |||
| 8eb81493ce | |||
| 044fc47586 | |||
| bbe18c582c | |||
| b894125b53 | |||
| 2e236703b2 | |||
| a771d24a57 | |||
| 69f5d12de7 | |||
| 5b5999e786 | |||
| fc3fe39d95 | |||
| 48e23aafab | |||
| 657b84d3cf | |||
| 2021bf39f8 | |||
| fdeb37c3d0 | |||
| f9123208e1 | |||
| accb8f2f9f | |||
| c643994546 | |||
| 6934a0adee | |||
| 93e32a7177 | |||
| c9f5bb4409 | |||
| 10b68858d6 | |||
| da72e8f9c5 | |||
| 73e86686dc | |||
| f43d0d486b | |||
| 65bde3331b | |||
| b60942aa86 | |||
| 197b267e71 | |||
| 79f7134bd5 | |||
| 6d432bc186 | |||
| 415307eb9f | |||
| 48e20b2af5 | |||
| b7924b9ca8 | |||
| a10a2e0a9d | |||
| 4aa88189ed | |||
| fdb05443c2 | |||
| 65d737db6d | |||
| f04f7f9abf | |||
| 935e118d15 | |||
| e218367332 | |||
| 3a3f3cf367 | |||
| 0e762b4157 | |||
| f4712baa39 | |||
| 7d8b653d6e | |||
| cf7f3f94be | |||
| 49f63b92ac | |||
| 5670a15b20 | |||
| 9e9ef20b7c | |||
| 0c034031d1 | |||
| 491a038b5a | |||
| 8a4fcb0023 | |||
| e93dcc1a7e | |||
| 383cbf250f | |||
| 9fe1450ac9 | |||
| 88b9b12998 | |||
| 9e25566271 | |||
| 8e54e06978 | |||
| e5c082ae13 | |||
| 96ab98ac3e | |||
| 1632c241ee | |||
| e9d05b0e75 | |||
| 6ade7e22f8 | |||
| 43d47c08cb | |||
| e616c5d8fe | |||
| cddf23c787 | |||
| 70a37309dd | |||
| 48555b5219 | |||
| 06d58f202f | |||
| 628870af9b | |||
| b46a6438e6 | |||
| 5488f99723 | |||
| 6bc1fe8d21 | |||
| 7cac16320c | |||
| 24dbd1db39 | |||
| 46b026b989 | |||
| 94c45f5e0f | |||
| 8950e19d4e | |||
| 99eb88f71c | |||
| 824d7839d8 | |||
| c88f9d95d4 | |||
| beb0bc2f64 | |||
| f741db874c | |||
| d684c09392 | |||
| 364be22dd0 | |||
| 20efa3bf9a | |||
| c7977dda3d | |||
| c27c5a9a9b | |||
| 0ab280f812 | |||
| c3066dac17 | |||
| b650d512b3 | |||
| 925ec9447d | |||
| 411a73c1bf | |||
| 84077e6e24 | |||
| 184cf97304 | |||
| 5f425b49b2 | |||
| 3ac8ee304a | |||
| 0faac01bb7 | |||
| 74d88a8fcc |
3
.github/ISSUE_TEMPLATE/bug_report.md
vendored
3
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@ -10,9 +10,6 @@ assignees: getActivity
|
||||
##### 版本号:
|
||||
|
||||
|
||||
##### 分支:
|
||||
|
||||
|
||||
##### 问题描述:
|
||||
|
||||
|
||||
|
||||
4
.github/ISSUE_TEMPLATE/feature_request.md
vendored
4
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@ -6,12 +6,10 @@ assignees: getActivity
|
||||
|
||||
---
|
||||
|
||||
|
||||
##### 版本号:
|
||||
|
||||
|
||||
##### 分支:
|
||||
|
||||
|
||||
##### 问题描述:
|
||||
|
||||
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@ -13,5 +13,4 @@ os_del.cmd
|
||||
os_del_doc.cmd
|
||||
.svn
|
||||
derby.log
|
||||
.cursor
|
||||
.history
|
||||
*.log
|
||||
21
README-AI.md
21
README-AI.md
@ -16,19 +16,6 @@ JeecgBoot平台的AIGC功能模块,是一套类似`Dify`的`AIGC应用开发
|
||||
[](https://www.bilibili.com/video/BV1zmd7YFE4w)
|
||||
|
||||
|
||||
##### 功能大模块
|
||||
|
||||
- AI应用开发平台
|
||||
- AI知识库系统
|
||||
- AI大模型管理
|
||||
- AI流程编排
|
||||
- AI对话支持图片
|
||||
- AI对话助手(智能问答)
|
||||
- AI建表(Online表单)
|
||||
- AI写文章(CMS)
|
||||
- AI表单字段建议(表单设计器)
|
||||
|
||||
|
||||
|
||||
#### Dify `VS` JEECG AI
|
||||
|
||||
@ -57,10 +44,10 @@ JeecgBoot平台的AIGC功能模块,是一套类似`Dify`的`AIGC应用开发
|
||||
|
||||
|
||||
|
||||
### 技术文档
|
||||
### 安装向量库 pgvector
|
||||
|
||||
- https://help.jeecg.com/aigc/config
|
||||
|
||||
- [AIGC开发文档](https://help.jeecg.com/aigc)
|
||||
- [安装向量库 pgvector](https://help.jeecg.com/aigc/config)
|
||||
|
||||
|
||||
|
||||
@ -86,7 +73,7 @@ JeecgBoot平台的AIGC功能模块,是一套类似`Dify`的`AIGC应用开发
|
||||
## 技术交流
|
||||
|
||||
- 开发文档:https://help.jeecg.com/aigc
|
||||
- QQ群:964611995、716488839(满)
|
||||
- QQ群:716488839
|
||||
|
||||
|
||||
## 功能列表
|
||||
|
||||
14
README-EN.md
14
README-EN.md
@ -7,12 +7,12 @@
|
||||
JEECG BOOT AI Low Code Platform
|
||||
===============
|
||||
|
||||
Current version: 3.8.3 (Release date: 2025-10-09)
|
||||
Current version: 3.8.0 (Release date: 2025-04-18)
|
||||
|
||||
|
||||
[](https://github.com/zhangdaiscott/jeecg-boot/blob/master/LICENSE)
|
||||
[](http://www.jeecg.com)
|
||||
[](https://github.com/zhangdaiscott/jeecg-boot)
|
||||
[](https://github.com/zhangdaiscott/jeecg-boot)
|
||||
[](https://github.com/zhangdaiscott/jeecg-boot)
|
||||
[](https://github.com/zhangdaiscott/jeecg-boot)
|
||||
|
||||
@ -69,13 +69,9 @@ Jeecg-Boot AI low code platform can be applied in the development of any J2EE pr
|
||||
Starts the project
|
||||
-----------------------------------
|
||||
|
||||
> Default account password: admin/123456
|
||||
- [IDEA Quick start](https://help.jeecg.com/java/setup/idea/startup)
|
||||
- [Docker Quick start](https://help.jeecg.com/java/docker/quick)
|
||||
|
||||
- [Development Environment setup](https://help.jeecg.com/java/setup/tools)
|
||||
- [IDEA Quick start(single model)](https://help.jeecg.com/java/setup/idea/startup)
|
||||
- [Docker Quick start(single model)](https://help.jeecg.com/java/docker/quick)
|
||||
- [IDEA Quick start(microservices model)](https://help.jeecg.com/java/springcloud/switchcloud/monomer)
|
||||
- [Docker Quick start(microservices model)](https://help.jeecg.com/java/docker/quickcloud)
|
||||
|
||||
|
||||
Technical documentation
|
||||
@ -85,7 +81,7 @@ Technical documentation
|
||||
- Demo : [OnlineDemo](http://boot3.jeecg.com) | [APP](http://jeecg.com/appIndex)
|
||||
- Doc: [DocumentCenter](http://help.jeecg.com) | [AI Config](https://help.jeecg.com/java/ai/aichat)
|
||||
- Newbie guide: [Quick start](http://www.jeecg.com/doc/quickstart) | [Q&A ](http://www.jeecg.com/doc/qa) | [1 minute experience](https://my.oschina.net/jeecg/blog/3083313)
|
||||
- QQ group : 964611995、⑩716488839(满)、⑨808791225(满)
|
||||
- QQ group : ⑩716488839、⑨808791225
|
||||
|
||||
|
||||
|
||||
|
||||
@ -1,124 +0,0 @@
|
||||
|
||||
JeecgBoot低代码平台(商业版介绍)
|
||||
===============
|
||||
|
||||
|
||||
|
||||
项目介绍
|
||||
-----------------------------------
|
||||
|
||||
<h3 align="center">企业级AI低代码平台</h3>
|
||||
|
||||
|
||||
JeecgBoot是一款集成AI应用的,基于BPM流程的低代码平台,旨在帮助企业快速实现低代码开发和构建个性化AI应用!前后端分离架构Ant Design&Vue3,SpringBoot,SpringCloud Alibaba,Mybatis-plus,Shiro。强大的代码生成器让前后端代码一键生成,无需写任何代码! 引领AI低代码开发模式: AI生成->OnlineCoding-> 代码生成-> 手工MERGE, 帮助Java项目解决80%的重复工作,让开发更多关注业务,提高效率、节省成本,同时又不失灵活性!低代码能力:Online表单、表单设计、流程设计、Online报表、大屏/仪表盘设计、报表设计; AI应用平台功能:AI知识库问答、AI模型管理、AI流程编排、AI聊天等,支持含ChatGPT、DeepSeek、Ollama等多种AI大模型
|
||||
|
||||
JeecgBoot 提供了一系列 `低代码能力`,实现`真正的零代码`在线开发:Online表单开发、Online报表、复杂报表设计、打印设计、在线图表设计、仪表盘设计、大屏设计、移动图表能力、表单设计器、在线设计流程、流程自动化配置、插件能力(可插拔)
|
||||
|
||||
`AI赋能低代码:` 目前提供了AI应用、AI模型管理、AI流程编排、AI对话助手,AI建表、AI写文章、AI知识库问答、AI字段建议等功能;支持各种AI大模型ChatGPT、DeepSeek、Ollama、智普、千问等.
|
||||
|
||||
`JEECG宗旨是:` 简单功能由OnlineCoding配置实现,做到`零代码开发`;复杂功能由代码生成器生成进行手工Merge 实现`低代码开发`,既保证了`智能`又兼顾`灵活`;实现了低代码开发的同时又支持灵活编码,解决了当前低代码产品普遍不灵活的弊端!
|
||||
|
||||
`JEECG业务流程:` 采用工作流来实现、扩展出任务接口,供开发编写业务逻辑,表单提供多种解决方案: 表单设计器、online配置表单、编码表单。同时实现了流程与表单的分离设计(松耦合)、并支持任务节点灵活配置,既保证了公司流程的保密性,又减少了开发人员的工作量。
|
||||
|
||||
|
||||
|
||||
#### JeecgBoot商业版与同类产品区别
|
||||
-----------------------------------
|
||||
|
||||
- 灵活性:jeecgboot基于开源技术栈,设计初考虑到可插拔性和集成灵活性,确保平台的智能性与灵活性,避免因平台过于庞大而导致的扩展困难。
|
||||
- 流程管理:支持一个表单挂接多个流程,同时一个流程可以连接多个表单,增强了流程的灵活性和复杂性管理。
|
||||
- 符合中国国情的流程:针对中国市场的特定需求,jeecgboot能够实现各种符合中国国情的业务流程。
|
||||
- 强大的表单设计器:jeecgboot的表单设计器与敲敲云共享,具备高质量和智能化的特点,能够满足零代码应用的需求,业内同类产品中不多见。
|
||||
- 报表功能:自主研发的报表工具,拥有独立知识产权,功能上比业内老牌产品如帆软更智能,操作简便。
|
||||
- BI产品整合:提供大屏、仪表盘、门户等功能,完美解决这些需求,并支持移动面板的设计与渲染。
|
||||
- 自主研发的模块:jeecgboot的所有模块均为自主研发,具有独立的知识产权。
|
||||
- 颗粒度和功能细致:在功能细致度和颗粒度上,jeecgboot远超同类产品,尤其在零代码能力方面表现突出。
|
||||
- 零代码应用管理:最新版支持与敲敲云的零代码应用管理能力的集成,使得jeecgboot既具备低代码,又具备零代码的应用能力,业内独一无二。
|
||||
- 强大的代码生成器:作为开源代码生成器的先锋,jeecgboot在代码生成的智能化和在线低代码与代码生成的结合方面,优势明显。
|
||||
- 精细化权限管理:提供行级和列级的数据权限控制,满足企业在ERP和OA领域对权限管理的严格需求。
|
||||
- 多平台支持的APP:目前采用uniapp3实现,支持小程序、H5、App及鸿蒙、鸿蒙Next、Electron桌面应用等多种终端。
|
||||
|
||||
> 综上所述,jeecgboot不仅在功能上具备丰富性和灵活性,还在技术架构、权限管理和用户体验等方面展现出明显的优势,是一个综合性能强大的低代码平台。
|
||||
|
||||
|
||||
|
||||
商业版演示
|
||||
-----------------------------------
|
||||
|
||||
JeecgBoot vs 敲敲云
|
||||
> - JeecgBoot是低代码产品拥有系列低代码能力,比如流程设计、表单设计、大屏设计,代码生成器,适合半开发模式(开发+低代码结合),也可以集成零代码应用管理模块.
|
||||
> - 敲敲云是零代码产品,完全不写代码,通过配置搭建业务系统,其在jeecgboot基础上研发而成,删除了online、代码生成、OA等需要编码功能,只保留应用管理功能和聊天、日程、文件三个OA组件.
|
||||
|
||||
|
||||
- JeecgBoot低代码: https://boot3.jeecg.com
|
||||
- 敲敲云零代码:https://app.qiaoqiaoyun.com
|
||||
- APP演示(多端): http://jeecg.com/appIndex
|
||||
|
||||
|
||||
### 流程视频介绍
|
||||
|
||||
[](https://www.bilibili.com/video/BV1Nk4y1o7Qc)
|
||||
|
||||
|
||||
|
||||
### 商业版功能简述
|
||||
|
||||
> 详细的功能介绍,[请联系官方](https://jeecg.com/vip)
|
||||
|
||||
```
|
||||
│─更多商业功能
|
||||
│ ├─流程设计器
|
||||
│ ├─简流设计器(类钉钉版)
|
||||
│ ├─门户设计(NEW)
|
||||
│ ├─表单设计器
|
||||
│ ├─大屏设计器
|
||||
│ └─我的任务
|
||||
│ └─历史流程
|
||||
│ └─历史流程
|
||||
│ └─流程实例管理
|
||||
│ └─流程监听管理
|
||||
│ └─流程表达式
|
||||
│ └─我发起的流程
|
||||
│ └─我的抄送
|
||||
│ └─流程委派、抄送、跳转
|
||||
│ └─OA办公组件
|
||||
│ └─零代码应用管理(无需编码,在线搭建应用系统)
|
||||
│ ├─积木报表企业版(含jimureport、jimubi)
|
||||
│ ├─AI流程设计器源码
|
||||
│ ├─Online全模块功能和源码
|
||||
│ ├─AI写文章(CMS)
|
||||
│ ├─AI表单字段建议(表单设计器)
|
||||
│ ├─OA办公协同组件
|
||||
│ ├─在线聊天功能
|
||||
│ ├─设计表单移动适配
|
||||
│ ├─设计表单支持外部填报
|
||||
│ ├─设计表单AI字段建议
|
||||
│ ├─设计表单视图功能(支持多种类型含日历、表格、看板、甘特图)
|
||||
│ └─。。。
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
##### 流程设计
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
##### 表单设计器
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
457
README.md
457
README.md
@ -2,13 +2,12 @@
|
||||
JeecgBoot AI低代码平台
|
||||
===============
|
||||
|
||||
当前最新版本: 3.8.3(发布日期:2025-10-09)
|
||||
当前最新版本: 3.8.0(发布日期:2025-04-18)
|
||||
|
||||
|
||||
[](https://github.com/jeecgboot/JeecgBoot/blob/master/LICENSE)
|
||||
[](https://jeecg.com)
|
||||
[](https://jeecg.blog.csdn.net)
|
||||
[](https://github.com/jeecgboot/JeecgBoot)
|
||||
[](http://guojusoft.com)
|
||||
[](https://github.com/jeecgboot/JeecgBoot)
|
||||
[](https://github.com/jeecgboot/JeecgBoot)
|
||||
[](https://github.com/jeecgboot/JeecgBoot)
|
||||
|
||||
@ -17,175 +16,177 @@ JeecgBoot AI低代码平台
|
||||
项目介绍
|
||||
-----------------------------------
|
||||
|
||||
<h3 align="center">企业级AI低代码平台</h3>
|
||||
<h3 align="center">Java AI Low Code Platform</h3>
|
||||
|
||||
JeecgBoot 是一款基于BPM流程和代码生成的AI低代码平台,助力企业快速实现低代码开发和构建AI应用。
|
||||
采用前后端分离架构(Ant Design&Vue3,SpringBoot3,SpringCloud Alibaba,Mybatis-plus),强大代码生成器实现前后端一键生成,无需手写代码。
|
||||
平台引领AI低代码开发模式:AI生成→在线编码→代码生成→手工合并,解决Java项目80%重复工作,提升效率,节省成本,兼顾灵活性。
|
||||
具备强大且颗粒化的权限控制,支持按钮权限和数据权限设置,满足大型业务系统需求。功能涵盖在线表单、表单设计、流程设计、门户设计、报表与大屏设计、OA办公、AI应用、AI知识库、大模型管理、AI流程编排、AI聊天,支持ChatGPT、DeepSeek、Ollama等多种AI大模型。
|
||||
JeecgBoot是一款基于AIGC和低代码引擎的AI低代码平台,旨在帮助开发者快速实现低代码开发和构建、部署个性化的 AI 应用。
|
||||
前后端分离架构Ant Design&Vue3,SpringBoot,SpringCloud Alibaba,Mybatis-plus,Shiro,强大的代码生成器让前后端代码一键生成,无需写任何代码!
|
||||
成套AI大模型功能: AI模型管理、AI应用、知识库、AI流程编排、AI对话助手等;
|
||||
引领AI低代码开发模式: AIGC生成->OnlineCoding-> 代码生成-> 手工MERGE, 帮助Java项目解决80%的重复工作,让开发更多关注业务,快速提高效率 节省成本,同时又不失灵活性!
|
||||
|
||||
`AI赋能报表:` 积木报表是一款自主研发的强大开源企业级Web报表与大屏工具。它通过零编码的拖拽式操作,赋能用户如同搭积木般轻松构建各类复杂报表和数据大屏,全面满足企业数据可视化与分析需求,助力企业级数据产品的高效打造与应用。
|
||||
|
||||
`AI赋能低代码:` 提供完善成熟的AI应用平台,涵盖AI应用管理、AI模型管理、智能对话助手、知识库问答、流程编排与设计器、AI建表等多项功能。平台兼容多种主流大模型,包括ChatGPT、DeepSeek、Ollama、智普、千问等,助力企业高效构建智能化应用,推动低代码开发与AI深度融合。
|
||||
JeecgBoot 提供了一系列 `低代码能力`,实现`真正的零代码`在线开发:Online表单开发、Online报表、复杂报表设计、打印设计、在线图表设计、仪表盘设计、大屏设计、移动图表能力、表单设计器、在线设计流程、流程自动化配置、插件能力(可插拔)
|
||||
|
||||
`JEECG宗旨是:` JEECG旨在通过OnlineCoding平台实现简单功能的零代码快速搭建,同时针对复杂功能采用代码生成器生成代码并手工合并,打造智能且灵活的低代码开发模式,有效解决了当前低代码产品普遍缺乏灵活性的问题,提升开发效率的同时兼顾系统的扩展性和定制化能力。
|
||||
`AI赋能低代码:` 目前提供了AI应用、AI模型管理、AI流程编排、AI对话助手,AI建表、AI写文章、AI知识库问答、AI字段建议等功能;支持各种AI大模型ChatGPT、DeepSeek、Ollama、智普、千问等.
|
||||
|
||||
`JEECG业务流程:` JEECG业务流程采用BPM工作流引擎实现业务审批,扩展任务接口供开发人员编写业务逻辑,表单提供表单设计器、在线配置表单和编码表单等多种解决方案。通过流程与表单的分离设计(松耦合)及任务节点的灵活配置,既保障了企业流程的安全性与保密性,又大幅降低了开发人员的工作量。
|
||||
`JEECG宗旨是:` 简单功能由OnlineCoding配置实现,做到`零代码开发`;复杂功能由代码生成器生成进行手工Merge 实现`低代码开发`,既保证了`智能`又兼顾`灵活`;实现了低代码开发的同时又支持灵活编码,解决了当前低代码产品普遍不灵活的弊端!
|
||||
|
||||
`JEECG业务流程:` 采用工作流来实现、扩展出任务接口,供开发编写业务逻辑,表单提供多种解决方案: 表单设计器、online配置表单、编码表单。同时实现了流程与表单的分离设计(松耦合)、并支持任务节点灵活配置,既保证了公司流程的保密性,又减少了开发人员的工作量。
|
||||
|
||||
|
||||
|
||||
### 视频介绍
|
||||
|
||||
[](https://www.bilibili.com/video/BV1Nk4y1o7Qc)
|
||||
|
||||
|
||||
适用项目
|
||||
-----------------------------------
|
||||
JeecgBoot低代码平台兼容所有J2EE项目开发,支持信创国产化,特别适用于SAAS、企业信息管理系统(MIS)、内部办公系统(OA)、企业资源计划系统(ERP)、客户关系管理系统(CRM)及AI知识库等场景。其半智能手工Merge开发模式,可显著提升70%以上的开发效率,极大降低开发成本。同时,JeecgBoot还是一款全栈式AI开发平台,助力企业快速构建和部署个性化AI应用。。
|
||||
JeecgBoot AI低代码平台,可以应用在任何J2EE项目的开发中,支持信创国产化。尤其适合SAAS项目、企业信息管理系统(MIS)、内部办公系统(OA)、企业资源计划系统(ERP)、客户关系管理系统(CRM)等,其半智能手工Merge的开发方式,可以显著提高开发效率70%以上,极大降低开发成本。
|
||||
又是一个全栈式 AI 开发平台,快速帮助企业构建和部署个性化的 AI 应用。
|
||||
|
||||
|
||||
**信创兼容说明**
|
||||
信创国产化
|
||||
-----------------------------------
|
||||
JeecgBoot 是一个开源低代码开发平台,支持全信创环境。它兼容多种国产操作系统和数据库,包括:
|
||||
|
||||
- 操作系统:国产麒麟、银河麒麟等国产系统几乎都是基于 Linux 内核,因此它们具有良好的兼容性。
|
||||
- 数据库:达梦、人大金仓、TiDB
|
||||
- 数据库:达梦、人大金仓、TiDB , [转库文档](https://my.oschina.net/jeecg/blog/4905722)
|
||||
- 中间件:东方通 TongWeb、TongRDS,宝兰德 AppServer、CacheDB, [信创配置文档](https://help.jeecg.com/java/tongweb-deploy/)
|
||||
|
||||
通过这些适配,JeecgBoot 为使用国产软件和硬件的用户提供了高效的开发解决方案。
|
||||
|
||||
版本说明
|
||||
|
||||
|
||||
项目说明
|
||||
-----------------------------------
|
||||
|
||||
|下载 | SpringBoot3.5 + Shiro |SpringBoot3.5+ SpringAuthorizationServer | SpringBoot3.5 + Sa-Token | SpringBoot2.7(JDK17/JDK8) |
|
||||
|------|----------------|----------------------------|-------------------|--------------------------------------------|
|
||||
| Github | [`springboot3`](https://github.com/jeecgboot/JeecgBoot/tree/springboot3) | [`springboot3_sas`](https://github.com/jeecgboot/JeecgBoot/tree/springboot3_sas) 分支 | [`springboot3-satoken`](https://github.com/jeecgboot/JeecgBoot/tree/springboot3-satoken) 分支|[`master`](https://github.com/jeecgboot/JeecgBoot) 分支|
|
||||
| Gitee | [`springboot3`](https://gitee.com/jeecg/JeecgBoot/tree/springboot3/) | [`springboot3_sas`](https://gitee.com/jeecg/JeecgBoot/tree/springboot3_sas) 分支| [`springboot3-satoken`](https://gitee.com/jeecg/JeecgBoot/tree/springboot3-satoken) 分支|[`master`](https://gitee.com/jeecg/JeecgBoot) 分支 |
|
||||
| 项目名 | 说明 |
|
||||
|--------------------|------------------------|
|
||||
| `jeecg-boot` | 后端源码JAVA(SpringBoot微服务架构) |
|
||||
| `jeecgboot-vue3` | 前端源码VUE3(vue3+vite6+ts最新技术栈) |
|
||||
| `JeecgUniapp` | [配套APP框架](https://github.com/jeecgboot/JeecgUniapp) 适配多个终端,支持APP、小程序、H5 |
|
||||
|
||||
|
||||
- `jeecg-boot` 是后端JAVA源码项目Springboot3+SpringCloudAlibaba(支持单体和微服务切换).
|
||||
- `jeecgboot-vue3` 是前端VUE3源码项目(vue3+vite6+ts最新技术栈).
|
||||
- `JeecgUniapp` 是[配套APP框架](https://github.com/jeecgboot/JeecgUniapp) 适配多个终端,支持APP、小程序、H5、鸿蒙、鸿蒙Next.
|
||||
- 参考 [文档](https://help.jeecg.com/ui/2dev/mini) 可以删除不需要的demo,制作一个精简版本
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
启动项目
|
||||
-----------------------------------
|
||||
|
||||
> 默认账号密码: admin/123456
|
||||
|
||||
- [开发环境搭建](https://help.jeecg.com/java/setup/tools)
|
||||
- [IDEA启动前后端(单体模式)](https://help.jeecg.com/java/setup/idea/startup)
|
||||
- [Docker一键启动(单体模式)](https://help.jeecg.com/java/docker/quick)
|
||||
- [IDEA启动前后端(微服务方式)](https://help.jeecg.com/java/springcloud/switchcloud/monomer)
|
||||
- [Docker一键启动(微服务方式)](https://help.jeecg.com/java/docker/quickcloud)
|
||||
|
||||
|
||||
技术文档
|
||||
-----------------------------------
|
||||
|
||||
- 官方网站: [http://www.jeecg.com](http://www.jeecg.com)
|
||||
- 在线演示: [平台演示](https://boot3.jeecg.com) | [APP演示](https://jeecg.com/appIndex)
|
||||
- 入门指南: [快速入门](http://www.jeecg.com/doc/quickstart) | [代码生成使用](https://help.jeecg.com/java/codegen/online) | [开发文档](https://help.jeecg.com) | [AI应用手册](https://help.jeecg.com/aigc) | [视频教程](http://jeecg.com/doc/video)
|
||||
- AI编程实战视频: [JEECG低代码与Cursor+GitHub Copilot实现AI高效编程实战](https://www.bilibili.com/video/BV11XyaBVEoH)
|
||||
- 技术支持: [反馈问题](https://github.com/jeecgboot/JeecgBoot/issues/new?template=bug_report.md) | [低代码体验一分钟](https://jeecg.blog.csdn.net/article/details/106079007)
|
||||
- QQ交流群 : 964611995、⑩716488839(满)、⑨808791225(满)、其他(满)
|
||||
- 在线演示 : [平台演示](http://boot3.jeecg.com) | [APP演示](http://jeecg.com/appIndex) | [体验低代码](https://jeecg.blog.csdn.net/article/details/106079007) | [体验零代码](https://app.qiaoqiaoyun.com/myapps/index)
|
||||
- 开发文档: [文档中心](https://help.jeecg.com) | [AIGC大模块](https://help.jeecg.com/aigc)
|
||||
- 新手指南: [快速入门](http://www.jeecg.com/doc/quickstart) | [入门视频](http://jeecg.com/doc/video) | [如何反馈问题](https://github.com/jeecgboot/JeecgBoot/issues/new?template=bug_report.md)
|
||||
- QQ交流群 : ⑩716488839、⑨808791225(满)、其他(满)
|
||||
|
||||
|
||||
AI 应用平台介绍
|
||||
|
||||
启动项目
|
||||
-----------------------------------
|
||||
|
||||
一个全栈式 AI 开发平台,旨在帮助开发者快速构建和部署个性化的 AI 应用。
|
||||
- [IDEA启动前后端项目](https://help.jeecg.com/java/setup/idea/startup)
|
||||
- [Docker一键启动前后端](https://help.jeecg.com/java/docker/quick)
|
||||
|
||||
JeecgBoot平台提供了一套完善的AI应用管理系统模块,是一套类似`Dify`的`AIGC应用开发平台`+`知识库问答`,是一款基于LLM大语言模型AI应用平台和 RAG 的知识库问答系统。
|
||||
其直观的界面结合了 AI 流程编排、RAG 管道、知识库管理、模型管理、对接向量库、实时运行可观察等,让您可以快速从原型到生产,拥有AI服务能力。
|
||||
|
||||
- [详细专题介绍,请点击查看](README-AI.md)
|
||||
|
||||
- AI视频介绍
|
||||
AIGC应用平台介绍
|
||||
-----------------------------------
|
||||
|
||||
JeecgBoot 平台的AIGC功能模块,是一套类似`Dify`的`AIGC应用开发平台`+`知识库问答`,是一款基于LLM大语言模型AI应用平台和 RAG 的知识库问答系统。
|
||||
其直观的界面结合了 AI 流程编排、RAG 管道、知识库管理、模型管理、对接向量库、实时运行可观察等,让您可以快速从原型到生产,拥有AI服务能力。
|
||||
|
||||
> JDK说明:AI流程编排引擎暂时不支持jdk21,所以目前只能使用jdk8或者jdk17启动项目。
|
||||
|
||||
- [AIGC专题介绍页](README-AI.md)
|
||||
- [AIGC开发文档](https://help.jeecg.com/aigc)
|
||||
- [配置向量库PGVector](https://help.jeecg.com/aigc/config)
|
||||
|
||||
|
||||
##### AI视频介绍
|
||||
|
||||
[](https://www.bilibili.com/video/BV1zmd7YFE4w)
|
||||
|
||||
|
||||
为什么选择JeecgBoot?
|
||||
-----------------------------------
|
||||
- 1.采用最新主流前后分离框架(Spring Boot3 + MyBatis + Shiro/SpringAuthorizationServer + Ant Design4 + Vue3),容易上手;代码生成器依赖性低,灵活的扩展能力,可快速实现二次开发。
|
||||
- 2.前端大版本换代,最新版采用 Vue3.0 + TypeScript + Vite6 + Ant Design Vue4 等新技术方案。
|
||||
- 3.支持微服务Spring Cloud Alibaba(Nacos、Gateway、Sentinel、Skywalking),提供简易机制,支持单体和微服务自由切换(这样可以满足各类项目需求)。
|
||||
- 4.开发效率高,支持在线建表和AI建表,提供强大代码生成器,单表、树列表、一对多、一对一等数据模型,增删改查功能一键生成,菜单配置直接使用。
|
||||
- 5.代码生成器提供强大模板机制,支持自定义模板,目前提供四套风格模板(单表两套、树模型一套、一对多三套)。
|
||||
- 6.提供强大的报表和大屏可视化工具,支持丰富的数据源连接,能够通过拖拉拽方式快速制作报表、大屏和门户设计;支持多种图表类型:柱形图、折线图、散点图、饼图、环形图、面积图、漏斗图、进度图、仪表盘、雷达图、地图等。
|
||||
- 7.低代码能力:在线表单(无需编码,通过在线配置表单,实现表单的增删改查,支持单表、树、一对多、一对一等模型,实现人人皆可编码),在线配置零代码开发、所见即所得支持23种类控件。
|
||||
- 8.低代码能力:在线报表、在线图表(无需编码,通过在线配置方式,实现数据报表和图形报表,可以快速抽取数据,减轻开发压力,实现人人皆可编码)。
|
||||
- 9.Online支持在线增强开发,提供在线代码编辑器,支持代码高亮、代码提示等功能,支持多种语言(Java、SQL、JavaScript等)。
|
||||
- 10.封装完善的用户、角色、菜单、组织机构、数据字典、在线定时任务等基础功能,支持访问授权、按钮权限、数据权限等功能。
|
||||
- 11.前端UI提供丰富的组件库,支持各种常用组件,如表格、树形控件、下拉框、日期选择器等,满足各种复杂的业务需求 [UI组件库文档](https://help.jeecg.com/category/ui%E7%BB%84%E4%BB%B6%E5%BA%93)。
|
||||
- 12.提供APP配套框架,一份多代码多终端适配,一份代码多终端适配,小程序、H5、安卓、iOS、鸿蒙Next。
|
||||
- 13.新版APP框架采用Uniapp、Vue3.0、Vite、Wot-design-uni、TypeScript等最新技术栈,包括二次封装组件、路由拦截、请求拦截等功能。实现了与JeecgBoot完美对接:目前已经实现登录、用户信息、通讯录、公告、移动首页、九宫格、聊天、Online表单、仪表盘等功能,提供了丰富的组件。
|
||||
- 14.提供了一套成熟的AI应用平台功能,从AI模型、知识库到AI应用搭建,助力企业快速落地AI服务,加速智能化升级。
|
||||
- 15.AI能力:目前JeecgBoot支持AI大模型chatgpt和deepseek,现在最新版默认使用deepseek,速度更快质量更高。目前提供了AI对话助手、AI知识库、AI应用、AI建表、AI报表等功能。
|
||||
- 16.提供新行编辑表格JVXETable,轻松满足各种复杂ERP布局,拥有更高的性能、更灵活的扩展、更强大的功能。
|
||||
- 17.平台首页风格,提供多种组合模式,支持自定义风格;支持门户设计,支持自定义首页。
|
||||
- 18.常用共通封装,各种工具类(定时任务、短信接口、邮件发送、Excel导入导出等),基本满足80%项目需求。
|
||||
- 19.简易Excel导入导出,支持单表导出和一对多表模式导出,生成的代码自带导入导出功能。
|
||||
- 20.集成智能报表工具,报表打印、图像报表和数据导出非常方便,可极其方便地生成PDF、Excel、Word等报表。
|
||||
- 21.采用前后分离技术,页面UI风格精美,针对常用组件做了封装:时间、行表格控件、截取显示控件、报表组件、编辑器等。
|
||||
- 22.查询过滤器:查询功能自动生成,后台动态拼SQL追加查询条件;支持多种匹配方式(全匹配/模糊查询/包含查询/不匹配查询)。
|
||||
- 23.数据权限(精细化数据权限控制,控制到行级、列表级、表单字段级,实现不同人看不同数据,不同人对同一个页面操作不同字段)。
|
||||
- 24.接口安全机制,可细化控制接口授权,非常简便实现不同客户端只看自己数据等控制;也提供了基于AK和SK认证鉴权的OpenAPI功能。
|
||||
- 25.活跃的社区支持;近年来,随着网络威胁的日益增加,团队在安全和漏洞管理方面积累了丰富的经验,能够为企业提供全面的安全解决方案。
|
||||
- 26.权限控制采用RBAC(Role-Based Access Control,基于角色的访问控制)。
|
||||
- 27.页面校验自动生成(必须输入、数字校验、金额校验、时间空间等)。
|
||||
- 28.支持SaaS服务模式,提供SaaS多租户架构方案。
|
||||
- 29.分布式文件服务,集成MinIO、阿里OSS等优秀的第三方,提供便捷的文件上传与管理,同时也支持本地存储。
|
||||
- 30.主流数据库兼容,一套代码完全兼容MySQL、PostgreSQL、Oracle、SQL Server、MariaDB、达梦、人大金仓等主流数据库。
|
||||
- 31.集成工作流Flowable,并实现了只需在页面配置流程转向,可极大简化BPM工作流的开发;用BPM的流程设计器画出了流程走向,一个工作流基本就完成了,只需写很少量的Java代码。
|
||||
- 32.低代码能力:在线流程设计,采用开源Flowable流程引擎,实现在线画流程、自定义表单、表单挂靠、业务流转。
|
||||
- 33.多数据源:极其简易的使用方式,在线配置数据源配置,便捷地从其他数据抓取数据。
|
||||
- 34.提供单点登录CAS集成方案,项目中已经提供完善的对接代码。
|
||||
- 35.低代码能力:表单设计器,支持用户自定义表单布局,支持单表、一对多表单,支持select、radio、checkbox、textarea、date、popup、列表、宏等控件。
|
||||
- 36.专业接口对接机制,统一采用RESTful接口方式,集成Swagger-UI在线接口文档,JWT token安全验证,方便客户端对接。
|
||||
- 37.高级组合查询功能,在线配置支持主子表关联查询,可保存查询历史。
|
||||
- 38.提供各种系统监控,实时跟踪系统运行情况(监控Redis、Tomcat、JVM、服务器信息、请求追踪、SQL监控)。
|
||||
- 39.消息中心(支持短信、邮件、微信推送等);集成WebSocket消息通知机制。
|
||||
- 40.支持多语言,提供国际化方案。
|
||||
- 41.数据变更记录日志,可记录数据每次变更内容,通过版本对比功能查看历史变化。
|
||||
- 42.提供简单易用的打印插件,支持谷歌、火狐、IE11+等各种浏览器。
|
||||
- 43.后端采用Maven分模块开发方式;前端支持菜单动态路由。
|
||||
- 44.提供丰富的示例代码,涵盖了常用的业务场景,便于学习和参考。
|
||||
##### 在线体验
|
||||
|
||||
- JeecgBoot演示: https://boot3.jeecg.com
|
||||
- 敲敲云在线搭建AI知识库:https://app.qiaoqiaoyun.com
|
||||
|
||||
##### Dify `VS` JEECG AI
|
||||
|
||||
> JEECG AI与Dify相比,在多个方面展现出显著的优势,特别是在文档处理、格式和图片保持方面。以下是一些具体的优点:
|
||||
> - Markdown文档库导入:
|
||||
> JEECG AI允许用户直接导入整个Markdown文档库,这不仅保留markdown格式,还支持图片的导入,确保文档内容的完整性和可视化效果。
|
||||
> - 对话回复格式美观:
|
||||
> 在对话过程中,JEECG AI能够保持回复内容的原格式,也不丢失图片,使得输出的文章更加美观,不会出现格式错乱的情况,还支持图片的渲染。
|
||||
> - PDF文档导入与格式转换:
|
||||
> JEECG AI在处理PDF文档时,能够更好地保持原始格式和图片,确保转换后的内容与原始文档一致。这个功能在许多AI产品中表现不佳,而JEECG AI在这方面做出了显著的优化
|
||||
|
||||
##### 功能大模块
|
||||
|
||||
- AI应用开发平台
|
||||
- AI知识库系统
|
||||
- AI大模型管理
|
||||
- AI流程编排
|
||||
- AI对话支持图片
|
||||
- AI对话助手(智能问答)
|
||||
- AI建表(Online表单)
|
||||
- AI写文章(CMS)
|
||||
- AI表单字段建议(表单设计器)
|
||||
|
||||
##### AI大模型支持
|
||||
|
||||
| AI大模型 | 支持 |
|
||||
| --- | --- |
|
||||
| DeepSeek | √ |
|
||||
| ChatGTP | √ |
|
||||
| Qwq | √ |
|
||||
| 智库 | √ |
|
||||
| Ollama本地模型 | √ |
|
||||
| 等等。。 | √ |
|
||||
|
||||
|
||||
|
||||
|
||||
技术架构:
|
||||
-----------------------------------
|
||||
|
||||
#### 前端
|
||||
|
||||
- 前端环境要求:Node.js要求`Node 20+` 版本以上、pnpm 要求`9+` 版本以上
|
||||
|
||||
` ( Vite 不再支持已结束生命周期(EOL)的 Node.js 18。现在需要使用 Node.js 20.19+ 或 22.12+)`
|
||||
|
||||
- 依赖管理:node、npm、pnpm
|
||||
- 前端IDE建议:IDEA、WebStorm、Vscode
|
||||
- 采用 Vue3.0+TypeScript+Vite6+Ant-Design-Vue4等新技术方案,包括二次封装组件、utils、hooks、动态菜单、权限校验、按钮级别权限控制等功能
|
||||
- 最新技术栈:Vue3.0 + TypeScript + Vite6 + ant-design-vue4 + pinia + echarts + unocss + vxe-table + qiankun + es6
|
||||
|
||||
|
||||
#### 后端
|
||||
|
||||
- IDE建议: IDEA (必须安装lombok插件 )
|
||||
- 语言:Java 默认jdk17(jdk21、jdk24)
|
||||
- 语言:Java 默认jdk17(支持jdk8、jdk21)
|
||||
- 依赖管理:Maven
|
||||
- 基础框架:Spring Boot 3.5.5
|
||||
- 微服务框架: Spring Cloud Alibaba 2023.0.3.3
|
||||
- 持久层框架:MybatisPlus 3.5.12
|
||||
- 报表工具: JimuReport 2.1.3
|
||||
- 安全框架:Apache Shiro 2.0.4,Jwt 4.5.0
|
||||
- 基础框架:Spring Boot 2.7.18
|
||||
- 微服务框架: Spring Cloud Alibaba 2021.0.6.2
|
||||
- 持久层框架:MybatisPlus 3.5.3.2
|
||||
- 报表工具: JimuReport 1.9.5
|
||||
- 安全框架:Apache Shiro 1.13.0,Jwt 4.5.0
|
||||
- 微服务技术栈:Spring Cloud Alibaba、Nacos、Gateway、Sentinel、Skywalking
|
||||
- 数据库连接池:阿里巴巴Druid 1.2.24
|
||||
- AI大模型:支持 `ChatGPT` `DeepSeek` `千问`等各种常规模式
|
||||
- 数据库连接池:阿里巴巴Druid 1.1.24
|
||||
- AI大模型:支持 `ChatGPT` `DeepSeek`切换
|
||||
- 日志打印:logback
|
||||
- 缓存:Redis
|
||||
- 其他:autopoi, fastjson,poi,Swagger-ui,quartz, lombok(简化代码)等。
|
||||
- 默认提供MySQL5.7+数据库脚本
|
||||
- 默认数据库脚本:MySQL5.7+
|
||||
- [其他数据库,需要自己转](https://my.oschina.net/jeecg/blog/4905722)
|
||||
|
||||
#### 数据库支持
|
||||
|
||||
#### 前端
|
||||
|
||||
- 前端IDE建议:WebStorm、Vscode
|
||||
- 采用 Vue3.0+TypeScript+Vite6+Ant-Design-Vue等新技术方案,包括二次封装组件、utils、hooks、动态菜单、权限校验、按钮级别权限控制等功能
|
||||
- 最新技术栈:Vue3.0 + TypeScript + Vite6 + ant-design-vue4 + pinia + echarts + unocss + vxe-table + qiankun + es6
|
||||
- 依赖管理:node、npm、pnpm
|
||||
|
||||
|
||||
#### 前端环境要求
|
||||
|
||||
* 本地环境安装 `Node.js 、npm 、pnpm`
|
||||
* pnpm 要求`9+` 版本以上
|
||||
* Node.js 版本建议`v20.15.0`,要求`Node 20+` 版本以上
|
||||
|
||||
` ( 因为Vite6 需要 Node.js 18 / 20+ )`
|
||||
|
||||
|
||||
#### 平台支持数据库
|
||||
|
||||
> jeecgboot平台支持以下数据库,默认我们只提供mysql脚本,其他数据库可以参考[转库文档](https://my.oschina.net/jeecg/blog/4905722)自己转。
|
||||
|
||||
@ -200,12 +201,12 @@ JeecgBoot平台提供了一套完善的AI应用管理系统模块,是一套类
|
||||
| 人大金仓 | √ |
|
||||
| TiDB | √ |
|
||||
| kingbase8 | √ |
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## 微服务解决方案
|
||||
|
||||
|
||||
- 1、服务注册和发现 Nacos √
|
||||
- 2、统一配置中心 Nacos √
|
||||
- 3、路由网关 gateway(三种加载方式) √
|
||||
@ -223,23 +224,62 @@ JeecgBoot平台提供了一套完善的AI应用管理系统模块,是一套类
|
||||
- 15、CAS 单点登录 √
|
||||
- 16、路由限流 √
|
||||
|
||||
|
||||
#### 微服务方式启动
|
||||
|
||||
- [单体快速切换微服务](https://help.jeecg.com/java/springcloud/switchcloud/monomer)
|
||||
- [Docker一键启动微服务前后端](https://help.jeecg.com/java/docker/quickcloud)
|
||||
|
||||
|
||||
#### 微服务架构图
|
||||

|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
开源版与企业版区别?
|
||||
为什么选择JeecgBoot?
|
||||
-----------------------------------
|
||||
|
||||
- JeecgBoot开源版采用 [Apache-2.0 license](LICENSE) 协议附加补充条款:允许商用使用,不会造成侵权行为,允许基于本平台软件开展业务系统开发(但在任何情况下,您不得使用本软件开发可能被认为与本软件竞争的软件).
|
||||
- 商业版与开源版主要区别在于商业版提供了技术支持 和 更多的企业级功能(例如:Online图表、流程监控、流程设计、流程审批、表单设计器、表单视图、积木报表企业版、OA办公、商业APP、零代码应用、Online模块源码等功能). [更多商业功能介绍,点击查看](README-Enterprise.md)
|
||||
- JeecgBoot未来发展方向是:零代码平台的建设,也就是团队的另外一款产品 [敲敲云零代码](https://www.qiaoqiaoyun.com) ,无需编码即可通过拖拽快速搭建企业级应用,与JeecgBoot低代码平台形成互补,满足从简单业务到复杂系统的全场景开发需求,目前已经开源,[欢迎下载](https://qiaoqiaoyun.com/downloadCode)
|
||||
|
||||
|
||||
|
||||
|
||||
* 1.采用最新主流前后分离框架(Springboot+Mybatis+antd+vue3),容易上手; 代码生成器依赖性低,灵活的扩展能力,可快速实现二次开发;
|
||||
* 2.支持微服务SpringCloud Alibaba(Nacos、Gateway、Sentinel、Skywalking),提供切换机制支持单体和微服务自由切换
|
||||
* 3.开发效率高,采用代码生成器,单表、树列表、一对多、一对一等数据模型,增删改查功能一键生成,菜单配置直接使用;引入AI能力,支持自动建表等功能;
|
||||
* 4.代码生成器提供强大模板机制,支持自定义模板,目前提供四套风格模板(单表两套、树模型一套、一对多三套)
|
||||
* 5.代码生成器非常智能,在线业务建模、在线配置、所见即所得支持23种类控件,一键生成前后端代码,大幅度提升开发效率,不再为重复工作发愁。
|
||||
* 6.AI能力:目前JeecgBoot支持AI大模型chatgpt和deepseek,现在最新版默认使用deepseek,速度更快质量更高。目前提供了AI对话助手、AI建表、AI报表等功能。
|
||||
* 6.低代码能力:Online在线表单(无需编码,通过在线配置表单,实现表单的增删改查,支持单表、树、一对多、一对一等模型,实现人人皆可编码)
|
||||
* 7.低代码能力:Online在线报表、Online在线图表(无需编码,通过在线配置方式,实现数据报表和图形报表,可以快速抽取数据,减轻开发压力,实现人人皆可编码)
|
||||
* 9.封装完善的用户、角色、菜单、组织机构、数据字典、在线定时任务等基础功能,支持访问授权、按钮权限、数据权限等功能
|
||||
* 10.常用共通封装,各种工具类(定时任务,短信接口,邮件发送,Excel导入导出等),基本满足80%项目需求
|
||||
* 11.简易Excel导入导出,支持单表导出和一对多表模式导出,生成的代码自带导入导出功能
|
||||
* 12.集成简易报表工具,图像报表和数据导出非常方便,可极其方便的生成图形报表、pdf、excel、word等报表;
|
||||
* 13.采用前后分离技术,页面UI风格精美,针对常用组件做了封装:时间、行表格控件、截取显示控件、报表组件,编辑器等等
|
||||
* 14.查询过滤器:查询功能自动生成,后台动态拼SQL追加查询条件;支持多种匹配方式(全匹配/模糊查询/包含查询/不匹配查询);
|
||||
* 15.数据权限(精细化数据权限控制,控制到行级,列表级,表单字段级,实现不同人看不同数据,不同人对同一个页面操作不同字段
|
||||
* 16.页面校验自动生成(必须输入、数字校验、金额校验、时间空间等);
|
||||
* 17.支持SAAS服务模式,提供SaaS多租户架构方案。
|
||||
* 18.分布式文件服务,集成minio、阿里OSS等优秀的第三方,提供便捷的文件上传与管理,同时也支持本地存储。
|
||||
* 19.主流数据库兼容,一套代码完全兼容Mysql、Postgresql、Oracle、Sqlserver、MariaDB、达梦、人大金仓等主流数据库。
|
||||
* 20.集成工作流flowable,并实现了只需在页面配置流程转向,可极大的简化bpm工作流的开发;用bpm的流程设计器画出了流程走向,一个工作流基本就完成了,只需写很少量的java代码;
|
||||
* 21.低代码能力:在线流程设计,采用开源flowable流程引擎,实现在线画流程,自定义表单,表单挂靠,业务流转
|
||||
* 22.多数据源:及其简易的使用方式,在线配置数据源配置,便捷的从其他数据抓取数据;
|
||||
* 23.提供单点登录CAS集成方案,项目中已经提供完善的对接代码
|
||||
* 24.低代码能力:表单设计器,支持用户自定义表单布局,支持单表,一对多表单、支持select、radio、checkbox、textarea、date、popup、列表、宏等控件
|
||||
* 25.专业接口对接机制,统一采用restful接口方式,集成swagger-ui在线接口文档,Jwt token安全验证,方便客户端对接
|
||||
* 26.接口安全机制,可细化控制接口授权,非常简便实现不同客户端只看自己数据等控制
|
||||
* 27.高级组合查询功能,在线配置支持主子表关联查询,可保存查询历史
|
||||
* 28.提供各种系统监控,实时跟踪系统运行情况(监控 Redis、Tomcat、jvm、服务器信息、请求追踪、SQL监控)
|
||||
* 29.消息中心(支持短信、邮件、微信推送等等)
|
||||
* 30.集成Websocket消息通知机制
|
||||
* 31.移动自适应效果优秀,提供APP发布方案:
|
||||
* 32.支持多语言,提供国际化方案;
|
||||
* 33.数据变更记录日志,可记录数据每次变更内容,通过版本对比功能查看历史变化
|
||||
* 34.平台UI强大,实现了移动自适应
|
||||
* 35.平台首页风格,提供多种组合模式,支持自定义风格
|
||||
* 36.提供简单易用的打印插件,支持谷歌、火狐、IE11+ 等各种浏览器
|
||||
* 37.示例代码丰富,提供很多学习案例参考
|
||||
* 38.采用maven分模块开发方式
|
||||
* 39.支持菜单动态路由
|
||||
* 40.权限控制采用 RBAC(Role-Based Access Control,基于角色的访问控制)
|
||||
* 41.提供新行编辑表格JVXETable,轻松满足各种复杂ERP布局,拥有更高的性能、更灵活的扩展、更强大的功能
|
||||
* 42.提供仪表盘设计器,类大屏设计支持移动端,免费的数据可视化设计工具,支持丰富的数据源连接,能够通过拖拉拽方式快速制作图表和门户设计;目前支持多种图表类型:柱形图、折线图、散点图、饼图、环形图、面积图、漏斗图、进度图、仪表盘、雷达图、地图等等;
|
||||
|
||||
|
||||
### Jeecg Boot 产品功能蓝图
|
||||
@ -247,19 +287,47 @@ JeecgBoot平台提供了一套完善的AI应用管理系统模块,是一套类
|
||||
|
||||
|
||||
|
||||
#### 系统功能架构图
|
||||
|
||||

|
||||
### 分支说明
|
||||
|
||||
> 主干master更稳定,如果你对最新技术栈无要求,建议采用主干
|
||||
|
||||
#### springboot3分支
|
||||
- 源码地址:https://github.com/jeecgboot/JeecgBoot/tree/springboot3
|
||||
- 架构说明:升级Spring Boot3 & JDK 17 + Undertow + springdoc + fastjson2
|
||||
|
||||
#### springboot3_sas分支
|
||||
- 源码地址:https://github.com/jeecgboot/JeecgBoot/tree/springboot3_sas
|
||||
- 架构说明:在springboot3分支基础上,采用SpringAuthorizationServer替换Shiro
|
||||
|
||||
|
||||
|
||||
### 开源版功能清单
|
||||
### 功能模块
|
||||
```
|
||||
├─AI开发
|
||||
│ ├─支持AI大模型ChatGPT和DeepSeek
|
||||
│ ├─AI对话助手
|
||||
│ ├─AI建表
|
||||
│ ├─AI写文章
|
||||
│ ├─AI流程编排
|
||||
│ ├─AI知识库问答系统
|
||||
│ ├─AI应用开发平台
|
||||
│ ├─AI聊天窗口支持嵌入第三方
|
||||
├─Online在线开发(低代码)
|
||||
│ ├─Online在线表单
|
||||
│ ├─Online代码生成器
|
||||
│ ├─Online在线报表
|
||||
│ ├─仪表盘设计器
|
||||
│ ├─系统编码规则
|
||||
│ ├─系统校验规则
|
||||
├─积木报表设计器
|
||||
│ ├─打印设计器
|
||||
│ ├─数据报表设计
|
||||
│ ├─图形报表设计(支持echart)
|
||||
├─系统管理
|
||||
│ ├─用户管理
|
||||
│ ├─角色管理
|
||||
│ ├─菜单管理
|
||||
│ ├─首页配置
|
||||
│ ├─权限设置(支持按钮权限、数据权限)
|
||||
│ ├─表单权限(控制字段禁用、隐藏)
|
||||
│ ├─部门管理
|
||||
@ -270,36 +338,7 @@ JeecgBoot平台提供了一套完善的AI应用管理系统模块,是一套类
|
||||
│ └─职务管理
|
||||
│ └─通讯录
|
||||
│ ├─多数据源管理
|
||||
│ ├─白名单管理
|
||||
│ ├─第三方配置(对接钉钉和企业微信)
|
||||
│ └─多租户管理(租户管理、租户角色、我的租户、租户默认套餐管理)
|
||||
├─Online在线开发(低代码)
|
||||
│ ├─Online在线表单
|
||||
│ ├─Online代码生成器
|
||||
│ ├─Online在线报表
|
||||
│ ├─仪表盘设计器
|
||||
│ ├─系统编码规则
|
||||
│ ├─系统校验规则
|
||||
│ ├─APP版本管理
|
||||
├─AI应用平台
|
||||
│ ├─AI知识库问答系统
|
||||
│ ├─AI大模型管理
|
||||
│ ├─AI流程编排
|
||||
│ ├─AI流程设计器
|
||||
│ ├─AI对话支持图片
|
||||
│ ├─AI对话助手(智能问答)
|
||||
│ ├─AI建表(Online表单)
|
||||
│ ├─AI聊天窗口支持嵌入第三方
|
||||
│ ├─AI聊天窗口支持移动端
|
||||
│ ├─支持常见大模型ChatGPT和DeepSeek、ollama等等
|
||||
│ ├─AI OCR示例
|
||||
├─数据可视化
|
||||
│ ├─报表设计器(支持打印设计)
|
||||
│ ├─大屏设和仪表盘设计
|
||||
├─OpenAPI(基于AK和SK认证鉴权)
|
||||
│ ├─接口管理
|
||||
│ ├─接口授权
|
||||
│ ├─接口文档
|
||||
│ └─多租户管理(租户管理、租户角色、我的租户)
|
||||
├─消息中心
|
||||
│ ├─消息管理
|
||||
│ ├─模板管理
|
||||
@ -311,12 +350,8 @@ JeecgBoot平台提供了一套完善的AI应用管理系统模块,是一套类
|
||||
│ ├─高级查询器(弹窗自动组合查询条件)
|
||||
│ ├─Excel导入导出工具集成(支持单表,一对多 导入导出)
|
||||
│ ├─平台移动自适应支持
|
||||
│ ├─提供新版uniapp3的代码生成器模板
|
||||
├─系统监控
|
||||
│ ├─Gateway路由网关
|
||||
│ ├─基于AK和SK认证鉴权OpenAPI功能
|
||||
│ ├─定时任务
|
||||
│ ├─数据源管理
|
||||
│ ├─性能扫描监控
|
||||
│ │ ├─监控 Redis
|
||||
│ │ ├─Tomcat
|
||||
@ -324,11 +359,13 @@ JeecgBoot平台提供了一套完善的AI应用管理系统模块,是一套类
|
||||
│ │ ├─服务器信息
|
||||
│ │ ├─请求追踪
|
||||
│ │ ├─磁盘监控
|
||||
│ ├─定时任务
|
||||
│ ├─系统日志
|
||||
│ ├─消息中心(支持短信、邮件、微信推送等等)
|
||||
│ ├─数据日志(记录数据快照,可对比快照,查看数据变更情况)
|
||||
│ ├─系统通知
|
||||
│ ├─SQL监控
|
||||
│ ├─在线用户
|
||||
│ ├─swagger-ui(在线接口文档)
|
||||
│─报表示例
|
||||
│ ├─曲线图
|
||||
│ └─饼状图
|
||||
@ -393,16 +430,46 @@ JeecgBoot平台提供了一套完善的AI应用管理系统模块,是一套类
|
||||
│ ├─提供单点登录CAS集成方案
|
||||
│ ├─提供APP发布方案
|
||||
│ ├─集成Websocket消息通知机制
|
||||
│ ├─支持electron桌面应用打包(支持windows、linux、macOS三大平台)
|
||||
│ ├─docker容器支持
|
||||
│ ├─提供移动APP框架及源码(Uniapp3版本)支持H5、小程序、APP、鸿蒙Next
|
||||
│ ├─提供移动APP低代码设计(Online表单、仪表盘)
|
||||
│─更多商业功能
|
||||
│ ├─流程设计器
|
||||
│ ├─表单设计器
|
||||
│ ├─大屏设计器
|
||||
│ └─我的任务
|
||||
│ └─历史流程
|
||||
│ └─历史流程
|
||||
│ └─流程实例管理
|
||||
│ └─流程监听管理
|
||||
│ └─流程表达式
|
||||
│ └─我发起的流程
|
||||
│ └─我的抄送
|
||||
│ └─流程委派、抄送、跳转
|
||||
│ └─OA办公组件
|
||||
│ └─。。。
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
### 系统效果
|
||||
|
||||
|
||||
##### AI功能
|
||||
|
||||
AI聊天助手
|
||||
|
||||

|
||||
|
||||
AI建表
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
AI写文章
|
||||
|
||||

|
||||
|
||||
|
||||
##### PC端
|
||||

|
||||
|
||||
@ -422,22 +489,6 @@ JeecgBoot平台提供了一套完善的AI应用管理系统模块,是一套类
|
||||

|
||||
|
||||
|
||||
##### AI功能
|
||||
|
||||
AI聊天助手
|
||||
|
||||

|
||||
|
||||
AI建表
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
AI写文章
|
||||
|
||||

|
||||
|
||||
|
||||
##### 仪表盘设计器
|
||||
|
||||
@ -504,6 +555,28 @@ AI写文章
|
||||

|
||||
|
||||
|
||||
##### 流程设计
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
##### 表单设计器
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -1,216 +0,0 @@
|
||||
import os
|
||||
import subprocess
|
||||
import re
|
||||
import sys
|
||||
from typing import Tuple, Optional
|
||||
|
||||
def run_command(cmd: str) -> Tuple[int, str]:
|
||||
"""执行命令并返回退出码和输出"""
|
||||
try:
|
||||
result = subprocess.run(cmd, shell=True, check=False,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
text=True)
|
||||
return result.returncode, result.stdout.strip()
|
||||
except Exception as e:
|
||||
return -1, str(e)
|
||||
|
||||
def check_java() -> bool:
|
||||
"""检查JDK 17+是否安装"""
|
||||
print("\n检查JDK 17+...")
|
||||
rc, output = run_command("java -version 2>&1")
|
||||
if rc != 0:
|
||||
print("❌ 未检测到Java,请安装JDK 17+")
|
||||
return False
|
||||
|
||||
version_pattern = r'"(\d+)(?:\.\d+)*(?:_\d+)?'
|
||||
match = re.search(version_pattern, output)
|
||||
if not match:
|
||||
print("❌ 无法解析Java版本")
|
||||
return False
|
||||
|
||||
version = int(match.group(1))
|
||||
if version >= 17:
|
||||
print(f"✅ JDK版本 {version} (满足17+要求)")
|
||||
return True
|
||||
else:
|
||||
print(f"❌ JDK版本 {version} (需要17+)")
|
||||
return False
|
||||
|
||||
def check_maven() -> bool:
|
||||
"""检查Maven是否安装"""
|
||||
print("\n检查Maven...")
|
||||
rc, output = run_command("mvn -v")
|
||||
if rc == 0:
|
||||
print("✅ Maven已安装")
|
||||
return True
|
||||
else:
|
||||
print("❌ Maven未安装")
|
||||
return False
|
||||
|
||||
def check_node() -> bool:
|
||||
"""检查Node.js 20+是否安装"""
|
||||
print("\n检查Node.js 20+...")
|
||||
rc, output = run_command("node -v")
|
||||
if rc != 0:
|
||||
print("❌ Node.js未安装")
|
||||
return False
|
||||
|
||||
version_pattern = r'v(\d+)\.\d+\.\d+'
|
||||
match = re.search(version_pattern, output)
|
||||
if not match:
|
||||
print("❌ 无法解析Node.js版本")
|
||||
return False
|
||||
|
||||
version = int(match.group(1))
|
||||
if version >= 20:
|
||||
print(f"✅ Node.js版本 {version} (满足20+要求)")
|
||||
return True
|
||||
else:
|
||||
print(f"❌ Node.js版本 {version} (需要20+)")
|
||||
return False
|
||||
|
||||
def check_pnpm() -> bool:
|
||||
"""检查PNPM 9+是否安装"""
|
||||
print("\n检查PNPM 9+...")
|
||||
rc, output = run_command("pnpm -v")
|
||||
if rc != 0:
|
||||
print("❌ PNPM未安装")
|
||||
return False
|
||||
|
||||
try:
|
||||
# 处理可能的版本号格式:v9.0.0 或 9.0.0 或 9
|
||||
version_str = output.strip().lstrip('v').split('.')[0]
|
||||
version = int(version_str)
|
||||
|
||||
if version >= 9:
|
||||
print(f"✅ PNPM版本 {output.strip()} (满足9+要求)")
|
||||
return True
|
||||
else:
|
||||
print(f"❌ PNPM版本 {output.strip()} (需要9+)")
|
||||
return False
|
||||
except (ValueError, IndexError):
|
||||
print(f"❌ 无法解析PNPM版本: {output.strip()}")
|
||||
return False
|
||||
|
||||
def check_redis_connection() -> bool:
|
||||
"""检查Redis连接"""
|
||||
print("\n检查Redis连接...")
|
||||
print("⚠️ 请确保已配置Redis连接信息并在jeecg-boot项目中正确配置")
|
||||
print("⚠️ 此检查需要根据实际项目配置进行验证")
|
||||
print("⚠️ 配置文件位置: jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/application-dev.yml")
|
||||
return True
|
||||
|
||||
def check_mysql_connection() -> bool:
|
||||
"""检查MySQL连接"""
|
||||
print("\n检查MySQL连接...")
|
||||
print("⚠️ 请确保已配置MySQL连接信息并在jeecg-boot项目中正确配置")
|
||||
print("⚠️ 此检查需要根据实际项目配置进行验证")
|
||||
print("⚠️ 配置文件位置: jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/application-dev.yml")
|
||||
return True
|
||||
|
||||
def print_mysql_config():
|
||||
"""打印MySQL配置并提示需要修改的位置"""
|
||||
print("\nMySQL配置参考 (请检查以下配置是否正确):")
|
||||
print("""
|
||||
spring.datasource.dynamic.datasource:
|
||||
master:
|
||||
url: jdbc:mysql://127.0.0.1:3306/jeecg-boot?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
|
||||
username: root # ← 可能需要修改
|
||||
password: root # ← 可能需要修改
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
""")
|
||||
|
||||
def check_ai_vector_db() -> bool:
|
||||
"""检查AI向量库(pgvector)配置"""
|
||||
print("\n检查AI知识库向量库配置...")
|
||||
print("⚠️ 如果需要使用AI知识库功能,请配置pgvector向量库")
|
||||
print("⚠️ 配置文件位置: jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/application-dev.yml")
|
||||
print("\n配置参考:")
|
||||
print("""
|
||||
jeecg.ai-rag:
|
||||
embed-store:
|
||||
host: 127.0.0.1 # ← 可能需要修改
|
||||
port: 5432 # ← 可能需要修改
|
||||
database: postgres # ← 可能需要修改
|
||||
user: postgres # ← 可能需要修改
|
||||
password: postgres # ← 可能需要修改
|
||||
table: embeddings # ← 可能需要修改
|
||||
""")
|
||||
print("⚠️ 注意: 请确保已安装PostgreSQL并添加pgvector扩展!docker安装参考:https://help.jeecg.com/aigc/config")
|
||||
return True
|
||||
|
||||
def check_ai_config() -> bool:
|
||||
"""检查AI账号配置"""
|
||||
print("\n检查AI功能配置...")
|
||||
print("⚠️ 如果需要使用AI聊天功能,请配置AI账号信息")
|
||||
print("⚠️ 配置文件位置: jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/resources/application-dev.yml")
|
||||
print("\n配置参考:")
|
||||
print("""
|
||||
jeecg:
|
||||
# AI集成
|
||||
ai-chat:
|
||||
enabled: true # ← 启用AI功能
|
||||
model: deepseek-chat # ← 模型名称
|
||||
apiKey: ?? # ← 必须修改为您的API Key
|
||||
apiHost: https://api.deepseek.com/v1 # ← API地址
|
||||
timeout: 60 # ← 超时时间(秒)
|
||||
""")
|
||||
print("⚠️ 注意: 请确保已获取有效的API Key并正确配置!AI账号注册获取参考: https://help.jeecg.com/java/deepSeekSupport")
|
||||
return True
|
||||
|
||||
|
||||
def print_redis_config():
|
||||
"""打印Redis配置并提示需要修改的位置"""
|
||||
print("\nRedis配置参考 (请检查以下配置是否正确):")
|
||||
print("""
|
||||
spring.redis:
|
||||
database: 0
|
||||
host: 127.0.0.1 # ← 可能需要修改
|
||||
port: 6379 # ← 可能需要修改
|
||||
password: '' # ← 如果需要密码请修改
|
||||
""")
|
||||
|
||||
def main():
|
||||
print("="*50)
|
||||
print("JeecgBoot 运行环境检查脚本")
|
||||
print("="*50)
|
||||
|
||||
all_checks_passed = True
|
||||
|
||||
# 检查各项依赖
|
||||
if not check_java():
|
||||
all_checks_passed = False
|
||||
|
||||
if not check_maven():
|
||||
all_checks_passed = False
|
||||
|
||||
if not check_node():
|
||||
all_checks_passed = False
|
||||
|
||||
if not check_pnpm():
|
||||
all_checks_passed = False
|
||||
|
||||
# 数据库提示
|
||||
print("="*50)
|
||||
check_redis_connection()
|
||||
print_redis_config()
|
||||
print("="*50)
|
||||
check_mysql_connection()
|
||||
print_mysql_config()
|
||||
print("="*50)
|
||||
check_ai_config()
|
||||
print("="*50)
|
||||
check_ai_vector_db()
|
||||
|
||||
print("\n" + "="*50)
|
||||
if all_checks_passed:
|
||||
print("✅ 所有基础环境检查通过")
|
||||
print("⚠️ 注意: 请确保Redis和MySQL、AI账号、向量库pgvector 已正确配置并连接成功")
|
||||
else:
|
||||
print("❌ 部分环境检查未通过,请根据上述提示解决问题")
|
||||
|
||||
print("="*50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
input("\n按回车键退出...") # 等待用户输入
|
||||
@ -18,33 +18,20 @@ services:
|
||||
--max_allowed_packet=128M
|
||||
--default-authentication-plugin=caching_sha2_password
|
||||
ports:
|
||||
- 13306:3306
|
||||
- 3306:3306
|
||||
networks:
|
||||
- jeecg-boot
|
||||
|
||||
jeecg-boot-redis:
|
||||
image: registry.cn-hangzhou.aliyuncs.com/jeecgdocker/redis:5.0
|
||||
# ports:
|
||||
# - 6379:6379
|
||||
ports:
|
||||
- 6379:6379
|
||||
restart: always
|
||||
hostname: jeecg-boot-redis
|
||||
container_name: jeecg-boot-redis
|
||||
networks:
|
||||
- jeecg-boot
|
||||
|
||||
jeecg-boot-pgvector:
|
||||
image: registry.cn-hangzhou.aliyuncs.com/jeecgdocker/pgvector
|
||||
container_name: jeecg-boot-pgvector
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: vector_db
|
||||
ports:
|
||||
- 5432:5432
|
||||
restart: always
|
||||
networks:
|
||||
- jeecg-boot
|
||||
|
||||
jeecg-boot-nacos:
|
||||
restart: always
|
||||
build:
|
||||
@ -109,37 +96,31 @@ services:
|
||||
# environment:
|
||||
# RABBITMQ_DEFAULT_USER: guest
|
||||
# RABBITMQ_DEFAULT_PASS: guest
|
||||
# jeecg-boot-sentinel:
|
||||
# restart: on-failure
|
||||
# build:
|
||||
# context: ./jeecg-visual/jeecg-cloud-sentinel
|
||||
# ports:
|
||||
# - 9000:9000
|
||||
# depends_on:
|
||||
# - jeecg-boot-nacos
|
||||
# - jeecg-boot-demo
|
||||
# - jeecg-boot-system
|
||||
# - jeecg-boot-gateway
|
||||
# container_name: jeecg-boot-sentinel
|
||||
# hostname: jeecg-boot-sentinel
|
||||
#
|
||||
# jeecg-boot-xxljob:
|
||||
# build:
|
||||
# context: ./jeecg-visual/jeecg-cloud-xxljob
|
||||
# ports:
|
||||
# - 9080:9080
|
||||
# container_name: jeecg-boot-xxljob
|
||||
# hostname: jeecg-boot-xxljob
|
||||
|
||||
jeecg-boot-sentinel:
|
||||
restart: on-failure
|
||||
build:
|
||||
context: ./jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel
|
||||
ports:
|
||||
- 9000:9000
|
||||
depends_on:
|
||||
- jeecg-boot-nacos
|
||||
- jeecg-boot-demo
|
||||
- jeecg-boot-system
|
||||
- jeecg-boot-gateway
|
||||
container_name: jeecg-boot-sentinel
|
||||
hostname: jeecg-boot-sentinel
|
||||
networks:
|
||||
- jeecg-boot
|
||||
|
||||
jeecg-boot-xxljob:
|
||||
build:
|
||||
context: ./jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-xxljob
|
||||
ports:
|
||||
- 9080:9080
|
||||
container_name: jeecg-boot-xxljob
|
||||
hostname: jeecg-boot-xxljob
|
||||
networks:
|
||||
- jeecg-boot
|
||||
|
||||
jeecg-vue:
|
||||
build:
|
||||
context: ./jeecgboot-vue3
|
||||
dockerfile: Dockerfile.cloud
|
||||
container_name: jeecgboot-vue3-nginx
|
||||
image: jeecgboot-vue3
|
||||
depends_on:
|
||||
|
||||
@ -18,33 +18,20 @@ services:
|
||||
--max_allowed_packet=128M
|
||||
--default-authentication-plugin=caching_sha2_password
|
||||
ports:
|
||||
- 13306:3306
|
||||
- 3306:3306
|
||||
networks:
|
||||
- jeecg-boot
|
||||
|
||||
jeecg-boot-redis:
|
||||
image: registry.cn-hangzhou.aliyuncs.com/jeecgdocker/redis:5.0
|
||||
# ports:
|
||||
# - 3792:6379
|
||||
ports:
|
||||
- 6379:6379
|
||||
restart: always
|
||||
hostname: jeecg-boot-redis
|
||||
container_name: jeecg-boot-redis
|
||||
networks:
|
||||
- jeecg-boot
|
||||
|
||||
jeecg-boot-pgvector:
|
||||
image: registry.cn-hangzhou.aliyuncs.com/jeecgdocker/pgvector
|
||||
container_name: jeecg-boot-pgvector
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: vector_db
|
||||
ports:
|
||||
- 5432:5432
|
||||
restart: always
|
||||
networks:
|
||||
- jeecg-boot
|
||||
|
||||
jeecg-boot-system:
|
||||
build:
|
||||
context: ./jeecg-boot/jeecg-module-system/jeecg-system-start
|
||||
|
||||
1
jeecg-boot/.gitignore
vendored
1
jeecg-boot/.gitignore
vendored
@ -13,3 +13,4 @@ os_del.cmd
|
||||
os_del_doc.cmd
|
||||
.svn
|
||||
derby.log
|
||||
*.log
|
||||
@ -2,12 +2,12 @@
|
||||
JeecgBoot 低代码开发平台
|
||||
===============
|
||||
|
||||
当前最新版本: 3.8.3(发布日期:2025-10-09)
|
||||
当前最新版本: 3.8.0(发布日期:2025-05-16)
|
||||
|
||||
|
||||
[](https://github.com/zhangdaiscott/jeecg-boot/blob/master/LICENSE)
|
||||
[](http://jeecg.com/aboutusIndex)
|
||||
[](https://github.com/zhangdaiscott/jeecg-boot)
|
||||
[](https://github.com/zhangdaiscott/jeecg-boot)
|
||||
[](https://github.com/zhangdaiscott/jeecg-boot)
|
||||
[](https://github.com/zhangdaiscott/jeecg-boot)
|
||||
|
||||
@ -16,127 +16,43 @@ JeecgBoot 低代码开发平台
|
||||
项目介绍
|
||||
-----------------------------------
|
||||
|
||||
<h3 align="center">企业级AI低代码平台</h3>
|
||||
|
||||
JeecgBoot 是一款基于BPM流程和代码生成的AI低代码平台,助力企业快速实现低代码开发和构建AI应用。
|
||||
采用前后端分离架构(Ant Design&Vue3,SpringBoot3,SpringCloud Alibaba,Mybatis-plus),强大代码生成器实现前后端一键生成,无需手写代码。
|
||||
平台引领AI低代码开发模式:AI生成→在线编码→代码生成→手工合并,解决Java项目80%重复工作,提升效率,节省成本,兼顾灵活性。
|
||||
具备强大且颗粒化的权限控制,支持按钮权限和数据权限设置,满足大型业务系统需求。功能涵盖在线表单、表单设计、流程设计、门户设计、报表与大屏设计、OA办公、AI应用、AI知识库、大模型管理、AI流程编排、AI聊天,支持ChatGPT、DeepSeek、Ollama等多种AI大模型。
|
||||
|
||||
`AI赋能报表:` 积木报表是一款自主研发的强大开源企业级Web报表与大屏工具。它通过零编码的拖拽式操作,赋能用户如同搭积木般轻松构建各类复杂报表和数据大屏,全面满足企业数据可视化与分析需求,助力企业级数据产品的高效打造与应用。
|
||||
|
||||
`AI赋能低代码:` 提供完善成熟的AI应用平台,涵盖AI应用管理、AI模型管理、智能对话助手、知识库问答、流程编排与设计器、AI建表等多项功能。平台兼容多种主流大模型,包括ChatGPT、DeepSeek、Ollama、智普、千问等,助力企业高效构建智能化应用,推动低代码开发与AI深度融合。
|
||||
|
||||
`JEECG宗旨是:` JEECG旨在通过OnlineCoding平台实现简单功能的零代码快速搭建,同时针对复杂功能采用代码生成器生成代码并手工合并,打造智能且灵活的低代码开发模式,有效解决了当前低代码产品普遍缺乏灵活性的问题,提升开发效率的同时兼顾系统的扩展性和定制化能力。
|
||||
|
||||
`JEECG业务流程:` JEECG业务流程采用BPM工作流引擎实现业务审批,扩展任务接口供开发人员编写业务逻辑,表单提供表单设计器、在线配置表单和编码表单等多种解决方案。通过流程与表单的分离设计(松耦合)及任务节点的灵活配置,既保障了企业流程的安全性与保密性,又大幅降低了开发人员的工作量。
|
||||
|
||||
|
||||
适用项目
|
||||
-----------------------------------
|
||||
JeecgBoot低代码平台兼容所有J2EE项目开发,支持信创国产化,特别适用于SAAS、企业信息管理系统(MIS)、内部办公系统(OA)、企业资源计划系统(ERP)、客户关系管理系统(CRM)及AI知识库等场景。其半智能手工Merge开发模式,可显著提升70%以上的开发效率,极大降低开发成本。同时,JeecgBoot还是一款全栈式AI开发平台,助力企业快速构建和部署个性化AI应用。。
|
||||
|
||||
|
||||
**信创兼容说明**
|
||||
- 操作系统:国产麒麟、银河麒麟等国产系统几乎都是基于 Linux 内核,因此它们具有良好的兼容性。
|
||||
- 数据库:达梦、人大金仓、TiDB
|
||||
- 中间件:东方通 TongWeb、TongRDS,宝兰德 AppServer、CacheDB, [信创配置文档](https://help.jeecg.com/java/tongweb-deploy/)
|
||||
|
||||
<h3 align="center">Java Low Code Platform for Enterprise web applications</h3>
|
||||
|
||||
JeecgBoot 是一款基于代码生成器的`低代码开发平台`!前后端分离架构 SpringBoot2.x和3.x,SpringCloud,Ant Design Vue3,Mybatis-plus,Shiro,JWT,支持微服务。强大的代码生成器让前后端代码一键生成,实现低代码开发! JeecgBoot 引领新的低代码开发模式(OnlineCoding-> 代码生成器-> 手工MERGE), 帮助解决Java项目70%的重复工作,让开发更多关注业务。既能快速提高效率,节省研发成本,同时又不失灵活性!
|
||||
|
||||
|
||||
#### 项目说明
|
||||
|
||||
| 项目名 | 说明 |
|
||||
|--------------------|------------------------------------|
|
||||
| `jeecg-boot` | 后端源码JAVA(SpringBoot3微服务架构) |
|
||||
| `jeecgboot-vue3` | 前端源码VUE3(vue3+vite6+antd4+ts最新技术栈) |
|
||||
| 项目名 | 说明 |
|
||||
|--------------------|------------------------|
|
||||
| `jeecg-boot` | 后端源码JAVA(SpringBoot微服务架构) |
|
||||
| `jeecgboot-vue3` | 前端源码VUE3(vue3+vite5+ts最新技术栈) |
|
||||
|
||||
|
||||
|
||||
启动项目
|
||||
-----------------------------------
|
||||
|
||||
> 默认账号密码: admin/123456
|
||||
|
||||
- [开发环境搭建](https://help.jeecg.com/java/setup/tools)
|
||||
- [IDEA启动前后端(单体模式)](https://help.jeecg.com/java/setup/idea/startup)
|
||||
- [Docker一键启动(单体模式)](https://help.jeecg.com/java/docker/quick)
|
||||
- [IDEA启动前后端(微服务方式)](https://help.jeecg.com/java/springcloud/switchcloud/monomer)
|
||||
- [Docker一键启动(微服务方式)](https://help.jeecg.com/java/docker/quickcloud)
|
||||
|
||||
|
||||
技术文档
|
||||
-----------------------------------
|
||||
|
||||
- 官方网站: [http://www.jeecg.com](http://www.jeecg.com)
|
||||
- 在线演示: [平台演示](https://boot3.jeecg.com) | [APP演示](https://jeecg.com/appIndex)
|
||||
- 入门指南: [快速入门](http://www.jeecg.com/doc/quickstart) | [代码生成使用](https://help.jeecg.com/java/codegen/online) | [开发文档](https://help.jeecg.com) | [AI应用手册](https://help.jeecg.com/aigc) | [视频教程](http://jeecg.com/doc/video)
|
||||
- 技术支持: [反馈问题](https://github.com/jeecgboot/JeecgBoot/issues/new?template=bug_report.md) | [低代码体验一分钟](https://jeecg.blog.csdn.net/article/details/106079007)
|
||||
- QQ交流群 : 964611995、⑩716488839(满)、⑨808791225(满)、其他(满)
|
||||
- 新手指南: [快速入门](http://www.jeecg.com/doc/quickstart)
|
||||
- QQ交流群 : ⑩716488839、⑨808791225、其他(满)
|
||||
- 在线演示 : [在线演示](http://boot3.jeecg.com) | [APP演示](http://jeecg.com/appIndex)
|
||||
> 演示系统的登录账号密码,请点击 [获取账号密码](http://jeecg.com/doc/demo) 获取
|
||||
|
||||
|
||||
AI 应用平台介绍
|
||||
|
||||
启动项目
|
||||
-----------------------------------
|
||||
|
||||
一个全栈式 AI 开发平台,旨在帮助开发者快速构建和部署个性化的 AI 应用。
|
||||
|
||||
JeecgBoot平台提供了一套完善的AI应用管理系统模块,是一套类似`Dify`的`AIGC应用开发平台`+`知识库问答`,是一款基于LLM大语言模型AI应用平台和 RAG 的知识库问答系统。
|
||||
其直观的界面结合了 AI 流程编排、RAG 管道、知识库管理、模型管理、对接向量库、实时运行可观察等,让您可以快速从原型到生产,拥有AI服务能力。
|
||||
|
||||
- [详细专题介绍,请点击查看](README-AI.md)
|
||||
|
||||
- AI视频介绍
|
||||
|
||||
[](https://www.bilibili.com/video/BV1zmd7YFE4w)
|
||||
- [IDEA启动前后端项目](https://help.jeecg.com/java/setup/idea/startup)
|
||||
- [Docker一键启动前后端](https://help.jeecg.com/java/docker/quick)
|
||||
|
||||
|
||||
为什么选择JeecgBoot?
|
||||
微服务启动
|
||||
-----------------------------------
|
||||
- 1.采用最新主流前后分离框架(Spring Boot3 + MyBatis + Shiro/SpringAuthorizationServer + Ant Design4 + Vue3),容易上手;代码生成器依赖性低,灵活的扩展能力,可快速实现二次开发。
|
||||
- 2.前端大版本换代,最新版采用 Vue3.0 + TypeScript + Vite6 + Ant Design Vue4 等新技术方案。
|
||||
- 3.支持微服务Spring Cloud Alibaba(Nacos、Gateway、Sentinel、Skywalking),提供简易机制,支持单体和微服务自由切换(这样可以满足各类项目需求)。
|
||||
- 4.开发效率高,支持在线建表和AI建表,提供强大代码生成器,单表、树列表、一对多、一对一等数据模型,增删改查功能一键生成,菜单配置直接使用。
|
||||
- 5.代码生成器提供强大模板机制,支持自定义模板,目前提供四套风格模板(单表两套、树模型一套、一对多三套)。
|
||||
- 6.提供强大的报表和大屏可视化工具,支持丰富的数据源连接,能够通过拖拉拽方式快速制作报表、大屏和门户设计;支持多种图表类型:柱形图、折线图、散点图、饼图、环形图、面积图、漏斗图、进度图、仪表盘、雷达图、地图等。
|
||||
- 7.低代码能力:在线表单(无需编码,通过在线配置表单,实现表单的增删改查,支持单表、树、一对多、一对一等模型,实现人人皆可编码),在线配置零代码开发、所见即所得支持23种类控件。
|
||||
- 8.低代码能力:在线报表、在线图表(无需编码,通过在线配置方式,实现数据报表和图形报表,可以快速抽取数据,减轻开发压力,实现人人皆可编码)。
|
||||
- 9.Online支持在线增强开发,提供在线代码编辑器,支持代码高亮、代码提示等功能,支持多种语言(Java、SQL、JavaScript等)。
|
||||
- 10.封装完善的用户、角色、菜单、组织机构、数据字典、在线定时任务等基础功能,支持访问授权、按钮权限、数据权限等功能。
|
||||
- 11.前端UI提供丰富的组件库,支持各种常用组件,如表格、树形控件、下拉框、日期选择器等,满足各种复杂的业务需求 [UI组件库文档](https://help.jeecg.com/category/ui%E7%BB%84%E4%BB%B6%E5%BA%93)。
|
||||
- 12.提供APP配套框架,一份多代码多终端适配,一份代码多终端适配,小程序、H5、安卓、iOS、鸿蒙Next。
|
||||
- 13.新版APP框架采用Uniapp、Vue3.0、Vite、Wot-design-uni、TypeScript等最新技术栈,包括二次封装组件、路由拦截、请求拦截等功能。实现了与JeecgBoot完美对接:目前已经实现登录、用户信息、通讯录、公告、移动首页、九宫格、聊天、Online表单、仪表盘等功能,提供了丰富的组件。
|
||||
- 14.提供了一套成熟的AI应用平台功能,从AI模型、知识库到AI应用搭建,助力企业快速落地AI服务,加速智能化升级。
|
||||
- 15.AI能力:目前JeecgBoot支持AI大模型chatgpt和deepseek,现在最新版默认使用deepseek,速度更快质量更高。目前提供了AI对话助手、AI知识库、AI应用、AI建表、AI报表等功能。
|
||||
- 16.提供新行编辑表格JVXETable,轻松满足各种复杂ERP布局,拥有更高的性能、更灵活的扩展、更强大的功能。
|
||||
- 17.平台首页风格,提供多种组合模式,支持自定义风格;支持门户设计,支持自定义首页。
|
||||
- 18.常用共通封装,各种工具类(定时任务、短信接口、邮件发送、Excel导入导出等),基本满足80%项目需求。
|
||||
- 19.简易Excel导入导出,支持单表导出和一对多表模式导出,生成的代码自带导入导出功能。
|
||||
- 20.集成智能报表工具,报表打印、图像报表和数据导出非常方便,可极其方便地生成PDF、Excel、Word等报表。
|
||||
- 21.采用前后分离技术,页面UI风格精美,针对常用组件做了封装:时间、行表格控件、截取显示控件、报表组件、编辑器等。
|
||||
- 22.查询过滤器:查询功能自动生成,后台动态拼SQL追加查询条件;支持多种匹配方式(全匹配/模糊查询/包含查询/不匹配查询)。
|
||||
- 23.数据权限(精细化数据权限控制,控制到行级、列表级、表单字段级,实现不同人看不同数据,不同人对同一个页面操作不同字段)。
|
||||
- 24.接口安全机制,可细化控制接口授权,非常简便实现不同客户端只看自己数据等控制;也提供了基于AK和SK认证鉴权的OpenAPI功能。
|
||||
- 25.活跃的社区支持;近年来,随着网络威胁的日益增加,团队在安全和漏洞管理方面积累了丰富的经验,能够为企业提供全面的安全解决方案。
|
||||
- 26.权限控制采用RBAC(Role-Based Access Control,基于角色的访问控制)。
|
||||
- 27.页面校验自动生成(必须输入、数字校验、金额校验、时间空间等)。
|
||||
- 28.支持SaaS服务模式,提供SaaS多租户架构方案。
|
||||
- 29.分布式文件服务,集成MinIO、阿里OSS等优秀的第三方,提供便捷的文件上传与管理,同时也支持本地存储。
|
||||
- 30.主流数据库兼容,一套代码完全兼容MySQL、PostgreSQL、Oracle、SQL Server、MariaDB、达梦、人大金仓等主流数据库。
|
||||
- 31.集成工作流Flowable,并实现了只需在页面配置流程转向,可极大简化BPM工作流的开发;用BPM的流程设计器画出了流程走向,一个工作流基本就完成了,只需写很少量的Java代码。
|
||||
- 32.低代码能力:在线流程设计,采用开源Flowable流程引擎,实现在线画流程、自定义表单、表单挂靠、业务流转。
|
||||
- 33.多数据源:极其简易的使用方式,在线配置数据源配置,便捷地从其他数据抓取数据。
|
||||
- 34.提供单点登录CAS集成方案,项目中已经提供完善的对接代码。
|
||||
- 35.低代码能力:表单设计器,支持用户自定义表单布局,支持单表、一对多表单,支持select、radio、checkbox、textarea、date、popup、列表、宏等控件。
|
||||
- 36.专业接口对接机制,统一采用RESTful接口方式,集成Swagger-UI在线接口文档,JWT token安全验证,方便客户端对接。
|
||||
- 37.高级组合查询功能,在线配置支持主子表关联查询,可保存查询历史。
|
||||
- 38.提供各种系统监控,实时跟踪系统运行情况(监控Redis、Tomcat、JVM、服务器信息、请求追踪、SQL监控)。
|
||||
- 39.消息中心(支持短信、邮件、微信推送等);集成WebSocket消息通知机制。
|
||||
- 40.支持多语言,提供国际化方案。
|
||||
- 41.数据变更记录日志,可记录数据每次变更内容,通过版本对比功能查看历史变化。
|
||||
- 42.提供简单易用的打印插件,支持谷歌、火狐、IE11+等各种浏览器。
|
||||
- 43.后端采用Maven分模块开发方式;前端支持菜单动态路由。
|
||||
- 44.提供丰富的示例代码,涵盖了常用的业务场景,便于学习和参考。
|
||||
- [单体快速切换微服务](https://help.jeecg.com/java/springcloud/switchcloud/monomer)
|
||||
- [Docker启动微服务后台](https://help.jeecg.com/java/docker/springcloud)
|
||||
|
||||
|
||||
|
||||
技术架构:
|
||||
@ -145,33 +61,28 @@ JeecgBoot平台提供了一套完善的AI应用管理系统模块,是一套类
|
||||
#### 后端
|
||||
|
||||
- IDE建议: IDEA (必须安装lombok插件 )
|
||||
- 语言:Java 默认jdk17(jdk21、jdk24)
|
||||
- 语言:Java 8+ (支持17)
|
||||
- 依赖管理:Maven
|
||||
- 基础框架:Spring Boot 3.5.5
|
||||
- 微服务框架: Spring Cloud Alibaba 2023.0.3.3
|
||||
- 持久层框架:MybatisPlus 3.5.12
|
||||
- 报表工具: JimuReport 2.1.3
|
||||
- 安全框架:Apache Shiro 2.0.4,Jwt 4.5.0
|
||||
- 基础框架:Spring Boot 2.7.18
|
||||
- 微服务框架: Spring Cloud Alibaba 2021.0.1.0
|
||||
- 持久层框架:MybatisPlus 3.5.3.2
|
||||
- 报表工具: JimuReport 1.9.4
|
||||
- 安全框架:Apache Shiro 1.12.0,Jwt 3.11.0
|
||||
- 微服务技术栈:Spring Cloud Alibaba、Nacos、Gateway、Sentinel、Skywalking
|
||||
- 数据库连接池:阿里巴巴Druid 1.2.24
|
||||
- AI大模型:支持 `ChatGPT` `DeepSeek` `千问`等各种常规模式
|
||||
- 数据库连接池:阿里巴巴Druid 1.1.24
|
||||
- 日志打印:logback
|
||||
- 缓存:Redis
|
||||
- 其他:autopoi, fastjson,poi,Swagger-ui,quartz, lombok(简化代码)等。
|
||||
- 默认提供MySQL5.7+数据库脚本
|
||||
- 默认数据库脚本:MySQL5.7+
|
||||
- [其他数据库,需要自己转](https://my.oschina.net/jeecg/blog/4905722)
|
||||
|
||||
|
||||
#### 前端
|
||||
|
||||
- 前端环境要求:Node.js要求`Node 20+` 版本以上、pnpm 要求`9+` 版本以上
|
||||
` ( Vite 不再支持已结束生命周期(EOL)的 Node.js 18。现在需要使用 Node.js 20.19+ 或 22.12+)`
|
||||
|
||||
- 前端IDE建议:WebStorm、Vscode
|
||||
- 采用 Vue3.0+TypeScript+Vite+Ant-Design-Vue等新技术方案,包括二次封装组件、utils、hooks、动态菜单、权限校验、按钮级别权限控制等功能
|
||||
- 最新技术栈:Vue3.0 + TypeScript + Vite5 + ant-design-vue4 + pinia + echarts + unocss + vxe-table + qiankun + es6
|
||||
- 依赖管理:node、npm、pnpm
|
||||
- 前端IDE建议:IDEA、WebStorm、Vscode
|
||||
- 采用 Vue3.0+TypeScript+Vite6+Ant-Design-Vue4等新技术方案,包括二次封装组件、utils、hooks、动态菜单、权限校验、按钮级别权限控制等功能
|
||||
- 最新技术栈:Vue3.0 + TypeScript + Vite6 + ant-design-vue4 + pinia + echarts + unocss + vxe-table + qiankun + es6
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -1,368 +0,0 @@
|
||||
# `Shiro 到 Sa-Token 迁移指南`
|
||||
|
||||
本项目已从 **Apache Shiro 2.0.4** 迁移到 **Sa-Token 1.44.0**,采用 JWT-Simple 模式,完全兼容原 JWT token 格式。
|
||||
|
||||
---
|
||||
|
||||
## 📦 1. 依赖配置
|
||||
|
||||
### 1.1 Maven 依赖
|
||||
|
||||
移除 Shiro 相关依赖,新增:
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>cn.dev33</groupId>
|
||||
<artifactId>sa-token-spring-boot3-starter</artifactId>
|
||||
<version>1.44.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.dev33</groupId>
|
||||
<artifactId>sa-token-redis-jackson</artifactId>
|
||||
<version>1.44.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.dev33</groupId>
|
||||
<artifactId>sa-token-jwt</artifactId>
|
||||
<version>1.44.0</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
### 1.2 配置文件(application.yml)
|
||||
|
||||
```yaml
|
||||
sa-token:
|
||||
token-name: X-Access-Token
|
||||
timeout: 2592000 # token有效期30天
|
||||
is-concurrent: true # 允许同账号并发登录
|
||||
token-style: jwt-simple # JWT模式(兼容原格式)
|
||||
jwt-secret-key: "your-secret-key-here"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💡 2. 核心代码实现
|
||||
|
||||
### 2.1 登录逻辑(⚠️ 使用 username 作为 loginId)
|
||||
|
||||
```java
|
||||
// 从数据库查询用户信息
|
||||
SysUser sysUser = userService.getUserByUsername(username);
|
||||
|
||||
// 执行登录(自动完成:Sa-Token登录 + 存储Session + 返回token)
|
||||
String token = LoginUserUtils.doLogin(sysUser);
|
||||
|
||||
// 返回token给前端
|
||||
return Result.ok(token);
|
||||
```
|
||||
|
||||
**💡 设计说明:**
|
||||
- `doLogin()` 方法自动完成:
|
||||
1. 调用 `StpUtil.login(username)` (使用 username 而非 userId)
|
||||
2. 调用 `setSessionUser()` 存储用户信息(自动清除 password 等15个字段)
|
||||
3. 返回生成的 token
|
||||
- 减少 Redis 存储约 50%,密码不再存储到 Session
|
||||
|
||||
### 2.2 权限认证接口(⚠️ 必须手动实现缓存)
|
||||
|
||||
```java
|
||||
@Component
|
||||
public class StpInterfaceImpl implements StpInterface {
|
||||
|
||||
@Lazy @Resource
|
||||
private CommonAPI commonApi;
|
||||
|
||||
private static final long CACHE_TIMEOUT = 60 * 60 * 24 * 30; // 30天
|
||||
private static final String PERMISSION_CACHE_PREFIX = "satoken:user-permission:";
|
||||
private static final String ROLE_CACHE_PREFIX = "satoken:user-role:";
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<String> getPermissionList(Object loginId, String loginType) {
|
||||
String username = loginId.toString();
|
||||
String cacheKey = PERMISSION_CACHE_PREFIX + username;
|
||||
SaTokenDao dao = SaManager.getSaTokenDao();
|
||||
|
||||
// 1. 先从缓存获取
|
||||
List<String> permissionList = (List<String>) dao.getObject(cacheKey);
|
||||
|
||||
if (permissionList == null) {
|
||||
// 2. 缓存未命中,查询数据库
|
||||
log.warn("权限缓存未命中,查询数据库 [ username={} ]", username);
|
||||
|
||||
String userId = commonApi.getUserIdByName(username);
|
||||
Set<String> permissionSet = commonApi.queryUserAuths(userId);
|
||||
permissionList = new ArrayList<>(permissionSet);
|
||||
|
||||
// 3. 将结果缓存起来
|
||||
dao.setObject(cacheKey, permissionList, CACHE_TIMEOUT);
|
||||
}
|
||||
|
||||
return permissionList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getRoleList(Object loginId, String loginType) {
|
||||
// 实现类似 getPermissionList(),使用 ROLE_CACHE_PREFIX
|
||||
// 详见:StpInterfaceImpl.java
|
||||
}
|
||||
|
||||
// 清除缓存的静态方法
|
||||
public static void clearUserCache(List<String> usernameList) {
|
||||
SaTokenDao dao = SaManager.getSaTokenDao();
|
||||
for (String username : usernameList) {
|
||||
dao.deleteObject(PERMISSION_CACHE_PREFIX + username);
|
||||
dao.deleteObject(ROLE_CACHE_PREFIX + username);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**⚠️ 关键:** Sa-Token 的 `StpInterface` **不提供自动缓存**,必须手动实现,否则每次请求都会查询数据库!
|
||||
|
||||
### 2.3 Filter 配置(支持 URL 参数传递 token)
|
||||
|
||||
```java
|
||||
@Bean
|
||||
@Primary
|
||||
public StpLogic getStpLogicJwt() {
|
||||
return new StpLogicJwtForSimple() {
|
||||
@Override
|
||||
public String getTokenValue() {
|
||||
SaRequest request = SaHolder.getRequest();
|
||||
|
||||
// 优先级:Header > URL参数"token" > URL参数"X-Access-Token"
|
||||
String tokenValue = request.getHeader(getConfigOrGlobal().getTokenName());
|
||||
if (isEmpty(tokenValue)) {
|
||||
tokenValue = request.getParam("token"); // 兼容 WebSocket、积木报表
|
||||
}
|
||||
if (isEmpty(tokenValue)) {
|
||||
tokenValue = request.getParam(getConfigOrGlobal().getTokenName());
|
||||
}
|
||||
|
||||
return isEmpty(tokenValue) ? super.getTokenValue() : tokenValue;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SaServletFilter getSaServletFilter() {
|
||||
return new SaServletFilter()
|
||||
.addInclude("/**")
|
||||
.setExcludeList(getExcludeUrls()) // 排除登录、静态资源等
|
||||
.setAuth(obj -> {
|
||||
// 检查是否是免认证路径
|
||||
String servletPath = SaHolder.getRequest().getRequestPath();
|
||||
if (InMemoryIgnoreAuth.contains(servletPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ⚠️ 关键:如果请求带 token,先切换到对应的登录会话
|
||||
try {
|
||||
String token = StpUtil.getTokenValue();
|
||||
if (isNotEmpty(token)) {
|
||||
Object loginId = StpUtil.getLoginIdByToken(token);
|
||||
if (loginId != null) {
|
||||
StpUtil.switchTo(loginId); // 切换登录会话
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("切换登录会话失败: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// 最终校验登录状态
|
||||
StpUtil.checkLogin();
|
||||
})
|
||||
.setError(e -> {
|
||||
// 返回401 JSON响应
|
||||
SaHolder.getResponse()
|
||||
.setStatus(401)
|
||||
.setHeader("Content-Type", "application/json;charset=UTF-8");
|
||||
return JwtUtil.responseErrorJson(401, "Token失效,请重新登录!");
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### 2.4 全局异常处理
|
||||
|
||||
```java
|
||||
@ExceptionHandler(NotLoginException.class)
|
||||
public Result<?> handleNotLoginException(NotLoginException e) {
|
||||
log.warn("用户未登录或Token失效: {}", e.getMessage());
|
||||
return Result.error(401, "Token失效,请重新登录!");
|
||||
}
|
||||
|
||||
@ExceptionHandler(NotPermissionException.class)
|
||||
public Result<?> handleNotPermissionException(NotPermissionException e) {
|
||||
log.warn("权限不足: {}", e.getMessage());
|
||||
return Result.error(403, "用户权限不足,无法访问!");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 3. API 迁移对照表
|
||||
|
||||
### 3.1 注解替换
|
||||
|
||||
| Shiro | Sa-Token | 说明 |
|
||||
|-------|----------|------|
|
||||
| `@RequiresPermissions("user:add")` | `@SaCheckPermission("user:add")` | 权限校验 |
|
||||
| `@RequiresRoles("admin")` | `@SaCheckRole("admin")` | 角色校验 |
|
||||
|
||||
### 3.2 API 替换
|
||||
|
||||
| Shiro | Sa-Token | 说明 |
|
||||
|-------|----------|------|
|
||||
| `SecurityUtils.getSubject().getPrincipal()` | `LoginUserUtils.getSessionUser()` | 获取登录用户 |
|
||||
| `Subject.login(token)` | `LoginUserUtils.doLogin(sysUser)` | 登录(推荐) |
|
||||
| `Subject.login(token)` | `StpUtil.login(username)` | 登录(底层API) |
|
||||
| `Subject.logout()` | `StpUtil.logout()` | 退出登录 |
|
||||
| `Subject.isAuthenticated()` | `StpUtil.isLogin()` | 判断是否登录 |
|
||||
| `Subject.hasRole("admin")` | `StpUtil.hasRole("admin")` | 判断角色 |
|
||||
| `Subject.isPermitted("user:add")` | `StpUtil.hasPermission("user:add")` | 判断权限 |
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 4. 重要特性说明
|
||||
|
||||
### 4.1 JWT-Simple 模式特性
|
||||
|
||||
- ✅ **生成标准 JWT token**:与原 Shiro JWT 格式完全兼容
|
||||
- ✅ **仍然检查 Redis Session**:支持强制退出(与纯 JWT 无状态模式不同)
|
||||
- ✅ **支持 URL 参数传递**:兼容 WebSocket、积木报表等场景
|
||||
- ⚠️ **非完全无状态**:依赖 Redis 存储会话和权限缓存
|
||||
|
||||
### 4.2 Session 数据优化
|
||||
|
||||
`LoginUserUtils.setSessionUser()` 会自动清除以下字段:
|
||||
|
||||
```
|
||||
password, workNo, birthday, sex, email, phone, status,
|
||||
delFlag, activitiSync, createTime, userIdentity, post,
|
||||
telephone, clientId, mainDepPostId
|
||||
```
|
||||
|
||||
**优势:**
|
||||
- 减少 Redis 存储约 **50%**
|
||||
- 密码不再存储在 Session 中,**安全性提升**
|
||||
|
||||
### 4.3 权限缓存动态更新
|
||||
|
||||
修改角色权限后,系统会自动清除受影响用户的权限缓存:
|
||||
|
||||
```java
|
||||
// SysPermissionController.saveRolePermission() 中
|
||||
@RequestMapping(value = "/saveRolePermission", method = RequestMethod.POST)
|
||||
public Result<String> saveRolePermission(@RequestBody JSONObject json) {
|
||||
String roleId = json.getString("roleId");
|
||||
String permissionIds = json.getString("permissionIds");
|
||||
String lastPermissionIds = json.getString("lastpermissionIds");
|
||||
|
||||
// 保存角色权限关系
|
||||
sysRolePermissionService.saveRolePermission(roleId, permissionIds, lastPermissionIds);
|
||||
|
||||
// ⚠️ 关键:清除拥有该角色的所有用户的权限缓存
|
||||
clearRolePermissionCache(roleId);
|
||||
|
||||
return Result.ok("保存成功!");
|
||||
}
|
||||
|
||||
// 实现:查询该角色下的所有用户,批量清除缓存
|
||||
private void clearRolePermissionCache(String roleId) {
|
||||
List<String> usernameList = new ArrayList<>();
|
||||
|
||||
// 分页查询拥有该角色的用户
|
||||
int pageNo = 1, pageSize = 100;
|
||||
while (true) {
|
||||
Page<SysUser> page = new Page<>(pageNo, pageSize);
|
||||
IPage<SysUser> userPage = sysUserService.getUserByRoleId(page, roleId, null, null);
|
||||
|
||||
if (userPage.getRecords().isEmpty()) break;
|
||||
|
||||
for (SysUser user : userPage.getRecords()) {
|
||||
usernameList.add(user.getUsername());
|
||||
}
|
||||
|
||||
if (pageNo >= userPage.getPages()) break;
|
||||
pageNo++;
|
||||
}
|
||||
|
||||
// 批量清除用户权限和角色缓存
|
||||
if (!usernameList.isEmpty()) {
|
||||
StpInterfaceImpl.clearUserCache(usernameList);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**结果:** 权限变更立即生效,用户无需重新登录。
|
||||
|
||||
|
||||
## ✅ 6. 测试清单
|
||||
|
||||
### 6.1 登录功能测试
|
||||
|
||||
| 测试项 | 测试状态 | 说明 |
|
||||
|--------|---------|------|
|
||||
| 账号密码登录 | ✅ 通过 | 验证 `/sys/login` 接口 |
|
||||
| 手机号登录 | ✅ 通过 | 验证 `/sys/phoneLogin` 接口 |
|
||||
| APP 登录 | ✅ 通过 | 验证 APP 端登录流程 |
|
||||
| 扫码登录 | ✅ 通过 | 验证二维码扫码登录 |
|
||||
| 第三方登录 | ⏳ 待测试 | 微信、QQ 等第三方登录 |
|
||||
| 钉钉 OAuth2.0 登录 | ⏳ 待测试 | 钉钉授权登录流程 |
|
||||
| 企业微信 OAuth2.0 登录 | ⏳ 待测试 | 企业微信授权登录流程 |
|
||||
| CAS 单点登录 | ⏳ 待测试 | CAS 单点登录集成 |
|
||||
|
||||
### 6.2 核心功能测试
|
||||
|
||||
| 测试项 | 测试状态 | 说明 |
|
||||
|--------|---------|------|
|
||||
| Token 权限拦截 | ✅ 通过 | 无 token 或失效 token 返回 401 |
|
||||
| 权限注解 `@SaCheckPermission` | ✅ 通过 | 无权限返回 403 |
|
||||
| 角色注解 `@SaCheckRole` | ✅ 通过 | 无角色返回 403 |
|
||||
| `@IgnoreAuth` 免认证 | ✅ 通过 | 无 token 也能正常访问 |
|
||||
| 自动续期(操作不掉线) | ✅ 通过 | 活跃用户 token 自动续期 |
|
||||
| 用户权限变更即刻生效 | ✅ 通过 | 修改角色权限后无需重新登录 |
|
||||
| 积木报表 token 参数模式 | ✅ 通过 | `/jmreport/**?token=xxx` 正常访问 |
|
||||
|
||||
### 6.3 异步和网关测试
|
||||
|
||||
| 测试项 | 测试状态 | 说明 |
|
||||
|--------|---------|------|
|
||||
| 异步接口(`@Async`) | ❌ 有问题 | **需排查:异步线程中获取登录用户失败** |
|
||||
| Gateway 模式权限验证 | ⏳ 待测试 | 网关模式下的权限拦截 |
|
||||
|
||||
### 6.4 多租户测试
|
||||
|
||||
| 测试项 | 测试状态 | 说明 |
|
||||
|--------|---------|------|
|
||||
| 租户 ID 校验 | ⚠️ 缺失 | **需补充:校验用户 tenant_id 和前端传参一致性** |
|
||||
|
||||
### 6.5 测试说明
|
||||
|
||||
**✅ 通过** - 功能正常,符合预期
|
||||
**❌ 有问题** - 功能异常,需要修复
|
||||
**⏳ 待测试** - 尚未测试
|
||||
**⚠️ 缺失** - 功能缺失,需要补充
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 📊 7. 迁移总结
|
||||
|
||||
| 优化项 | 说明 | 收益 |
|
||||
|--------|------|------|
|
||||
| **loginId 设计** | 使用 `username` 而非 `userId` | 语义清晰,与业务逻辑一致 |
|
||||
| **Session 优化** | 清除 15 个不必要字段 | Redis 存储减少 50%,安全性提升 |
|
||||
| **权限缓存** | 手动实现 30 天缓存 | 性能提升 99%,降低 DB 压力 |
|
||||
| **权限实时更新** | 角色权限修改后自动清除缓存 | 无需重新登录即生效 |
|
||||
| **URL Token 支持** | Filter 中实现 `switchTo` | 兼容 WebSocket、积木报表等场景 |
|
||||
| **JWT 兼容** | JWT-Simple 模式 | 完全兼容原 JWT token 格式 |
|
||||
|
||||
---
|
||||
|
||||
## 📚 参考资料
|
||||
|
||||
- [Sa-Token 官方文档](https://sa-token.cc/)
|
||||
- [Sa-Token JWT-Simple 模式](https://sa-token.cc/doc.html#/plugin/jwt-extend)
|
||||
- [Sa-Token 权限缓存最佳实践](https://sa-token.cc/doc.html#/fun/jur-cache)
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -1,5 +1,5 @@
|
||||
#
|
||||
# XXL-JOB v2.4.0
|
||||
# XXL-JOB v2.2.0
|
||||
# Copyright (c) 2015-present, xuxueli.
|
||||
|
||||
CREATE database if NOT EXISTS `xxl_job` default character set utf8mb4 collate utf8mb4_general_ci;
|
||||
|
||||
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -1,5 +0,0 @@
|
||||
oracle导出编码: export NLS_LANG=AMERICAN_AMERICA.ZHS16GBK
|
||||
|
||||
导出用户: jeecgbootos
|
||||
|
||||
导入命令: imp scott/tiger@orcl file=jeecgboot-oracle11g.dmp
|
||||
@ -22,22 +22,22 @@ SET FOREIGN_KEY_CHECKS = 0;
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `open_api`;
|
||||
CREATE TABLE `open_api` (
|
||||
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '接口名称',
|
||||
`request_method` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '请求方法',
|
||||
`request_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '接口地址',
|
||||
`black_list` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'IP 黑名单',
|
||||
`body` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '请求体内容',
|
||||
`origin_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '原始地址',
|
||||
`status` int(10) NULL DEFAULT NULL COMMENT '状态',
|
||||
`del_flag` int(10) NULL DEFAULT NULL COMMENT '删除标识',
|
||||
`create_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '创建人',
|
||||
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
|
||||
`update_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '修改人',
|
||||
`update_time` datetime NULL DEFAULT NULL COMMENT '修改时间',
|
||||
`headers_json` json NULL COMMENT '请求头json',
|
||||
`params_json` json NULL COMMENT '请求参数json',
|
||||
PRIMARY KEY (`id`) USING BTREE
|
||||
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '接口名称',
|
||||
`request_method` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '请求方法',
|
||||
`request_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '接口地址',
|
||||
`black_list` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'IP 黑名单',
|
||||
`body` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '请求体内容',
|
||||
`origin_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '原始地址',
|
||||
`status` int(10) NULL DEFAULT NULL COMMENT '状态',
|
||||
`del_flag` int(10) NULL DEFAULT NULL COMMENT '删除标识',
|
||||
`create_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '创建人',
|
||||
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
|
||||
`update_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '修改人',
|
||||
`update_time` datetime NULL DEFAULT NULL COMMENT '修改时间',
|
||||
`headers_json` json NULL COMMENT '请求头json',
|
||||
`params_json` json NULL COMMENT '请求参数json',
|
||||
PRIMARY KEY (`id`) USING BTREE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '接口表' ROW_FORMAT = DYNAMIC;
|
||||
|
||||
-- ----------------------------
|
||||
@ -50,16 +50,16 @@ INSERT INTO `open_api` VALUES ('1922132683346649090', '根据部门查询用户'
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `open_api_auth`;
|
||||
CREATE TABLE `open_api_auth` (
|
||||
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '授权名称',
|
||||
`ak` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'AK',
|
||||
`sk` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'SK',
|
||||
`create_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '创建人',
|
||||
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
|
||||
`update_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '修改人',
|
||||
`update_time` datetime NULL DEFAULT NULL COMMENT '修改时间',
|
||||
`system_user_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '关联系统用户名',
|
||||
PRIMARY KEY (`id`) USING BTREE
|
||||
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '授权名称',
|
||||
`ak` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'AK',
|
||||
`sk` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT 'SK',
|
||||
`create_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '创建人',
|
||||
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
|
||||
`update_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '修改人',
|
||||
`update_time` datetime NULL DEFAULT NULL COMMENT '修改时间',
|
||||
`system_user_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '关联系统用户名',
|
||||
PRIMARY KEY (`id`) USING BTREE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '权限表' ROW_FORMAT = DYNAMIC;
|
||||
|
||||
-- ----------------------------
|
||||
@ -72,13 +72,13 @@ INSERT INTO `open_api_auth` VALUES ('1922164194775056386', 'scott', 'ak-pFjyNHWR
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `open_api_log`;
|
||||
CREATE TABLE `open_api_log` (
|
||||
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`api_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '接口ID',
|
||||
`call_auth_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '调用ID',
|
||||
`call_time` datetime NULL DEFAULT NULL COMMENT '调用时间',
|
||||
`used_time` bigint(20) NULL DEFAULT NULL COMMENT '耗时',
|
||||
`response_time` datetime NULL DEFAULT NULL COMMENT '响应时间',
|
||||
PRIMARY KEY (`id`) USING BTREE
|
||||
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`api_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '接口ID',
|
||||
`call_auth_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '调用ID',
|
||||
`call_time` datetime NULL DEFAULT NULL COMMENT '调用时间',
|
||||
`used_time` bigint(20) NULL DEFAULT NULL COMMENT '耗时',
|
||||
`response_time` datetime NULL DEFAULT NULL COMMENT '响应时间',
|
||||
PRIMARY KEY (`id`) USING BTREE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '调用记录表' ROW_FORMAT = DYNAMIC;
|
||||
|
||||
-- ----------------------------
|
||||
@ -117,14 +117,14 @@ INSERT INTO `open_api_log` VALUES ('1922836856287428610', '1922132683346649090',
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `open_api_permission`;
|
||||
CREATE TABLE `open_api_permission` (
|
||||
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`api_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '接口ID',
|
||||
`api_auth_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '认证ID',
|
||||
`create_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '创建人',
|
||||
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
|
||||
`update_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '更新人',
|
||||
`update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`) USING BTREE
|
||||
`id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
|
||||
`api_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '接口ID',
|
||||
`api_auth_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '认证ID',
|
||||
`create_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '创建人',
|
||||
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
|
||||
`update_by` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '更新人',
|
||||
`update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`) USING BTREE
|
||||
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'openapi授权' ROW_FORMAT = DYNAMIC;
|
||||
|
||||
-- ----------------------------
|
||||
@ -165,4 +165,6 @@ INSERT INTO sys_role_permission (id, role_id, permission_id, data_rule_ids, oper
|
||||
INSERT INTO sys_role_permission (id, role_id, permission_id, data_rule_ids, operate_date, operate_ip) VALUES ('1917881149431058436', 'f6817f48af4fb3af11b9e8bf182f618b', '2025050105554940203', null, '2025-05-01 17:57:53', '0:0:0:0:0:0:0:1');
|
||||
INSERT INTO sys_role_permission (id, role_id, permission_id, data_rule_ids, operate_date, operate_ip) VALUES ('1917881149431058437', 'f6817f48af4fb3af11b9e8bf182f618b', '2025050105554940204', null, '2025-05-01 17:57:53', '0:0:0:0:0:0:0:1');
|
||||
INSERT INTO sys_role_permission (id, role_id, permission_id, data_rule_ids, operate_date, operate_ip) VALUES ('1917881149431058438', 'f6817f48af4fb3af11b9e8bf182f618b', '2025050105554940205', null, '2025-05-01 17:57:53', '0:0:0:0:0:0:0:1');
|
||||
INSERT INTO sys_role_permission (id, role_id, permission_id, data_rule_ids, operate_date, operate_ip) VALUES ('1917881149431058439', 'f6817f48af4fb3af11b9e8bf182f618b', '2025050105554940206', null, '2025-05-01 17:57:53', '0:0:0:0:0:0:0:1');
|
||||
INSERT INTO sys_role_permission (id, role_id, permission_id, data_rule_ids, operate_date, operate_ip) VALUES ('1917881149431058439', 'f6817f48af4fb3af11b9e8bf182f618b', '2025050105554940206', null, '2025-05-01 17:57:53', '0:0:0:0:0:0:0:1');
|
||||
INSERT INTO sys_role_permission (id, role_id, permission_id, data_rule_ids, operate_date, operate_ip) VALUES ('1917957659860963330', 'f6817f48af4fb3af11b9e8bf182f618b', '1917957565728198657', null, '2025-05-01 23:01:55', '0:0:0:0:0:0:0:1');
|
||||
INSERT INTO sys_role_permission (id, role_id, permission_id, data_rule_ids, operate_date, operate_ip) VALUES ('1922109760551858178', 'f6817f48af4fb3af11b9e8bf182f618b', '1922109301837606914', null, '2025-05-13 10:00:53', '0:0:0:0:0:0:0:1');
|
||||
45
jeecg-boot/db/增量SQL/sas升级脚本.sql
Normal file
45
jeecg-boot/db/增量SQL/sas升级脚本.sql
Normal file
@ -0,0 +1,45 @@
|
||||
CREATE TABLE `oauth2_registered_client` (
|
||||
`id` varchar(100) NOT NULL,
|
||||
`client_id` varchar(100) NOT NULL,
|
||||
`client_id_issued_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`client_secret` varchar(200) DEFAULT NULL,
|
||||
`client_secret_expires_at` timestamp NULL DEFAULT NULL,
|
||||
`client_name` varchar(200) NOT NULL,
|
||||
`client_authentication_methods` varchar(1000) NOT NULL,
|
||||
`authorization_grant_types` varchar(1000) NOT NULL,
|
||||
`redirect_uris` varchar(1000) DEFAULT NULL,
|
||||
`post_logout_redirect_uris` varchar(1000) DEFAULT NULL,
|
||||
`scopes` varchar(1000) NOT NULL,
|
||||
`client_settings` varchar(2000) NOT NULL,
|
||||
`token_settings` varchar(2000) NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
INSERT INTO `oauth2_registered_client`
|
||||
(`id`,
|
||||
`client_id`,
|
||||
`client_id_issued_at`,
|
||||
`client_secret`,
|
||||
`client_secret_expires_at`,
|
||||
`client_name`,
|
||||
`client_authentication_methods`,
|
||||
`authorization_grant_types`,
|
||||
`redirect_uris`,
|
||||
`post_logout_redirect_uris`,
|
||||
`scopes`,
|
||||
`client_settings`,
|
||||
`token_settings`)
|
||||
VALUES
|
||||
('3eacac0e-0de9-4727-9a64-6bdd4be2ee1f',
|
||||
'jeecg-client',
|
||||
now(),
|
||||
'secret',
|
||||
null,
|
||||
'3eacac0e-0de9-4727-9a64-6bdd4be2ee1f',
|
||||
'client_secret_basic',
|
||||
'refresh_token,authorization_code,password,app,phone,social',
|
||||
'http://127.0.0.1:8080/jeecg-',
|
||||
'http://127.0.0.1:8080/',
|
||||
'*',
|
||||
'{"@class":"java.util.Collections$UnmodifiableMap","settings.client.require-proof-key":false,"settings.client.require-authorization-consent":true}',
|
||||
'{"@class":"java.util.Collections$UnmodifiableMap","settings.token.reuse-refresh-tokens":true,"settings.token.id-token-signature-algorithm":["org.springframework.security.oauth2.jose.jws.SignatureAlgorithm","RS256"],"settings.token.access-token-time-to-live":["java.time.Duration",300000.000000000],"settings.token.access-token-format":{"@class":"org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat","value":"self-contained"},"settings.token.refresh-token-time-to-live":["java.time.Duration",3600.000000000],"settings.token.authorization-code-time-to-live":["java.time.Duration",300000.000000000],"settings.token.device-code-time-to-live":["java.time.Duration",300000.000000000]}');
|
||||
@ -18,47 +18,20 @@ services:
|
||||
--max_allowed_packet=128M
|
||||
--default-authentication-plugin=caching_sha2_password
|
||||
ports:
|
||||
- 13306:3306
|
||||
- 3306:3306
|
||||
networks:
|
||||
- jeecg-boot
|
||||
|
||||
jeecg-boot-redis:
|
||||
image: registry.cn-hangzhou.aliyuncs.com/jeecgdocker/redis:5.0
|
||||
# ports:
|
||||
# - 6379:6379
|
||||
ports:
|
||||
- 6379:6379
|
||||
restart: always
|
||||
hostname: jeecg-boot-redis
|
||||
container_name: jeecg-boot-redis
|
||||
networks:
|
||||
- jeecg-boot
|
||||
|
||||
jeecg-boot-pgvector:
|
||||
image: registry.cn-hangzhou.aliyuncs.com/jeecgdocker/pgvector
|
||||
container_name: jeecg-boot-pgvector
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: vector_db
|
||||
# ports:
|
||||
# - 5432:5432
|
||||
restart: always
|
||||
networks:
|
||||
- jeecg-boot
|
||||
|
||||
# jeecg-boot-rabbitmq:
|
||||
# image: rabbitmq:3.7.7-management
|
||||
## ports:
|
||||
## - 5672:5672
|
||||
## - 15672:15672
|
||||
# restart: always
|
||||
# container_name: jeecg-boot-rabbitmq
|
||||
# hostname: jeecg-boot-rabbitmq
|
||||
# environment:
|
||||
# RABBITMQ_DEFAULT_USER: guest
|
||||
# RABBITMQ_DEFAULT_PASS: guest
|
||||
# networks:
|
||||
# - jeecg-boot
|
||||
|
||||
jeecg-boot-system:
|
||||
build:
|
||||
context: ./jeecg-module-system/jeecg-system-start
|
||||
@ -73,8 +46,6 @@ services:
|
||||
- 8080:8080
|
||||
networks:
|
||||
- jeecg-boot
|
||||
volumes:
|
||||
- ./config:/jeecg-boot/config
|
||||
|
||||
networks:
|
||||
jeecg-boot:
|
||||
|
||||
@ -2,9 +2,9 @@
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.jeecgframework.boot3</groupId>
|
||||
<groupId>org.jeecgframework.boot</groupId>
|
||||
<artifactId>jeecg-boot-parent</artifactId>
|
||||
<version>3.8.3</version>
|
||||
<version>3.8.1</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>jeecg-boot-base-core</artifactId>
|
||||
@ -42,13 +42,23 @@
|
||||
<dependencies>
|
||||
<!--jeecg-tools-->
|
||||
<dependency>
|
||||
<groupId>org.jeecgframework.boot3</groupId>
|
||||
<artifactId>jeecg-boot-common</artifactId>
|
||||
<groupId>org.jeecgframework.boot</groupId>
|
||||
<artifactId>jeecg-boot-common3</artifactId>
|
||||
</dependency>
|
||||
<!--集成springmvc框架并实现自动配置 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-tomcat</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-undertow</artifactId>
|
||||
</dependency>
|
||||
<!-- websocket -->
|
||||
<dependency>
|
||||
@ -107,10 +117,11 @@
|
||||
<version>${mybatis-plus.version}</version>
|
||||
</dependency>
|
||||
<!-- minidao -->
|
||||
<dependency>
|
||||
<groupId>org.jeecgframework.boot3</groupId>
|
||||
<artifactId>minidao-spring-boot-starter-jsqlparser-4.9</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-jsqlparser-4.9</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- druid -->
|
||||
<dependency>
|
||||
@ -137,7 +148,7 @@
|
||||
<!-- sqlserver-->
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
<artifactId>sqljdbc4</artifactId>
|
||||
<version>${sqljdbc4.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
@ -159,13 +170,13 @@
|
||||
<dependency>
|
||||
<groupId>org.jeecgframework</groupId>
|
||||
<artifactId>kingbase8</artifactId>
|
||||
<version>${kingbase8.version}</version>
|
||||
<version>9.0.0</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!--达梦数据库驱动 版本号1-3-26-2023.07.26-197096-20046-ENT -->
|
||||
<dependency>
|
||||
<groupId>com.dameng</groupId>
|
||||
<artifactId>DmJdbcDriver18</artifactId>
|
||||
<artifactId>Dm8JdbcDriver18</artifactId>
|
||||
<version>${dm8.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -180,31 +191,33 @@
|
||||
<artifactId>spring-boot-starter-quartz</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Sa-Token 权限认证,在线文档:https://sa-token.cc -->
|
||||
<!--JWT-->
|
||||
<dependency>
|
||||
<groupId>cn.dev33</groupId>
|
||||
<artifactId>sa-token-spring-boot3-starter</artifactId>
|
||||
<version>${sa-token.version}</version>
|
||||
</dependency>
|
||||
<!-- Sa-Token 整合 Redis (使用 jackson 序列化方式) -->
|
||||
<dependency>
|
||||
<groupId>cn.dev33</groupId>
|
||||
<artifactId>sa-token-redis-jackson</artifactId>
|
||||
<version>${sa-token.version}</version>
|
||||
</dependency>
|
||||
<!-- Sa-Token 整合 jwt (Simple模式),保持与原JWT token格式兼容 -->
|
||||
<dependency>
|
||||
<groupId>cn.dev33</groupId>
|
||||
<artifactId>sa-token-jwt</artifactId>
|
||||
<version>${sa-token.version}</version>
|
||||
<groupId>com.auth0</groupId>
|
||||
<artifactId>java-jwt</artifactId>
|
||||
<version>${java-jwt.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
|
||||
</dependency>
|
||||
<!-- 添加spring security cas支持 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-cas</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- <dependency>
|
||||
<groupId>com.github.xiaoymin</groupId>
|
||||
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
|
||||
<version>${knife4j-spring-boot-starter.version}</version>
|
||||
</dependency>-->
|
||||
<groupId>com.github.xiaoymin</groupId>
|
||||
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
|
||||
<version>${knife4j-spring-boot-starter.version}</version>
|
||||
</dependency>-->
|
||||
<!-- knife4j 升级springboot3.4.5报错 -->
|
||||
<dependency>
|
||||
<groupId>com.github.xiaoymin</groupId>
|
||||
@ -216,7 +229,7 @@
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>2.7.0</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- 代码生成器 -->
|
||||
<!-- 如下载失败,请参考此文档 https://help.jeecg.com/java/setup/maven.html -->
|
||||
<dependency>
|
||||
@ -239,6 +252,17 @@
|
||||
<dependency>
|
||||
<groupId>org.jeecgframework.boot3</groupId>
|
||||
<artifactId>autopoi-web</artifactId>
|
||||
<version>${autopoi-web.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<artifactId>xercesImpl</artifactId>
|
||||
<groupId>xerces</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>xerces</groupId>
|
||||
@ -309,9 +333,14 @@
|
||||
<artifactId>hutool-crypto</artifactId>
|
||||
</dependency>
|
||||
<!-- chatgpt -->
|
||||
<dependency>
|
||||
<groupId>org.jeecgframework.boot</groupId>
|
||||
<artifactId>jeecg-boot-starter3-chatgpt</artifactId>
|
||||
</dependency>
|
||||
<!-- minidao -->
|
||||
<dependency>
|
||||
<groupId>org.jeecgframework.boot3</groupId>
|
||||
<artifactId>jeecg-boot-starter-chatgpt</artifactId>
|
||||
<artifactId>minidao-spring-boot-starter-jsqlparser-4.9</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@ -1,7 +1,6 @@
|
||||
package org.apache.shiro.subject;
|
||||
|
||||
|
||||
import org.jeecg.common.util.LoginUserUtils;
|
||||
import org.jeecg.config.security.utils.SecureUtil;
|
||||
|
||||
/**
|
||||
* 兼容处理Online功能使用处理,请勿修改
|
||||
@ -10,6 +9,6 @@ import org.jeecg.common.util.LoginUserUtils;
|
||||
*/
|
||||
public interface Subject {
|
||||
default Object getPrincipal() {
|
||||
return LoginUserUtils.getSessionUser();
|
||||
return SecureUtil.currentUser();
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
package org.jeecg.common.api;
|
||||
|
||||
import org.jeecg.common.api.dto.AiragFlowDTO;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.jeecg.common.system.vo.*;
|
||||
|
||||
import java.util.List;
|
||||
@ -65,6 +65,13 @@ public interface CommonAPI {
|
||||
*/
|
||||
public String getUserIdByName(String username);
|
||||
|
||||
/**
|
||||
* 5根据用户手机号查询用户信息
|
||||
* @param username
|
||||
* @return
|
||||
*/
|
||||
public LoginUser getUserByPhone(String phone);
|
||||
|
||||
|
||||
/**
|
||||
* 6字典表的 翻译
|
||||
@ -146,14 +153,30 @@ public interface CommonAPI {
|
||||
//update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
|
||||
|
||||
/**
|
||||
* 16 运行AIRag流程
|
||||
* for [QQYUN-13634]在baseapi里面封装方法,方便其他模块调用
|
||||
*
|
||||
* @param airagFlowDTO
|
||||
* @return 流程执行结果,可能是String或者Map
|
||||
* @author chenrui
|
||||
* @date 2025/9/2 11:43
|
||||
* 登录加载系统字典
|
||||
* @return
|
||||
*/
|
||||
Object runAiragFlow(AiragFlowDTO airagFlowDTO);
|
||||
Map<String,List<DictModel>> queryAllDictItems();
|
||||
|
||||
/**
|
||||
* 查询SysDepart集合
|
||||
* @param userId
|
||||
* @return
|
||||
*/
|
||||
List<SysDepartModel> queryUserDeparts(String userId);
|
||||
|
||||
/**
|
||||
* 根据用户名设置部门ID
|
||||
* @param username
|
||||
* @param orgCode
|
||||
*/
|
||||
void updateUserDepart(String username,String orgCode,Integer loginTenantId);
|
||||
|
||||
/**
|
||||
* 设置登录租户
|
||||
* @param username
|
||||
* @return
|
||||
*/
|
||||
JSONObject setLoginTenant(String username);
|
||||
|
||||
}
|
||||
|
||||
@ -1,36 +0,0 @@
|
||||
package org.jeecg.common.api.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 调用AI流程入参
|
||||
* for [QQYUN-13634]在baseapi里面封装方法,方便其他模块调用
|
||||
* @author chenrui
|
||||
* @date 2025/9/2 14:11
|
||||
*/
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Data
|
||||
public class AiragFlowDTO implements Serializable {
|
||||
|
||||
|
||||
private static final long serialVersionUID = 7431775881170684867L;
|
||||
|
||||
/**
|
||||
* 流程id
|
||||
*/
|
||||
private String flowId;
|
||||
|
||||
|
||||
/**
|
||||
* 输入参数
|
||||
*/
|
||||
private Map<String, Object> inputParams;
|
||||
}
|
||||
@ -91,12 +91,6 @@ public class MessageDTO implements Serializable {
|
||||
private Boolean isTimeJob = false;
|
||||
|
||||
//---【邮件相关参数】-------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 枚举:org.jeecg.common.constant.enums.NoticeTypeEnum
|
||||
* 通知类型(system:系统消息、file:知识库、flow:流程、plan:日程计划、meeting:会议)
|
||||
*/
|
||||
private String noticeType;
|
||||
|
||||
public MessageDTO(){
|
||||
}
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
package org.jeecg.common.api.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
package org.jeecg.common.aspect;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alibaba.fastjson.serializer.PropertyFilter;
|
||||
import org.jeecg.common.util.LoginUserUtils;
|
||||
import org.apache.shiro.SecurityUtils;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
@ -15,12 +16,14 @@ import org.jeecg.common.aspect.annotation.AutoLog;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
import org.jeecg.common.constant.enums.ModuleType;
|
||||
import org.jeecg.common.constant.enums.OperateTypeEnum;
|
||||
import org.jeecg.config.security.utils.SecureUtil;
|
||||
import org.jeecg.modules.base.service.BaseCommonService;
|
||||
import org.jeecg.common.system.vo.LoginUser;
|
||||
import org.jeecg.common.util.IpUtils;
|
||||
import org.jeecg.common.util.SpringContextUtils;
|
||||
import org.jeecg.common.util.oConvertUtils;
|
||||
import org.springframework.core.StandardReflectionParameterNameDiscoverer;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
@ -100,7 +103,7 @@ public class AutoLogAspect {
|
||||
//设置IP地址
|
||||
dto.setIp(IpUtils.getIpAddr(request));
|
||||
//获取登录用户信息
|
||||
LoginUser sysUser = LoginUserUtils.getSessionUser();
|
||||
LoginUser sysUser = SecureUtil.currentUser();
|
||||
if(sysUser!=null){
|
||||
dto.setUserid(sysUser.getUsername());
|
||||
dto.setUsername(sysUser.getRealname());
|
||||
@ -244,7 +247,7 @@ public class AutoLogAspect {
|
||||
sysLog.setIp(IPUtils.getIpAddr(request));
|
||||
|
||||
//获取登录用户信息
|
||||
LoginUser sysUser = LoginUserUtils.getLoginUser();
|
||||
LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
|
||||
if(sysUser!=null){
|
||||
sysLog.setUserid(sysUser.getUsername());
|
||||
sysLog.setUsername(sysUser.getRealname());
|
||||
|
||||
@ -87,6 +87,13 @@ public interface CommonConstant {
|
||||
/**访问权限认证未通过 510*/
|
||||
Integer SC_JEECG_NO_AUTHZ=510;
|
||||
|
||||
/** 登录用户Shiro权限缓存KEY前缀 */
|
||||
public static String PREFIX_USER_SHIRO_CACHE = "shiro:cache:org.jeecg.config.shiro.ShiroRealm.authorizationCache:";
|
||||
/** 登录用户Token令牌缓存KEY前缀 */
|
||||
String PREFIX_USER_TOKEN = "token::jeecg-client::";
|
||||
// /** Token缓存时间:3600秒即一小时 */
|
||||
// int TOKEN_EXPIRE_TIME = 3600;
|
||||
|
||||
/** 登录二维码 */
|
||||
String LOGIN_QRCODE_PRE = "QRCODELOGIN:";
|
||||
String LOGIN_QRCODE = "LQ:";
|
||||
@ -296,11 +303,6 @@ public interface CommonConstant {
|
||||
*/
|
||||
String SYS_USER_ID_MAPPING_CACHE = "sys:cache:user:id_mapping";
|
||||
|
||||
/**
|
||||
* 系统角色管理员编码
|
||||
*/
|
||||
String SYS_ROLE_ADMIN = "admin";
|
||||
|
||||
/**
|
||||
* 考勤补卡业务状态 (1:同意 2:不同意)
|
||||
*/
|
||||
@ -426,11 +428,6 @@ public interface CommonConstant {
|
||||
*/
|
||||
String NOTICE_MSG_BUS_TYPE = "NOTICE_MSG_BUS_TYPE";
|
||||
|
||||
/**
|
||||
* 通知类型,用于区分来源 file 知识 flow 流程 plan 日程 system 系统消息
|
||||
*/
|
||||
String NOTICE_TYPE = "noticeType";
|
||||
|
||||
/**
|
||||
* 邮箱消息中地址登录时地址后携带的token,需要替换成真实的token值
|
||||
*/
|
||||
@ -632,74 +629,4 @@ public interface CommonConstant {
|
||||
* 修改手机号验证码请求次数超出
|
||||
*/
|
||||
Integer PHONE_SMS_FAIL_CODE = 40002;
|
||||
|
||||
|
||||
/**
|
||||
* 自定义首页关联关系(ROLE:表示角色 USER:表示用户 DEFAULT:默认首页)
|
||||
*
|
||||
*/
|
||||
String HOME_RELATION_ROLE = "ROLE";
|
||||
String HOME_RELATION_USER = "USER";
|
||||
String HOME_RELATION_DEFAULT = "DEFAULT";
|
||||
|
||||
/**
|
||||
* 是否置顶(0否 1是)
|
||||
*/
|
||||
Integer IZ_TOP_1 = 1;
|
||||
Integer IZ_TOP_0 = 0;
|
||||
|
||||
|
||||
//关注流程缓存前缀
|
||||
String FLOW_FOCUS_NOTICE_PREFIX = "flow:runtimeData:focus:notice:";
|
||||
//任务缓办时间缓存前缀
|
||||
String FLOW_TASK_DELAY_PREFIX = "flow:runtimeData:task:delay:";
|
||||
/**
|
||||
* 用户代理类型:离职:quit 代理:agent
|
||||
*/
|
||||
String USER_AGENT_TYPE_QUIT = "quit";
|
||||
String USER_AGENT_TYPE_AGENT = "agent";
|
||||
/**
|
||||
* 督办流程首节点任务taskKey
|
||||
*/
|
||||
String SUPERVISE_FIRST_TASK_KEY = "Task_1bhxpt0";
|
||||
|
||||
/**
|
||||
* wps模板预览数据缓存前缀
|
||||
*/
|
||||
String EOA_WPS_TEMPLATE_VIEW_DATA ="eoa:wps:templateViewData:";
|
||||
|
||||
/**
|
||||
* wps模板预览版本号缓存前缀
|
||||
*/
|
||||
String EOA_WPS_TEMPLATE_VIEW_VERSION ="eoa:wps:templateViewVersion:";
|
||||
/**
|
||||
* 表单设计器oa新增字段
|
||||
* x_oa_timeout_date:逾期时间
|
||||
* x_oa_archive_status:归档状态
|
||||
*/
|
||||
String X_OA_TIMEOUT_DATE ="x_oa_timeout_date";
|
||||
String X_OA_ARCHIVE_STATUS ="x_oa_archive_status";
|
||||
/**
|
||||
* 流程状态
|
||||
* 待提交: 1
|
||||
* 处理中: 2
|
||||
* 已完成: 3
|
||||
* 已作废: 4
|
||||
* 已挂起: 5
|
||||
*/
|
||||
String BPM_STATUS_1 ="1";
|
||||
String BPM_STATUS_2 ="2";
|
||||
String BPM_STATUS_3 ="3";
|
||||
String BPM_STATUS_4 ="4";
|
||||
String BPM_STATUS_5 ="5";
|
||||
|
||||
/**
|
||||
* 默认租户产品包
|
||||
*/
|
||||
String TENANT_PACK_DEFAULT = "default";
|
||||
|
||||
/**
|
||||
* 部门名称redisKey(全路径)
|
||||
*/
|
||||
String DEPART_NAME_REDIS_KEY_PRE = "sys:cache:departPathName:";
|
||||
}
|
||||
|
||||
@ -4,20 +4,6 @@ package org.jeecg.common.constant;
|
||||
* @author: jeecg-boot
|
||||
*/
|
||||
public interface DataBaseConstant {
|
||||
|
||||
/**
|
||||
* 内置的系统变量键列表
|
||||
*/
|
||||
public static final String[] SYSTEM_KEYS = {
|
||||
DataBaseConstant.SYS_ORG_CODE, DataBaseConstant.SYS_ORG_CODE_TABLE, DataBaseConstant.SYS_MULTI_ORG_CODE,
|
||||
DataBaseConstant.SYS_MULTI_ORG_CODE_TABLE, DataBaseConstant.SYS_ORG_ID, DataBaseConstant.SYS_ORG_ID_TABLE,
|
||||
DataBaseConstant.SYS_ROLE_CODE, DataBaseConstant.SYS_ROLE_CODE_TABLE, DataBaseConstant.SYS_USER_CODE,
|
||||
DataBaseConstant.SYS_USER_CODE_TABLE, DataBaseConstant.SYS_USER_ID, DataBaseConstant.SYS_USER_ID_TABLE,
|
||||
DataBaseConstant.SYS_USER_NAME, DataBaseConstant.SYS_USER_NAME_TABLE, DataBaseConstant.SYS_DATE,
|
||||
DataBaseConstant.SYS_DATE_TABLE, DataBaseConstant.SYS_TIME, DataBaseConstant.SYS_TIME_TABLE,
|
||||
DataBaseConstant.SYS_BASE_PATH
|
||||
};
|
||||
|
||||
//*********数据库类型****************************************
|
||||
|
||||
/**MYSQL数据库*/
|
||||
|
||||
@ -1,15 +0,0 @@
|
||||
package org.jeecg.common.constant;
|
||||
|
||||
/**
|
||||
* @Description: 密码常量类
|
||||
*
|
||||
* @author: wangshuai
|
||||
* @date: 2025/8/27 20:10
|
||||
*/
|
||||
public interface PasswordConstant {
|
||||
|
||||
/**
|
||||
* 导入用户默认密码
|
||||
*/
|
||||
String DEFAULT_PASSWORD = "123456";
|
||||
}
|
||||
@ -121,7 +121,7 @@ public class ProvinceCityArea {
|
||||
|
||||
public void getAreaByCode(String code,List<String> ls){
|
||||
for(Area area: areaList){
|
||||
if(null != area && area.getId().equals(code)){
|
||||
if(area.getId().equals(code)){
|
||||
String pid = area.getPid();
|
||||
ls.add(0,area.getText());
|
||||
getAreaByCode(pid,ls);
|
||||
|
||||
@ -1,97 +0,0 @@
|
||||
package org.jeecg.common.constant.enums;
|
||||
|
||||
import org.jeecg.common.util.oConvertUtils;
|
||||
|
||||
/**
|
||||
* @Description: 部门类型枚举类
|
||||
*
|
||||
* @author: wangshuai
|
||||
* @date: 2025/8/19 21:37
|
||||
*/
|
||||
public enum DepartCategoryEnum {
|
||||
|
||||
DEPART_CATEGORY_COMPANY("部门类型:公司","公司","1"),
|
||||
DEPART_CATEGORY_DEPART("部门类型:部门","部门","2"),
|
||||
DEPART_CATEGORY_POST("部门类型:岗位","岗位","3"),
|
||||
DEPART_CATEGORY_SUB_COMPANY("部门类型:子公司","子公司","4");
|
||||
|
||||
DepartCategoryEnum(String described, String name, String value) {
|
||||
this.value = value;
|
||||
this.name = name;
|
||||
this.described = described;
|
||||
}
|
||||
|
||||
/**
|
||||
* 描述
|
||||
*/
|
||||
private String described;
|
||||
/**
|
||||
* 值
|
||||
*/
|
||||
private String value;
|
||||
|
||||
/**
|
||||
* 名称
|
||||
*/
|
||||
private String name;
|
||||
|
||||
public String getDescribed() {
|
||||
return described;
|
||||
}
|
||||
|
||||
public void setDescribed(String described) {
|
||||
this.described = described;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据值获取名称
|
||||
*
|
||||
* @param value
|
||||
* @return
|
||||
*/
|
||||
public static String getNameByValue(String value){
|
||||
if (oConvertUtils.isEmpty(value)) {
|
||||
return null;
|
||||
}
|
||||
for (DepartCategoryEnum val : values()) {
|
||||
if (val.getValue().equals(value)) {
|
||||
return val.getName();
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据名称获取值
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static String getValueByName(String name){
|
||||
if (oConvertUtils.isEmpty(name)) {
|
||||
return null;
|
||||
}
|
||||
for (DepartCategoryEnum val : values()) {
|
||||
if (val.getName().equals(name)) {
|
||||
return val.getValue();
|
||||
}
|
||||
}
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@ -9,14 +9,14 @@ import org.apache.commons.lang3.StringUtils;
|
||||
public enum DySmsEnum {
|
||||
|
||||
/**登录短信模板编码*/
|
||||
LOGIN_TEMPLATE_CODE("SMS_175435174","敲敲云","code"),
|
||||
LOGIN_TEMPLATE_CODE("SMS_175435174","敲敲云","code"),
|
||||
/**忘记密码短信模板编码*/
|
||||
FORGET_PASSWORD_TEMPLATE_CODE("SMS_175435174","敲敲云","code"),
|
||||
/**修改密码短信模板编码*/
|
||||
CHANGE_PASSWORD_TEMPLATE_CODE("SMS_465391221","敲敲云","code"),
|
||||
/**注册账号短信模板编码*/
|
||||
REGISTER_TEMPLATE_CODE("SMS_175430166","敲敲云","code");
|
||||
|
||||
FORGET_PASSWORD_TEMPLATE_CODE("SMS_175435174","敲敲云","code"),
|
||||
/**修改密码短信模板编码*/
|
||||
CHANGE_PASSWORD_TEMPLATE_CODE("SMS_465391221","敲敲云","code"),
|
||||
/**注册账号短信模板编码*/
|
||||
REGISTER_TEMPLATE_CODE("SMS_175430166","敲敲云","code");
|
||||
|
||||
/**
|
||||
* 短信模板编码
|
||||
*/
|
||||
|
||||
@ -13,10 +13,6 @@ public enum EmailTemplateEnum {
|
||||
* 流程催办
|
||||
*/
|
||||
BPM_CUIBAN_EMAIL("bpm_cuiban_email", "/templates/email/bpm_cuiban_email.ftl"),
|
||||
/**
|
||||
* 流程抄送
|
||||
*/
|
||||
BPM_CC_EMAIL("bpm_cc_email", "/templates/email/bpm_cc_email.ftl"),
|
||||
/**
|
||||
* 流程新任务
|
||||
*/
|
||||
|
||||
@ -8,30 +8,21 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
*
|
||||
* @author: jeecg-boot
|
||||
*/
|
||||
@EnumDict("messageType")
|
||||
public enum MessageTypeEnum {
|
||||
|
||||
/**
|
||||
* 系统消息
|
||||
*/
|
||||
XT("system", "系统消息"),
|
||||
/**
|
||||
* 邮件消息
|
||||
*/
|
||||
YJ("email", "邮件消息"),
|
||||
/**
|
||||
* 钉钉消息
|
||||
*/
|
||||
/** 系统消息 */
|
||||
XT("system", "系统消息"),
|
||||
/** 邮件消息 */
|
||||
YJ("email", "邮件消息"),
|
||||
/** 钉钉消息 */
|
||||
DD("dingtalk", "钉钉消息"),
|
||||
/**
|
||||
* 企业微信
|
||||
*/
|
||||
/** 企业微信 */
|
||||
QYWX("wechat_enterprise", "企业微信");
|
||||
|
||||
MessageTypeEnum(String type, String note) {
|
||||
MessageTypeEnum(String type, String note){
|
||||
this.type = type;
|
||||
this.note = note;
|
||||
}
|
||||
@ -65,13 +56,12 @@ public enum MessageTypeEnum {
|
||||
|
||||
/**
|
||||
* 获取字典数据
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static List<DictModel> getDictList() {
|
||||
public static List<DictModel> getDictList(){
|
||||
List<DictModel> list = new ArrayList<>();
|
||||
DictModel dictModel = null;
|
||||
for (MessageTypeEnum e : MessageTypeEnum.values()) {
|
||||
for(MessageTypeEnum e: MessageTypeEnum.values()){
|
||||
dictModel = new DictModel();
|
||||
dictModel.setValue(e.getType());
|
||||
dictModel.setText(e.getNote());
|
||||
|
||||
@ -1,84 +0,0 @@
|
||||
package org.jeecg.common.constant.enums;
|
||||
|
||||
/**
|
||||
* @Description: 文件类型枚举类
|
||||
*
|
||||
* @author: wangshuai
|
||||
* @date: 2025/6/26 17:29
|
||||
*/
|
||||
public enum NoticeTypeEnum {
|
||||
|
||||
//VUE3专用
|
||||
NOTICE_TYPE_FILE("知识库消息","file"),
|
||||
NOTICE_TYPE_FLOW("工作流消息","flow"),
|
||||
NOTICE_TYPE_PLAN("日程消息","plan"),
|
||||
//暂时没用到
|
||||
NOTICE_TYPE_MEETING("会议消息","meeting"),
|
||||
NOTICE_TYPE_SYSTEM("系统消息","system"),
|
||||
/**
|
||||
* 协同工作
|
||||
* for [JHHB-136]【vue3】协同工作系统消息需要添加一个类型
|
||||
*/
|
||||
NOTICE_TYPE_COLLABORATION("协同工作", "collab"),
|
||||
/**
|
||||
* 督办
|
||||
*/
|
||||
NOTICE_TYPE_SUPERVISE("督办管理", "supe");
|
||||
|
||||
/**
|
||||
* 文件类型名称
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 文件类型值
|
||||
*/
|
||||
private String value;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
NoticeTypeEnum(String name, String value) {
|
||||
this.name = name;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取聊天通知类型
|
||||
*
|
||||
* @param value
|
||||
* @return
|
||||
*/
|
||||
public static String getChatNoticeType(String value){
|
||||
return value + "Notice";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取通知名称
|
||||
*
|
||||
* @param value
|
||||
* @return
|
||||
*/
|
||||
public static String getNoticeNameByValue(String value){
|
||||
value = value.replace("Notice","");
|
||||
for (NoticeTypeEnum e : NoticeTypeEnum.values()) {
|
||||
if (e.getValue().equals(value)) {
|
||||
return e.getName();
|
||||
}
|
||||
}
|
||||
return "系统消息";
|
||||
}
|
||||
}
|
||||
@ -1,180 +0,0 @@
|
||||
package org.jeecg.common.constant.enums;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 职级枚举类
|
||||
*
|
||||
* 注意:此枚举仅适用于天津临港控股OA项目,职级的名称和等级均为写死(需要与数据库配置一致)
|
||||
* @date 2025-08-26
|
||||
* @author scott
|
||||
*/
|
||||
public enum PositionLevelEnum {
|
||||
|
||||
// 领导层级(等级1-3)
|
||||
CHAIRMAN("董事长", 1, PositionType.LEADER),
|
||||
GENERAL_MANAGER("总经理", 2, PositionType.LEADER),
|
||||
VICE_GENERAL_MANAGER("副总经理", 3, PositionType.LEADER),
|
||||
|
||||
// 职员层级(等级4-6)
|
||||
MINISTER("部长", 4, PositionType.STAFF),
|
||||
VICE_MINISTER("副部长", 5, PositionType.STAFF),
|
||||
STAFF("职员", 6, PositionType.STAFF);
|
||||
|
||||
private final String name;
|
||||
private final int level;
|
||||
private final PositionType type;
|
||||
|
||||
PositionLevelEnum(String name, int level, PositionType type) {
|
||||
this.name = name;
|
||||
this.level = level;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getLevel() {
|
||||
return level;
|
||||
}
|
||||
|
||||
public PositionType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* 职级类型枚举
|
||||
*/
|
||||
public enum PositionType {
|
||||
STAFF("职员层级"),
|
||||
LEADER("领导层级");
|
||||
|
||||
private final String desc;
|
||||
|
||||
PositionType(String desc) {
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据职级名称获取枚举
|
||||
* @param name 职级名称
|
||||
* @return 职级枚举
|
||||
*/
|
||||
public static PositionLevelEnum getByName(String name) {
|
||||
for (PositionLevelEnum position : values()) {
|
||||
if (position.getName().equals(name)) {
|
||||
return position;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据职级等级获取枚举
|
||||
* @param level 职级等级
|
||||
* @return 职级枚举
|
||||
*/
|
||||
public static PositionLevelEnum getByLevel(int level) {
|
||||
for (PositionLevelEnum position : values()) {
|
||||
if (position.getLevel() == level) {
|
||||
return position;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据职级名称判断是否为职员层级
|
||||
* @param name 职级名称
|
||||
* @return true-职员层级,false-非职员层级
|
||||
*/
|
||||
public static boolean isStaffLevel(String name) {
|
||||
PositionLevelEnum position = getByName(name);
|
||||
return position != null && position.getType() == PositionType.STAFF;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据职级名称判断是否为领导层级
|
||||
* @param name 职级名称
|
||||
* @return true-领导层级,false-非领导层级
|
||||
*/
|
||||
public static boolean isLeaderLevel(String name) {
|
||||
PositionLevelEnum position = getByName(name);
|
||||
return position != null && position.getType() == PositionType.LEADER;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个职级的等级高低
|
||||
* @param name1 职级名称1
|
||||
* @param name2 职级名称2
|
||||
* @return 正数表示name1等级更高,负数表示name2等级更高,0表示等级相同
|
||||
*/
|
||||
public static int compareLevel(String name1, String name2) {
|
||||
PositionLevelEnum pos1 = getByName(name1);
|
||||
PositionLevelEnum pos2 = getByName(name2);
|
||||
|
||||
if (pos1 == null || pos2 == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 等级数字越小代表职级越高
|
||||
return pos2.getLevel() - pos1.getLevel();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为更高等级
|
||||
* @param currentName 当前职级名称
|
||||
* @param targetName 目标职级名称
|
||||
* @return true-目标职级更高,false-目标职级不高于当前职级
|
||||
*/
|
||||
public static boolean isHigherLevel(String currentName, String targetName) {
|
||||
return compareLevel(targetName, currentName) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有职员层级名称
|
||||
* @return 职员层级名称列表
|
||||
*/
|
||||
public static List<String> getStaffLevelNames() {
|
||||
return Arrays.asList(MINISTER.getName(), VICE_MINISTER.getName(), STAFF.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有领导层级名称
|
||||
* @return 领导层级名称列表
|
||||
*/
|
||||
public static List<String> getLeaderLevelNames() {
|
||||
return Arrays.asList(CHAIRMAN.getName(), GENERAL_MANAGER.getName(), VICE_GENERAL_MANAGER.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有职级名称(按等级排序)
|
||||
* @return 所有职级名称列表
|
||||
*/
|
||||
public static List<String> getAllPositionNames() {
|
||||
return Arrays.asList(
|
||||
CHAIRMAN.getName(), GENERAL_MANAGER.getName(), VICE_GENERAL_MANAGER.getName(),
|
||||
MINISTER.getName(), VICE_MINISTER.getName(), STAFF.getName()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定等级范围的职级
|
||||
* @param minLevel 最小等级
|
||||
* @param maxLevel 最大等级
|
||||
* @return 职级名称列表
|
||||
*/
|
||||
public static List<String> getPositionsByLevelRange(int minLevel, int maxLevel) {
|
||||
return Arrays.stream(values())
|
||||
.filter(p -> p.getLevel() >= minLevel && p.getLevel() <= maxLevel)
|
||||
.map(PositionLevelEnum::getName)
|
||||
.collect(java.util.stream.Collectors.toList());
|
||||
}
|
||||
}
|
||||
@ -23,25 +23,7 @@ public enum SysAnnmentTypeEnum {
|
||||
/**
|
||||
* 邀请用户跳转到个人设置
|
||||
*/
|
||||
TENANT_INVITE("tenant_invite", "url", "/system/usersetting"),
|
||||
/**
|
||||
* 协同工作-待办通知
|
||||
* for [JHHB-136]【vue3】协同工作系统消息需要添加一个类型
|
||||
*/
|
||||
EOA_CO_NOTIFY("eoa_co_notify", "url", "/collaboration/pending"),
|
||||
/**
|
||||
* 协同工作-催办通知
|
||||
* for [JHHB-136]【vue3】协同工作系统消息需要添加一个类型
|
||||
*/
|
||||
EOA_CO_REMIND("eoa_co_remind", "url", "/collaboration/pending"),
|
||||
/**
|
||||
* 督办管理-催办
|
||||
*/
|
||||
EOA_SUP_REMIND("eoa_sup_remind", "url", "/superivse/list"),
|
||||
/**
|
||||
* 督办管理-通知
|
||||
*/
|
||||
EOA_SUP_NOTIFY("eoa_sup_notify", "url", "/superivse/list");
|
||||
TENANT_INVITE("tenant_invite", "url", "/system/usersetting");
|
||||
|
||||
/**
|
||||
* 业务类型(email:邮件 bpm:流程)
|
||||
|
||||
@ -5,10 +5,7 @@ import jakarta.annotation.Resource;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.exception.ExceptionUtils;
|
||||
import org.jeecg.common.util.LoginUserUtils;
|
||||
import cn.dev33.satoken.exception.NotLoginException;
|
||||
import cn.dev33.satoken.exception.NotPermissionException;
|
||||
import cn.dev33.satoken.exception.NotRoleException;
|
||||
import org.apache.shiro.SecurityUtils;
|
||||
import org.jeecg.common.api.dto.LogDTO;
|
||||
import org.jeecg.common.api.vo.Result;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
@ -25,6 +22,8 @@ import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.data.redis.connection.PoolException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.validation.ObjectError;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
@ -33,7 +32,6 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
import org.springframework.web.multipart.MultipartException;
|
||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||
|
||||
import java.util.Map;
|
||||
@ -48,9 +46,27 @@ import java.util.stream.Collectors;
|
||||
@RestControllerAdvice
|
||||
@Slf4j
|
||||
public class JeecgBootExceptionHandler {
|
||||
|
||||
@Resource
|
||||
|
||||
@Resource
|
||||
BaseCommonService baseCommonService;
|
||||
|
||||
/**
|
||||
* 验证码错误异常
|
||||
*/
|
||||
|
||||
@ExceptionHandler(JeecgCaptchaException.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public Result<?> handleJeecgCaptchaException(JeecgCaptchaException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return Result.error(e.getCode(), e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(AuthenticationException.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
public Result<?> handleJeecgCaptchaException(AuthenticationException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return Result.error(401, e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public Result<?> handleValidationExceptions(MethodArgumentNotValidException e) {
|
||||
@ -58,7 +74,7 @@ public class JeecgBootExceptionHandler {
|
||||
addSysLog(e);
|
||||
return Result.error("校验失败!" + e.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(",")));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 处理自定义异常
|
||||
*/
|
||||
@ -113,34 +129,12 @@ public class JeecgBootExceptionHandler {
|
||||
return Result.error("数据库中已存在该记录");
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理Sa-Token未登录异常
|
||||
*/
|
||||
@ExceptionHandler(NotLoginException.class)
|
||||
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||
public Result<?> handleNotLoginException(NotLoginException e){
|
||||
log.error("Sa-Token未登录异常: {}", e.getMessage());
|
||||
return new Result(401, CommonConstant.TOKEN_IS_INVALID_MSG);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理Sa-Token无权限异常
|
||||
*/
|
||||
@ExceptionHandler(NotPermissionException.class)
|
||||
public Result<?> handleNotPermissionException(NotPermissionException e){
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public Result<?> handleAuthorizationException(AccessDeniedException e){
|
||||
log.error(e.getMessage(), e);
|
||||
return Result.noauth("没有权限,请联系管理员分配权限!");
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理Sa-Token无角色异常
|
||||
*/
|
||||
@ExceptionHandler(NotRoleException.class)
|
||||
public Result<?> handleNotRoleException(NotRoleException e){
|
||||
log.error(e.getMessage(), e);
|
||||
return Result.noauth("没有角色权限,请联系管理员分配角色!");
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public Result<?> handleException(Exception e){
|
||||
log.error(e.getMessage(), e);
|
||||
@ -190,27 +184,6 @@ public class JeecgBootExceptionHandler {
|
||||
return Result.error("文件大小超出10MB限制, 请压缩或降低文件质量! ");
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理文件过大异常.
|
||||
* jdk17中的MultipartException异常类已经被拆分成了MultipartException和MaxUploadSizeExceededException
|
||||
* for [QQYUN-11716]上传大图片失败没有精确提示
|
||||
* @param e
|
||||
* @return
|
||||
* @author chenrui
|
||||
* @date 2025/4/8 16:13
|
||||
*/
|
||||
@ExceptionHandler(MultipartException.class)
|
||||
public Result<?> handleMaxUploadSizeExceededException(MultipartException e) {
|
||||
Throwable cause = e.getCause();
|
||||
if (cause instanceof IllegalStateException) {
|
||||
log.error("文件大小超出限制: {}", cause.getMessage(), e);
|
||||
addSysLog(e);
|
||||
return Result.error("文件大小超出限制, 请压缩或降低文件质量!");
|
||||
} else {
|
||||
return handleException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@ExceptionHandler(DataIntegrityViolationException.class)
|
||||
public Result<?> handleDataIntegrityViolationException(DataIntegrityViolationException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
@ -266,16 +239,11 @@ public class JeecgBootExceptionHandler {
|
||||
} catch (NullPointerException | BeansException ignored) {
|
||||
}
|
||||
if (null != request) {
|
||||
//update-begin---author:chenrui ---date:20250408 for:[QQYUN-11716]上传大图片失败没有精确提示------------
|
||||
//请求的参数
|
||||
if (!isTooBigException(e)) {
|
||||
// 文件上传过大异常时不能获取参数,否则会报错
|
||||
Map<String, String[]> parameterMap = request.getParameterMap();
|
||||
if(!CollectionUtils.isEmpty(parameterMap)) {
|
||||
log.setMethod(oConvertUtils.mapToString(request.getParameterMap()));
|
||||
}
|
||||
Map<String, String[]> parameterMap = request.getParameterMap();
|
||||
if(!CollectionUtils.isEmpty(parameterMap)){
|
||||
log.setMethod(oConvertUtils.mapToString(request.getParameterMap()));
|
||||
}
|
||||
//update-end---author:chenrui ---date:20250408 for:[QQYUN-11716]上传大图片失败没有精确提示------------
|
||||
// 请求地址
|
||||
log.setRequestUrl(request.getRequestURI());
|
||||
//设置IP地址
|
||||
@ -290,7 +258,7 @@ public class JeecgBootExceptionHandler {
|
||||
|
||||
|
||||
//获取登录用户信息
|
||||
LoginUser sysUser = LoginUserUtils.getSessionUser();
|
||||
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
|
||||
if(sysUser!=null){
|
||||
log.setUserid(sysUser.getUsername());
|
||||
log.setUsername(sysUser.getRealname());
|
||||
@ -301,26 +269,4 @@ public class JeecgBootExceptionHandler {
|
||||
}
|
||||
//update-end---author:chenrui ---date:20240423 for:[QQYUN-8732]把错误的日志都抓取了 方便后续处理,单独弄个日志类型------------
|
||||
|
||||
/**
|
||||
* 是否文件过大异常
|
||||
* for [QQYUN-11716]上传大图片失败没有精确提示
|
||||
* @param e
|
||||
* @return
|
||||
* @author chenrui
|
||||
* @date 2025/4/8 20:21
|
||||
*/
|
||||
private static boolean isTooBigException(Throwable e) {
|
||||
boolean isTooBigException = false;
|
||||
if(e instanceof MultipartException){
|
||||
Throwable cause = e.getCause();
|
||||
if (cause instanceof IllegalStateException){
|
||||
isTooBigException = true;
|
||||
}
|
||||
}
|
||||
if(e instanceof MaxUploadSizeExceededException){
|
||||
isTooBigException = true;
|
||||
}
|
||||
return isTooBigException;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,28 @@
|
||||
package org.jeecg.common.exception;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author kezhijie@wuhandsj.com
|
||||
* @date 2024/1/2 11:38
|
||||
*/
|
||||
@Data
|
||||
public class JeecgCaptchaException extends RuntimeException{
|
||||
|
||||
private Integer code;
|
||||
|
||||
private static final long serialVersionUID = -9093410345065209053L;
|
||||
|
||||
public JeecgCaptchaException(Integer code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public JeecgCaptchaException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public JeecgCaptchaException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
@ -4,11 +4,6 @@ import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 将枚举类转化成字典数据
|
||||
*
|
||||
* <<使用说明>>
|
||||
* 1. 枚举类需以 `Enum` 结尾,并且在类上添加 `@EnumDict` 注解。
|
||||
* 2. 需要手动将枚举类所在包路径** 添加到 `org.jeecg.common.system.util.ResourceUtil.BASE_SCAN_PACKAGES` 配置数组中。
|
||||
*
|
||||
* @Author taoYan
|
||||
* @Date 2022/7/8 10:34
|
||||
**/
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
package org.jeecg.common.system.base.controller;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
@ -9,17 +10,17 @@ import org.apache.commons.beanutils.PropertyUtils;
|
||||
import org.jeecg.common.api.vo.Result;
|
||||
import org.jeecg.common.system.query.QueryGenerator;
|
||||
import org.jeecg.common.system.vo.LoginUser;
|
||||
import org.jeecg.common.util.LoginUserUtils;
|
||||
import org.jeecg.common.util.oConvertUtils;
|
||||
import org.jeecg.config.JeecgBaseConfig;
|
||||
import org.jeecg.config.security.utils.SecureUtil;
|
||||
import org.jeecgframework.poi.excel.ExcelImportUtil;
|
||||
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
|
||||
import org.jeecgframework.poi.excel.entity.ExportParams;
|
||||
import org.jeecgframework.poi.excel.entity.ImportParams;
|
||||
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
|
||||
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
|
||||
import org.jeecgframework.poi.handler.inter.IExcelExportServer;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.multipart.MultipartHttpServletRequest;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
@ -52,7 +53,7 @@ public class JeecgController<T, S extends IService<T>> {
|
||||
protected ModelAndView exportXls(HttpServletRequest request, T object, Class<T> clazz, String title) {
|
||||
// Step.1 组装查询条件
|
||||
QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
|
||||
LoginUser sysUser = LoginUserUtils.getSessionUser();
|
||||
LoginUser sysUser = SecureUtil.currentUser();
|
||||
|
||||
// 过滤选中数据
|
||||
String selections = request.getParameter("selections");
|
||||
@ -90,7 +91,7 @@ public class JeecgController<T, S extends IService<T>> {
|
||||
protected ModelAndView exportXlsSheet(HttpServletRequest request, T object, Class<T> clazz, String title,String exportFields,Integer pageNum) {
|
||||
// Step.1 组装查询条件
|
||||
QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
|
||||
LoginUser sysUser = LoginUserUtils.getSessionUser();
|
||||
LoginUser sysUser = SecureUtil.currentUser();
|
||||
// Step.2 计算分页sheet数据
|
||||
double total = service.count();
|
||||
int count = (int)Math.ceil(total/pageNum);
|
||||
@ -128,53 +129,6 @@ public class JeecgController<T, S extends IService<T>> {
|
||||
return mv;
|
||||
}
|
||||
|
||||
/**
|
||||
* 大数据导出
|
||||
* @param request
|
||||
* @param object
|
||||
* @param clazz
|
||||
* @param title
|
||||
* @param pageSize 每次查询的数据量
|
||||
* @return
|
||||
* @author chenrui
|
||||
* @date 2025/8/11 16:11
|
||||
*/
|
||||
protected ModelAndView exportXlsForBigData(HttpServletRequest request, T object, Class<T> clazz, String title,Integer pageSize) {
|
||||
// 组装查询条件
|
||||
QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
|
||||
LoginUser sysUser = LoginUserUtils.getSessionUser();
|
||||
// 计算分页数
|
||||
double total = service.count();
|
||||
int count = (int) Math.ceil(total / pageSize);
|
||||
// 过滤选中数据
|
||||
String selections = request.getParameter("selections");
|
||||
if (oConvertUtils.isNotEmpty(selections)) {
|
||||
List<String> selectionList = Arrays.asList(selections.split(","));
|
||||
queryWrapper.in("id", selectionList);
|
||||
}
|
||||
|
||||
// 定义IExcelExportServer
|
||||
IExcelExportServer excelExportServer = (queryParams, pageNum) -> {
|
||||
if (pageNum > count) {
|
||||
return null;
|
||||
}
|
||||
Page<T> page = new Page<T>(pageNum, pageSize);
|
||||
IPage<T> pageList = service.page(page, (QueryWrapper<T>) queryParams);
|
||||
return new ArrayList<>(pageList.getRecords());
|
||||
};
|
||||
|
||||
// AutoPoi 导出Excel
|
||||
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
|
||||
//此处设置的filename无效 ,前端会重更新设置一下
|
||||
mv.addObject(NormalExcelConstants.FILE_NAME, title);
|
||||
mv.addObject(NormalExcelConstants.CLASS, clazz);
|
||||
ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title, jeecgBaseConfig.getPath().getUpload());
|
||||
mv.addObject(NormalExcelConstants.PARAMS, exportParams);
|
||||
mv.addObject(NormalExcelConstants.EXPORT_SERVER, excelExportServer);
|
||||
mv.addObject(NormalExcelConstants.QUERY_PARAMS, queryWrapper);
|
||||
return mv;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 根据权限导出excel,传入导出字段参数
|
||||
|
||||
@ -2,6 +2,7 @@ package org.jeecg.common.system.base.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.jeecgframework.poi.excel.annotation.Excel;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
@ -9,11 +10,9 @@ import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.experimental.Accessors;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
/**
|
||||
* @Description: Entity基类
|
||||
|
||||
@ -11,7 +11,6 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.OrderItem;
|
||||
import org.apache.commons.beanutils.PropertyUtils;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
import org.jeecg.common.constant.DataBaseConstant;
|
||||
@ -258,69 +257,8 @@ public class QueryGenerator {
|
||||
if(parameterMap!=null&& parameterMap.containsKey(ORDER_TYPE)) {
|
||||
order = parameterMap.get(ORDER_TYPE)[0];
|
||||
}
|
||||
|
||||
if(oConvertUtils.isNotEmpty(column)){
|
||||
log.info("单字段排序规则>> column:" + column + ",排序方式:" + order);
|
||||
}
|
||||
log.debug("排序规则>>列:" + column + ",排序方式:" + order);
|
||||
|
||||
// 1. 列表多字段排序优先
|
||||
if(parameterMap!=null&& parameterMap.containsKey("sortInfoString")) {
|
||||
// 多字段排序
|
||||
String sortInfoString = parameterMap.get("sortInfoString")[0];
|
||||
log.info("多字段排序规则>> sortInfoString:" + sortInfoString);
|
||||
List<OrderItem> orderItemList = SqlConcatUtil.getQueryConditionOrders(column, order, sortInfoString);
|
||||
log.info(orderItemList.toString());
|
||||
if (orderItemList != null && !orderItemList.isEmpty()) {
|
||||
for (OrderItem item : orderItemList) {
|
||||
// 一、获取排序数据库字段
|
||||
String columnName = item.getColumn();
|
||||
// 1.字典字段,去掉字典翻译文本后缀
|
||||
if(columnName.endsWith(CommonConstant.DICT_TEXT_SUFFIX)) {
|
||||
columnName = columnName.substring(0, column.lastIndexOf(CommonConstant.DICT_TEXT_SUFFIX));
|
||||
}
|
||||
// 2.实体驼峰字段转为数据库字段
|
||||
columnName = SqlInjectionUtil.getSqlInjectSortField(columnName);
|
||||
|
||||
// 二、设置字段排序规则
|
||||
if (item.isAsc()) {
|
||||
queryWrapper.orderByAsc(columnName);
|
||||
} else {
|
||||
queryWrapper.orderByDesc(columnName);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 列表单字段默认排序
|
||||
if(oConvertUtils.isEmpty(column) && parameterMap!=null&& parameterMap.containsKey("defSortString")) {
|
||||
// 多字段排序
|
||||
String sortInfoString = parameterMap.get("defSortString")[0];
|
||||
log.info("默认多字段排序规则>> defSortString:" + sortInfoString);
|
||||
List<OrderItem> orderItemList = SqlConcatUtil.getQueryConditionOrders(column, order, sortInfoString);
|
||||
log.info(orderItemList.toString());
|
||||
if (orderItemList != null && !orderItemList.isEmpty()) {
|
||||
for (OrderItem item : orderItemList) {
|
||||
// 一、获取排序数据库字段
|
||||
String columnName = item.getColumn();
|
||||
// 1.字典字段,去掉字典翻译文本后缀
|
||||
if(columnName.endsWith(CommonConstant.DICT_TEXT_SUFFIX)) {
|
||||
columnName = columnName.substring(0, column.lastIndexOf(CommonConstant.DICT_TEXT_SUFFIX));
|
||||
}
|
||||
// 2.实体驼峰字段转为数据库字段
|
||||
columnName = SqlInjectionUtil.getSqlInjectSortField(columnName);
|
||||
|
||||
// 二、设置字段排序规则
|
||||
if (item.isAsc()) {
|
||||
queryWrapper.orderByAsc(columnName);
|
||||
} else {
|
||||
queryWrapper.orderByDesc(columnName);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
//update-begin-author:scott date:2022-11-07 for:避免用户自定义表无默认字段{创建时间},导致排序报错
|
||||
//TODO 避免用户自定义表无默认字段创建时间,导致排序报错
|
||||
if(DataBaseConstant.CREATE_TIME.equals(column) && !fieldColumnMap.containsKey(DataBaseConstant.CREATE_TIME)){
|
||||
@ -414,11 +352,9 @@ public class QueryGenerator {
|
||||
}
|
||||
// update-begin-author:sunjianlei date:20220119 for: 【JTC-573】 过滤空条件查询,防止 sql 拼接多余的 and
|
||||
List<QueryCondition> filterConditions = conditions.stream().filter(
|
||||
rule -> (oConvertUtils.isNotEmpty(rule.getField())
|
||||
&& oConvertUtils.isNotEmpty(rule.getRule())
|
||||
&& oConvertUtils.isNotEmpty(rule.getVal())
|
||||
)
|
||||
|| "empty".equals(rule.getRule())
|
||||
rule -> oConvertUtils.isNotEmpty(rule.getField())
|
||||
&& oConvertUtils.isNotEmpty(rule.getRule())
|
||||
&& oConvertUtils.isNotEmpty(rule.getVal())
|
||||
).collect(Collectors.toList());
|
||||
if (filterConditions.size() == 0) {
|
||||
return;
|
||||
@ -429,12 +365,9 @@ public class QueryGenerator {
|
||||
queryWrapper.and(andWrapper -> {
|
||||
for (int i = 0; i < filterConditions.size(); i++) {
|
||||
QueryCondition rule = filterConditions.get(i);
|
||||
if (
|
||||
(
|
||||
oConvertUtils.isNotEmpty(rule.getField()) && oConvertUtils.isNotEmpty(rule.getRule()) && oConvertUtils.isNotEmpty(rule.getVal())
|
||||
)
|
||||
|| "empty".equals(rule.getRule())
|
||||
) {
|
||||
if (oConvertUtils.isNotEmpty(rule.getField())
|
||||
&& oConvertUtils.isNotEmpty(rule.getRule())
|
||||
&& oConvertUtils.isNotEmpty(rule.getVal())) {
|
||||
|
||||
log.debug("SuperQuery ==> " + rule.toString());
|
||||
|
||||
@ -721,11 +654,7 @@ public class QueryGenerator {
|
||||
* @param value 查询条件值
|
||||
*/
|
||||
public static void addEasyQuery(QueryWrapper<?> queryWrapper, String name, QueryRuleEnum rule, Object value) {
|
||||
if (
|
||||
(
|
||||
name==null || value == null || rule == null || oConvertUtils.isEmpty(value)
|
||||
)
|
||||
&& !QueryRuleEnum.EMPTY.equals(rule)) {
|
||||
if (name==null || value == null || rule == null || oConvertUtils.isEmpty(value)) {
|
||||
return;
|
||||
}
|
||||
name = oConvertUtils.camelToUnderline(name);
|
||||
@ -737,9 +666,6 @@ public class QueryGenerator {
|
||||
case GE:
|
||||
queryWrapper.ge(name, value);
|
||||
break;
|
||||
case EMPTY:
|
||||
queryWrapper.isNull(name);
|
||||
break;
|
||||
case LT:
|
||||
queryWrapper.lt(name, value);
|
||||
break;
|
||||
|
||||
@ -1,101 +1,155 @@
|
||||
package org.jeecg.common.system.util;
|
||||
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTVerifier;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.exceptions.JWTDecodeException;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.base.Joiner;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
import java.io.OutputStream;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import jakarta.servlet.ServletResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jeecg.common.api.CommonAPI;
|
||||
import org.jeecg.common.api.vo.Result;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
import org.jeecg.common.constant.DataBaseConstant;
|
||||
import org.jeecg.common.constant.SymbolConstant;
|
||||
import org.jeecg.common.constant.TenantConstant;
|
||||
import org.jeecg.common.util.LoginUserUtils;
|
||||
import org.jeecg.common.api.vo.Result;
|
||||
import org.jeecg.common.constant.DataBaseConstant;
|
||||
import org.jeecg.common.exception.JeecgBootException;
|
||||
import org.jeecg.common.system.vo.LoginUser;
|
||||
import org.jeecg.common.system.vo.SysUserCacheInfo;
|
||||
import org.jeecg.common.util.DateUtils;
|
||||
import org.jeecg.common.util.SpringContextUtils;
|
||||
import org.jeecg.common.util.oConvertUtils;
|
||||
import org.jeecg.config.security.self.SelfAuthenticationProvider;
|
||||
import org.jeecg.config.security.self.SelfAuthenticationToken;
|
||||
import org.jeecg.config.security.utils.SecureUtil;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.core.*;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
|
||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
|
||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
|
||||
import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContextHolder;
|
||||
import org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext;
|
||||
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
|
||||
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
|
||||
|
||||
/**
|
||||
* @Author Scott
|
||||
* @Date 2018-07-12 14:23
|
||||
* @Desc JWT工具类 - 已迁移到Sa-Token,此类作为兼容层保留
|
||||
* @Desc JWT工具类
|
||||
**/
|
||||
@Slf4j
|
||||
public class JwtUtil {
|
||||
|
||||
|
||||
/**Token有效期为7天(Token在reids中缓存时间为两倍)*/
|
||||
public static final long EXPIRE_TIME = (7 * 12) * 60 * 60 * 1000;
|
||||
static final String WELL_NUMBER = SymbolConstant.WELL_NUMBER + SymbolConstant.LEFT_CURLY_BRACKET;
|
||||
|
||||
/**
|
||||
* 返回错误 JSON 字符串(用于 Sa-Token Filter)
|
||||
* @param code 错误码
|
||||
* @param errorMsg 错误信息
|
||||
* @return JSON 字符串
|
||||
*/
|
||||
public static String responseErrorJson(Integer code, String errorMsg) {
|
||||
try {
|
||||
Result jsonResult = new Result(code, errorMsg);
|
||||
jsonResult.setSuccess(false);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
return objectMapper.writeValueAsString(jsonResult);
|
||||
} catch (IOException e) {
|
||||
log.error("生成错误 JSON 失败: {}", e.getMessage());
|
||||
// 返回备用的硬编码 JSON
|
||||
return "{\"success\":false,\"message\":\"" + errorMsg + "\",\"code\":" + code + ",\"result\":null,\"timestamp\":" + System.currentTimeMillis() + "}";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static final String DEFAULT_CLIENT = "jeecg-client";
|
||||
|
||||
/**
|
||||
*
|
||||
* @param response
|
||||
* @param code
|
||||
* @param errorMsg
|
||||
*/
|
||||
public static void responseError(ServletResponse response, Integer code, String errorMsg) {
|
||||
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
|
||||
// issues/I4YH95浏览器显示乱码问题
|
||||
httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
|
||||
Result jsonResult = new Result(code, errorMsg);
|
||||
jsonResult.setSuccess(false);
|
||||
OutputStream os = null;
|
||||
try {
|
||||
os = httpServletResponse.getOutputStream();
|
||||
httpServletResponse.setCharacterEncoding("UTF-8");
|
||||
httpServletResponse.setStatus(code);
|
||||
os.write(new ObjectMapper().writeValueAsString(jsonResult).getBytes("UTF-8"));
|
||||
os.flush();
|
||||
os.close();
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验token是否正确
|
||||
* 注意:此方法已废弃,使用Sa-Token自动校验
|
||||
*
|
||||
* @param token
|
||||
* @return
|
||||
*
|
||||
* @param token 密钥
|
||||
* @param secret 用户的密码
|
||||
* @return 是否正确
|
||||
*/
|
||||
@Deprecated
|
||||
public static boolean verify(String token){
|
||||
public static boolean verify(String token, String username, String secret) {
|
||||
try {
|
||||
// 使用Sa-Token验证
|
||||
return StpUtil.getLoginIdByToken(token) != null;
|
||||
// 根据密码生成JWT效验器
|
||||
JwtDecoder jwtDecoder = SpringContextUtils.getBean(JwtDecoder.class);
|
||||
// 效验TOKEN
|
||||
jwtDecoder.decode(token);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.warn(e.getMessage(), e);
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得Token中的用户名(不校验token是否有效)
|
||||
* <p>注意:现在 loginId 就是 username,直接返回
|
||||
*
|
||||
* @param token JWT token
|
||||
* @return 用户名(username),如果 token 无效则返回 null
|
||||
* 获得token中的信息无需secret解密也能获得
|
||||
*
|
||||
* @return token中包含的用户名
|
||||
*/
|
||||
public static String getUsername(String token){
|
||||
public static String getUsername(String token) {
|
||||
try {
|
||||
if(oConvertUtils.isEmpty(token)) {
|
||||
return null;
|
||||
}
|
||||
// Sa-Token 的 loginId 现在就是 username,直接返回
|
||||
Object loginId = StpUtil.getLoginIdByToken(token);
|
||||
return loginId != null ? loginId.toString() : null;
|
||||
} catch (Exception e) {
|
||||
log.warn("获取用户名失败: {}", e.getMessage());
|
||||
DecodedJWT jwt = JWT.decode(token);
|
||||
return jwt.getClaim("username").asString();
|
||||
} catch (JWTDecodeException e) {
|
||||
log.warn(e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成token
|
||||
*
|
||||
* @param username 用户名
|
||||
* @param secret 用户的密码
|
||||
* @return 加密的token
|
||||
*/
|
||||
public static String sign(String username, String secret) {
|
||||
Map<String, Object> additionalParameter = new HashMap<>();
|
||||
additionalParameter.put("username", username);
|
||||
|
||||
RegisteredClientRepository registeredClientRepository = SpringContextUtils.getBean(RegisteredClientRepository.class);
|
||||
SelfAuthenticationProvider selfAuthenticationProvider = SpringContextUtils.getBean(SelfAuthenticationProvider.class);
|
||||
|
||||
OAuth2ClientAuthenticationToken client = new OAuth2ClientAuthenticationToken(Objects.requireNonNull(registeredClientRepository.findByClientId("jeecg-client")), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null);
|
||||
client.setAuthenticated(true);
|
||||
SelfAuthenticationToken selfAuthenticationToken = new SelfAuthenticationToken(client, additionalParameter);
|
||||
selfAuthenticationToken.setAuthenticated(true);
|
||||
OAuth2AccessTokenAuthenticationToken accessToken = (OAuth2AccessTokenAuthenticationToken) selfAuthenticationProvider.authenticate(selfAuthenticationToken);
|
||||
return accessToken.getAccessToken().getTokenValue();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据request中的token获取用户账号
|
||||
* 注意:此方法已适配Sa-Token
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
@ -109,9 +163,9 @@ public class JwtUtil {
|
||||
}
|
||||
return username;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 从session中获取变量
|
||||
* 从session中获取变量
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
@ -122,7 +176,7 @@ public class JwtUtil {
|
||||
String wellNumber = WELL_NUMBER;
|
||||
|
||||
if(key.indexOf(SymbolConstant.RIGHT_CURLY_BRACKET)!=-1){
|
||||
moshi = key.substring(key.indexOf("}")+1);
|
||||
moshi = key.substring(key.indexOf("}")+1);
|
||||
}
|
||||
String returnValue = null;
|
||||
if (key.contains(wellNumber)) {
|
||||
@ -136,16 +190,16 @@ public class JwtUtil {
|
||||
if(returnValue!=null){returnValue = returnValue + moshi;}
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 从当前用户中获取变量
|
||||
* 从当前用户中获取变量
|
||||
* @param key
|
||||
* @param user
|
||||
* @return
|
||||
*/
|
||||
public static String getUserSystemData(String key, SysUserCacheInfo user) {
|
||||
//1.优先获取 SysUserCacheInfo
|
||||
if (user == null) {
|
||||
if(user==null) {
|
||||
try {
|
||||
user = JeecgDataAutorUtils.loadUserInfo();
|
||||
} catch (Exception e) {
|
||||
@ -155,82 +209,84 @@ public class JwtUtil {
|
||||
//2.通过shiro获取登录用户信息
|
||||
LoginUser sysUser = null;
|
||||
try {
|
||||
sysUser = (LoginUser) LoginUserUtils.getSessionUser();
|
||||
sysUser = SecureUtil.currentUser();
|
||||
} catch (Exception e) {
|
||||
log.warn("SecurityUtils.getSubject() 获取用户信息异常:" + e.getMessage());
|
||||
}
|
||||
|
||||
//#{sys_user_code}%
|
||||
String moshi = "";
|
||||
String wellNumber = WELL_NUMBER;
|
||||
if (key.indexOf(SymbolConstant.RIGHT_CURLY_BRACKET) != -1) {
|
||||
moshi = key.substring(key.indexOf("}") + 1);
|
||||
String wellNumber = WELL_NUMBER;
|
||||
if(key.indexOf(SymbolConstant.RIGHT_CURLY_BRACKET)!=-1){
|
||||
moshi = key.substring(key.indexOf("}")+1);
|
||||
}
|
||||
String returnValue = null;
|
||||
//针对特殊标示处理#{sysOrgCode},判断替换
|
||||
if (key.contains(wellNumber)) {
|
||||
key = key.substring(2, key.indexOf("}"));
|
||||
key = key.substring(2,key.indexOf("}"));
|
||||
} else {
|
||||
key = key;
|
||||
}
|
||||
//update-begin---author:chenrui ---date:20250107 for:[QQYUN-10785]数据权限,查看自己拥有部门的权限中存在问题 #7288------------
|
||||
// 是否存在字符串标志
|
||||
boolean multiStr;
|
||||
if (oConvertUtils.isNotEmpty(key) && key.trim().matches("^\\[\\w+]$")) {
|
||||
key = key.substring(1, key.length() - 1);
|
||||
if(oConvertUtils.isNotEmpty(key) && key.trim().matches("^\\[\\w+]$")){
|
||||
key = key.substring(1,key.length()-1);
|
||||
multiStr = true;
|
||||
} else {
|
||||
multiStr = false;
|
||||
}
|
||||
multiStr = false;
|
||||
}
|
||||
//update-end---author:chenrui ---date:20250107 for:[QQYUN-10785]数据权限,查看自己拥有部门的权限中存在问题 #7288------------
|
||||
//替换为当前系统时间(年月日)
|
||||
if (key.equals(DataBaseConstant.SYS_DATE) || key.toLowerCase().equals(DataBaseConstant.SYS_DATE_TABLE)) {
|
||||
if (key.equals(DataBaseConstant.SYS_DATE)|| key.toLowerCase().equals(DataBaseConstant.SYS_DATE_TABLE)) {
|
||||
returnValue = DateUtils.formatDate();
|
||||
}
|
||||
//替换为当前系统时间(年月日时分秒)
|
||||
else if (key.equals(DataBaseConstant.SYS_TIME) || key.toLowerCase().equals(DataBaseConstant.SYS_TIME_TABLE)) {
|
||||
else if (key.equals(DataBaseConstant.SYS_TIME)|| key.toLowerCase().equals(DataBaseConstant.SYS_TIME_TABLE)) {
|
||||
returnValue = DateUtils.now();
|
||||
}
|
||||
//流程状态默认值(默认未发起)
|
||||
else if (key.equals(DataBaseConstant.BPM_STATUS) || key.toLowerCase().equals(DataBaseConstant.BPM_STATUS_TABLE)) {
|
||||
else if (key.equals(DataBaseConstant.BPM_STATUS)|| key.toLowerCase().equals(DataBaseConstant.BPM_STATUS_TABLE)) {
|
||||
returnValue = "1";
|
||||
}
|
||||
|
||||
//后台任务获取用户信息异常,导致程序中断
|
||||
if (sysUser == null && user == null) {
|
||||
if(sysUser==null && user==null){
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
//替换为系统登录用户帐号
|
||||
if (key.equals(DataBaseConstant.SYS_USER_CODE) || key.toLowerCase().equals(DataBaseConstant.SYS_USER_CODE_TABLE)) {
|
||||
if (user == null) {
|
||||
if (key.equals(DataBaseConstant.SYS_USER_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_USER_CODE_TABLE)) {
|
||||
if(user==null) {
|
||||
returnValue = sysUser.getUsername();
|
||||
} else {
|
||||
}else {
|
||||
returnValue = user.getSysUserCode();
|
||||
}
|
||||
}
|
||||
|
||||
// 替换为系统登录用户ID
|
||||
else if (key.equals(DataBaseConstant.SYS_USER_ID) || key.equalsIgnoreCase(DataBaseConstant.SYS_USER_ID_TABLE)) {
|
||||
if (user == null) {
|
||||
if(user==null) {
|
||||
returnValue = sysUser.getId();
|
||||
} else {
|
||||
}else {
|
||||
returnValue = user.getSysUserId();
|
||||
}
|
||||
}
|
||||
|
||||
//替换为系统登录用户真实名字
|
||||
else if (key.equals(DataBaseConstant.SYS_USER_NAME) || key.toLowerCase().equals(DataBaseConstant.SYS_USER_NAME_TABLE)) {
|
||||
if (user == null) {
|
||||
else if (key.equals(DataBaseConstant.SYS_USER_NAME)|| key.toLowerCase().equals(DataBaseConstant.SYS_USER_NAME_TABLE)) {
|
||||
if(user==null) {
|
||||
returnValue = sysUser.getRealname();
|
||||
} else {
|
||||
}else {
|
||||
returnValue = user.getSysUserName();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//替换为系统用户登录所使用的机构编码
|
||||
else if (key.equals(DataBaseConstant.SYS_ORG_CODE) || key.toLowerCase().equals(DataBaseConstant.SYS_ORG_CODE_TABLE)) {
|
||||
if (user == null) {
|
||||
else if (key.equals(DataBaseConstant.SYS_ORG_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_ORG_CODE_TABLE)) {
|
||||
if(user==null) {
|
||||
returnValue = sysUser.getOrgCode();
|
||||
} else {
|
||||
}else {
|
||||
returnValue = user.getSysOrgCode();
|
||||
}
|
||||
}
|
||||
@ -245,17 +301,24 @@ public class JwtUtil {
|
||||
}
|
||||
|
||||
//替换为系统用户所拥有的所有机构编码
|
||||
else if (key.equals(DataBaseConstant.SYS_MULTI_ORG_CODE) || key.toLowerCase().equals(DataBaseConstant.SYS_MULTI_ORG_CODE_TABLE)) {
|
||||
if (user == null) {
|
||||
else if (key.equals(DataBaseConstant.SYS_MULTI_ORG_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_MULTI_ORG_CODE_TABLE)) {
|
||||
if(user==null){
|
||||
//TODO 暂时使用用户登录部门,存在逻辑缺陷,不是用户所拥有的部门
|
||||
returnValue = sysUser.getOrgCode();
|
||||
//update-begin---author:chenrui ---date:20250107 for:[QQYUN-10785]数据权限,查看自己拥有部门的权限中存在问题 #7288------------
|
||||
returnValue = multiStr ? "'" + returnValue + "'" : returnValue;
|
||||
} else {
|
||||
if (user.isOneDepart()) {
|
||||
//update-end---author:chenrui ---date:20250107 for:[QQYUN-10785]数据权限,查看自己拥有部门的权限中存在问题 #7288------------
|
||||
}else{
|
||||
if(user.isOneDepart()) {
|
||||
returnValue = user.getSysMultiOrgCode().get(0);
|
||||
//update-begin---author:chenrui ---date:20250107 for:[QQYUN-10785]数据权限,查看自己拥有部门的权限中存在问题 #7288------------
|
||||
returnValue = multiStr ? "'" + returnValue + "'" : returnValue;
|
||||
} else {
|
||||
//update-end---author:chenrui ---date:20250107 for:[QQYUN-10785]数据权限,查看自己拥有部门的权限中存在问题 #7288------------
|
||||
}else {
|
||||
//update-begin---author:chenrui ---date:20250107 for:[QQYUN-10785]数据权限,查看自己拥有部门的权限中存在问题 #7288------------
|
||||
returnValue = user.getSysMultiOrgCode().stream()
|
||||
.filter(Objects::nonNull)
|
||||
//update-begin---author:chenrui ---date:20250224 for:[issues/7288]数据权限,查看自己拥有部门的权限中存在问题 #7288------------
|
||||
.map(orgCode -> {
|
||||
if (multiStr) {
|
||||
return "'" + orgCode + "'";
|
||||
@ -263,7 +326,9 @@ public class JwtUtil {
|
||||
return orgCode;
|
||||
}
|
||||
})
|
||||
//update-end---author:chenrui ---date:20250224 for:[issues/7288]数据权限,查看自己拥有部门的权限中存在问题 #7288------------
|
||||
.collect(Collectors.joining(", "));
|
||||
//update-end---author:chenrui ---date:20250107 for:[QQYUN-10785]数据权限,查看自己拥有部门的权限中存在问题 #7288------------
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -277,17 +342,21 @@ public class JwtUtil {
|
||||
}
|
||||
}
|
||||
|
||||
// 多租户ID作为系统变量
|
||||
else if (key.equals(TenantConstant.TENANT_ID) || key.toLowerCase().equals(TenantConstant.TENANT_ID_TABLE)) {
|
||||
//update-begin-author:taoyan date:20210330 for:多租户ID作为系统变量
|
||||
else if (key.equals(TenantConstant.TENANT_ID) || key.toLowerCase().equals(TenantConstant.TENANT_ID_TABLE)){
|
||||
try {
|
||||
returnValue = SpringContextUtils.getHttpServletRequest().getHeader(CommonConstant.TENANT_ID);
|
||||
} catch (Exception e) {
|
||||
log.warn("获取系统租户异常:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
if (returnValue != null) {
|
||||
returnValue = returnValue + moshi;
|
||||
}
|
||||
//update-end-author:taoyan date:20210330 for:多租户ID作为系统变量
|
||||
if(returnValue!=null){returnValue = returnValue + moshi;}
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
// public static void main(String[] args) {
|
||||
// String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NjUzMzY1MTMsInVzZXJuYW1lIjoiYWRtaW4ifQ.xjhud_tWCNYBOg_aRlMgOdlZoWFFKB_givNElHNw3X0";
|
||||
// System.out.println(JwtUtil.getUsername(token));
|
||||
// }
|
||||
}
|
||||
|
||||
@ -13,33 +13,31 @@ import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
|
||||
import org.springframework.core.type.classreading.MetadataReader;
|
||||
import org.springframework.core.type.classreading.MetadataReaderFactory;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 枚举字典数据 资源加载工具类
|
||||
*
|
||||
* 资源加载工具类
|
||||
* @Author taoYan
|
||||
* @Date 2022/7/8 10:40
|
||||
**/
|
||||
@Slf4j
|
||||
public class ResourceUtil {
|
||||
|
||||
/**
|
||||
* 多个包扫描根路径
|
||||
*
|
||||
* 之所以让用户手工配置扫描路径,是为了避免不必要的类加载开销,提升启动性能。
|
||||
* 请务必将所有枚举类所在包路径添加到此配置中。
|
||||
*/
|
||||
private final static String[] BASE_SCAN_PACKAGES = {
|
||||
"org.jeecg.common.constant.enums",
|
||||
"org.jeecg.modules.message.enums"
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* 枚举字典数据
|
||||
*/
|
||||
private final static Map<String, List<DictModel>> enumDictData = new HashMap<>(5);
|
||||
|
||||
/**
|
||||
* 所有java类
|
||||
*/
|
||||
private final static String CLASS_PATTERN="/**/*.class";
|
||||
|
||||
/**
|
||||
* 所有枚举java类
|
||||
*/
|
||||
@ -47,9 +45,9 @@ public class ResourceUtil {
|
||||
private final static String CLASS_ENUM_PATTERN="/**/*Enum.class";
|
||||
|
||||
/**
|
||||
* 初始化状态标识
|
||||
* 包路径 org.jeecg
|
||||
*/
|
||||
private static volatile boolean initialized = false;
|
||||
private final static String BASE_PACKAGE = "org.jeecg";
|
||||
|
||||
/**
|
||||
* 枚举类中获取字典数据的方法名
|
||||
@ -57,135 +55,59 @@ public class ResourceUtil {
|
||||
private final static String METHOD_NAME = "getDictList";
|
||||
|
||||
/**
|
||||
* 获取枚举字典数据
|
||||
* 获取枚举类对应的字典数据 SysDictServiceImpl#queryAllDictItems()
|
||||
*
|
||||
* @return 枚举字典数据
|
||||
* @return
|
||||
*/
|
||||
public static Map<String, List<DictModel>> getEnumDictData() {
|
||||
if (!initialized) {
|
||||
synchronized (ResourceUtil.class) {
|
||||
if (!initialized) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
log.info("【枚举字典加载】开始初始化枚举字典数据...");
|
||||
|
||||
initEnumDictData();
|
||||
initialized = true;
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
log.info("【枚举字典加载】枚举字典数据初始化完成,共加载 {} 个字典,总耗时: {}ms", enumDictData.size(), endTime - startTime);
|
||||
public static Map<String, List<DictModel>> getEnumDictData(){
|
||||
if(enumDictData.keySet().size()>0){
|
||||
return enumDictData;
|
||||
}
|
||||
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
|
||||
String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(BASE_PACKAGE) + CLASS_ENUM_PATTERN;
|
||||
try {
|
||||
Resource[] resources = resourcePatternResolver.getResources(pattern);
|
||||
MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
|
||||
for (Resource resource : resources) {
|
||||
MetadataReader reader = readerFactory.getMetadataReader(resource);
|
||||
String classname = reader.getClassMetadata().getClassName();
|
||||
Class<?> clazz = Class.forName(classname);
|
||||
EnumDict enumDict = clazz.getAnnotation(EnumDict.class);
|
||||
if (enumDict != null) {
|
||||
EnumDict annotation = clazz.getAnnotation(EnumDict.class);
|
||||
String key = annotation.value();
|
||||
if(oConvertUtils.isNotEmpty(key)){
|
||||
List<DictModel> list = (List<DictModel>) clazz.getDeclaredMethod(METHOD_NAME).invoke(null);
|
||||
enumDictData.put(key, list);
|
||||
}
|
||||
}
|
||||
}
|
||||
}catch (Exception e){
|
||||
log.error("获取枚举类字典数据异常", e.getMessage());
|
||||
// e.printStackTrace();
|
||||
}
|
||||
return enumDictData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用多包路径扫描方式初始化枚举字典数据
|
||||
*/
|
||||
private static void initEnumDictData() {
|
||||
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
|
||||
|
||||
long scanStartTime = System.currentTimeMillis();
|
||||
List<Resource> allResources = new ArrayList<>();
|
||||
|
||||
// 扫描多个包路径
|
||||
for (String basePackage : BASE_SCAN_PACKAGES) {
|
||||
String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(basePackage) + CLASS_ENUM_PATTERN;
|
||||
|
||||
try {
|
||||
Resource[] resources = resourcePatternResolver.getResources(pattern);
|
||||
allResources.addAll(Arrays.asList(resources));
|
||||
log.debug("【枚举字典加载】扫描包 {} 找到 {} 个枚举类文件", basePackage, resources.length);
|
||||
} catch (Exception e) {
|
||||
log.warn("【枚举字典加载】扫描包 {} 时出现异常: {}", basePackage, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
long scanEndTime = System.currentTimeMillis();
|
||||
log.info("【枚举字典加载】文件扫描完成,总共找到 {} 个枚举类文件,扫描耗时: {}ms", allResources.size(), scanEndTime - scanStartTime);
|
||||
|
||||
MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver);
|
||||
|
||||
long processStartTime = System.currentTimeMillis();
|
||||
int processedCount = 0;
|
||||
|
||||
for (Resource resource : allResources) {
|
||||
try {
|
||||
MetadataReader reader = readerFactory.getMetadataReader(resource);
|
||||
String classname = reader.getClassMetadata().getClassName();
|
||||
|
||||
// 提前检查是否有@EnumDict注解,避免不必要的Class.forName
|
||||
if (hasEnumDictAnnotation(reader)) {
|
||||
processEnumClass(classname);
|
||||
processedCount++;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("处理资源异常: {} - {}", resource.getFilename(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
long processEndTime = System.currentTimeMillis();
|
||||
log.info("【枚举字典加载】处理完成,实际处理 {} 个带注解的枚举类,处理耗时: {}ms", processedCount, processEndTime - processStartTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查类是否有EnumDict注解(通过元数据,避免类加载)
|
||||
*/
|
||||
private static boolean hasEnumDictAnnotation(MetadataReader reader) {
|
||||
try {
|
||||
return reader.getAnnotationMetadata().hasAnnotation(EnumDict.class.getName());
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理单个枚举类
|
||||
*/
|
||||
private static void processEnumClass(String classname) {
|
||||
try {
|
||||
Class<?> clazz = Class.forName(classname);
|
||||
EnumDict enumDict = clazz.getAnnotation(EnumDict.class);
|
||||
|
||||
if (enumDict != null) {
|
||||
String key = enumDict.value();
|
||||
if (oConvertUtils.isNotEmpty(key)) {
|
||||
Method method = clazz.getDeclaredMethod(METHOD_NAME);
|
||||
List<DictModel> list = (List<DictModel>) method.invoke(null);
|
||||
enumDictData.put(key, list);
|
||||
log.debug("成功加载枚举字典: {} -> {}", key, classname);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("处理枚举类异常: {} - {}", classname, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用于后端字典翻译 SysDictServiceImpl#queryManyDictByKeys(java.util.List, java.util.List)
|
||||
*
|
||||
* @param dictCodeList 字典编码列表
|
||||
* @param keys 键值列表
|
||||
* @return 字典数据映射
|
||||
* @param dictCodeList
|
||||
* @param keys
|
||||
* @return
|
||||
*/
|
||||
public static Map<String, List<DictModel>> queryManyDictByKeys(List<String> dictCodeList, List<String> keys) {
|
||||
Map<String, List<DictModel>> enumDict = getEnumDictData();
|
||||
public static Map<String, List<DictModel>> queryManyDictByKeys(List<String> dictCodeList, List<String> keys){
|
||||
if(enumDictData.keySet().size()==0){
|
||||
getEnumDictData();
|
||||
}
|
||||
Map<String, List<DictModel>> map = new HashMap<>();
|
||||
|
||||
// 使用更高效的查找方式
|
||||
Set<String> dictCodeSet = new HashSet<>(dictCodeList);
|
||||
Set<String> keySet = new HashSet<>(keys);
|
||||
|
||||
for (String code : enumDict.keySet()) {
|
||||
if (dictCodeSet.contains(code)) {
|
||||
List<DictModel> dictItemList = enumDict.get(code);
|
||||
for (DictModel dm : dictItemList) {
|
||||
for (String code : enumDictData.keySet()) {
|
||||
if(dictCodeList.indexOf(code)>=0){
|
||||
List<DictModel> dictItemList = enumDictData.get(code);
|
||||
for(DictModel dm: dictItemList){
|
||||
String value = dm.getValue();
|
||||
if (keySet.contains(value)) {
|
||||
if(keys.indexOf(value)>=0){
|
||||
List<DictModel> list = new ArrayList<>();
|
||||
list.add(new DictModel(value, dm.getText()));
|
||||
map.put(code, list);
|
||||
map.put(code,list);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@ -193,5 +115,22 @@ public class ResourceUtil {
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取实现类
|
||||
*
|
||||
* @param classPath
|
||||
*/
|
||||
public static Object getImplementationClass(String classPath){
|
||||
try {
|
||||
Class<?> aClass = Class.forName(classPath);
|
||||
return SpringContextUtils.getBean(aClass);
|
||||
} catch (ClassNotFoundException e) {
|
||||
log.error("类没有找到",e);
|
||||
return null;
|
||||
} catch (NoSuchBeanDefinitionException e){
|
||||
log.error(classPath + "没有实现",e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,22 +1,13 @@
|
||||
package org.jeecg.common.system.util;
|
||||
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.baomidou.mybatisplus.core.metadata.OrderItem;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
import org.jeecg.common.constant.DataBaseConstant;
|
||||
import org.jeecg.common.constant.SymbolConstant;
|
||||
import org.jeecg.common.exception.JeecgBootException;
|
||||
import org.jeecg.common.system.query.QueryGenerator;
|
||||
import org.jeecg.common.system.query.QueryRuleEnum;
|
||||
import org.jeecg.common.util.CommonUtils;
|
||||
import org.jeecg.common.util.oConvertUtils;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@ -248,47 +239,5 @@ public class SqlConcatUtil {
|
||||
private static String getDbType() {
|
||||
return CommonUtils.getDatabaseType();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取前端传过来的 "多字段排序信息: sortInfoString"
|
||||
* @return
|
||||
*/
|
||||
public static List<OrderItem> getQueryConditionOrders(String column, String order, String queryInfoString){
|
||||
List<OrderItem> list = new ArrayList<>();
|
||||
if(oConvertUtils.isEmpty(queryInfoString)){
|
||||
//默认以创建时间倒序查询
|
||||
if(CommonConstant.ORDER_TYPE_DESC.equalsIgnoreCase(order)){
|
||||
list.add(OrderItem.desc(column));
|
||||
}else{
|
||||
list.add(OrderItem.asc(column));
|
||||
}
|
||||
}else{
|
||||
// 【TV360X-967】URL解码(微服务下需要)
|
||||
if (queryInfoString.contains("%22column%22")) {
|
||||
log.info("queryInfoString 原生 = {}", queryInfoString);
|
||||
try {
|
||||
queryInfoString = URLDecoder.decode(queryInfoString, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new JeecgBootException(e);
|
||||
}
|
||||
log.info("queryInfoString 解码 = {}", queryInfoString);
|
||||
}
|
||||
JSONArray array = JSONArray.parseArray(queryInfoString);
|
||||
Iterator it = array.iterator();
|
||||
while(it.hasNext()){
|
||||
JSONObject json = (JSONObject)it.next();
|
||||
String tempColumn = json.getString("column");
|
||||
if(oConvertUtils.isNotEmpty(tempColumn)){
|
||||
String tempOrder = json.getString("order");
|
||||
if(CommonConstant.ORDER_TYPE_DESC.equalsIgnoreCase(tempOrder)){
|
||||
list.add(OrderItem.desc(tempColumn));
|
||||
}else{
|
||||
list.add(OrderItem.asc(tempColumn));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,13 +1,18 @@
|
||||
package org.jeecg.common.system.vo;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.jeecg.common.desensitization.annotation.SensitiveField;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
@ -20,8 +25,10 @@ import java.util.Date;
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Accessors(chain = true)
|
||||
public class LoginUser {
|
||||
public class LoginUser implements Serializable {
|
||||
|
||||
|
||||
private static final long serialVersionUID = -7143159031677245866L;
|
||||
/**
|
||||
* 登录人id
|
||||
*/
|
||||
@ -68,12 +75,6 @@ public class LoginUser {
|
||||
@SensitiveField
|
||||
private String avatar;
|
||||
|
||||
/**
|
||||
* 工号
|
||||
*/
|
||||
@SensitiveField
|
||||
private String workNo;
|
||||
|
||||
/**
|
||||
* 生日
|
||||
*/
|
||||
@ -144,8 +145,29 @@ public class LoginUser {
|
||||
/**设备id uniapp推送用*/
|
||||
private String clientId;
|
||||
|
||||
/**
|
||||
* 主岗位
|
||||
*/
|
||||
private String mainDepPostId;
|
||||
@SensitiveField
|
||||
private String salt;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
// 重新构建对象过滤一些敏感字段
|
||||
LoginUser loginUser = new LoginUser();
|
||||
loginUser.setId(id);
|
||||
loginUser.setUsername(username);
|
||||
loginUser.setRealname(realname);
|
||||
loginUser.setOrgCode(orgCode);
|
||||
loginUser.setSex(sex);
|
||||
loginUser.setEmail(email);
|
||||
loginUser.setPhone(phone);
|
||||
loginUser.setDelFlag(delFlag);
|
||||
loginUser.setStatus(status);
|
||||
loginUser.setActivitiSync(activitiSync);
|
||||
loginUser.setUserIdentity(userIdentity);
|
||||
loginUser.setDepartIds(departIds);
|
||||
loginUser.setPost(post);
|
||||
loginUser.setTelephone(telephone);
|
||||
loginUser.setRelTenantIds(relTenantIds);
|
||||
loginUser.setClientId(clientId);
|
||||
return JSON.toJSONString(loginUser);
|
||||
}
|
||||
}
|
||||
|
||||
@ -25,7 +25,6 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.SQLException;
|
||||
@ -153,9 +152,9 @@ public class CommonUtils {
|
||||
*/
|
||||
public static String uploadLocal(MultipartFile mf,String bizPath,String uploadpath){
|
||||
try {
|
||||
// 文件安全校验,防止上传漏洞文件
|
||||
SsrfFileTypeFilter.checkUploadFileType(mf, bizPath);
|
||||
|
||||
//update-begin-author:liusq date:20210809 for: 过滤上传文件类型
|
||||
SsrfFileTypeFilter.checkUploadFileType(mf);
|
||||
//update-end-author:liusq date:20210809 for: 过滤上传文件类型
|
||||
String fileName = null;
|
||||
File file = new File(uploadpath + File.separator + bizPath + File.separator );
|
||||
if (!file.exists()) {
|
||||
@ -164,10 +163,6 @@ public class CommonUtils {
|
||||
}
|
||||
// 获取文件名
|
||||
String orgName = mf.getOriginalFilename();
|
||||
// 无中文情况下进行转码
|
||||
if (orgName != null && !CommonUtils.ifContainChinese(orgName)) {
|
||||
orgName = new String(orgName.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
|
||||
}
|
||||
orgName = CommonUtils.getFileName(orgName);
|
||||
if(orgName.indexOf(SymbolConstant.SPOT)!=-1){
|
||||
fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
|
||||
@ -247,10 +242,6 @@ public class CommonUtils {
|
||||
try {
|
||||
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
|
||||
dbTypeEnum = JdbcUtils.getDbType(dataSource.getConnection().getMetaData().getURL());
|
||||
//【采用SQL_SERVER2005引擎】QQYUN-13298 解决升级mybatisPlus后SqlServer分页使用OFFSET,无排序字段报错问题
|
||||
if (dbTypeEnum == DbType.SQL_SERVER) {
|
||||
dbTypeEnum = DbType.SQL_SERVER2005;
|
||||
}
|
||||
return dbTypeEnum;
|
||||
} catch (SQLException e) {
|
||||
log.warn(e.getMessage(), e);
|
||||
|
||||
@ -13,8 +13,6 @@ import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
@ -816,44 +814,4 @@ public class DateUtils extends PropertyEditorSupport {
|
||||
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取两个日期之间的所有日期列表,包含开始和结束日期
|
||||
*
|
||||
* @param begin
|
||||
* @param end
|
||||
* @return
|
||||
*/
|
||||
public static List<Date> getDateRangeList(Date begin, Date end) {
|
||||
List<Date> dateList = new ArrayList<>();
|
||||
if (begin == null || end == null) {
|
||||
return dateList;
|
||||
}
|
||||
|
||||
// 清除时间部分,只比较日期
|
||||
Calendar beginCal = Calendar.getInstance();
|
||||
beginCal.setTime(begin);
|
||||
beginCal.set(Calendar.HOUR_OF_DAY, 0);
|
||||
beginCal.set(Calendar.MINUTE, 0);
|
||||
beginCal.set(Calendar.SECOND, 0);
|
||||
beginCal.set(Calendar.MILLISECOND, 0);
|
||||
|
||||
Calendar endCal = Calendar.getInstance();
|
||||
endCal.setTime(end);
|
||||
endCal.set(Calendar.HOUR_OF_DAY, 0);
|
||||
endCal.set(Calendar.MINUTE, 0);
|
||||
endCal.set(Calendar.SECOND, 0);
|
||||
endCal.set(Calendar.MILLISECOND, 0);
|
||||
|
||||
if (endCal.before(beginCal)) {
|
||||
return dateList;
|
||||
}
|
||||
|
||||
dateList.add(beginCal.getTime());
|
||||
while (beginCal.before(endCal)) {
|
||||
beginCal.add(Calendar.DAY_OF_YEAR, 1);
|
||||
dateList.add(beginCal.getTime());
|
||||
}
|
||||
return dateList;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,22 +1,14 @@
|
||||
package org.jeecg.common.util;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import cn.hutool.core.io.IoUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
import org.jeecg.common.exception.JeecgBootException;
|
||||
import org.jeecg.common.util.filter.SsrfFileTypeFilter;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
@ -211,150 +203,4 @@ public class FileDownloadUtils {
|
||||
dir.mkdirs();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 下载单个文件到ZIP流
|
||||
* 核心功能:获取文件流,写入ZIP条目
|
||||
* @param fileUrl 文件URL(可以是HTTP URL或本地路径)
|
||||
* @param fileName ZIP内的文件名
|
||||
* @param zous ZIP输出流
|
||||
*/
|
||||
public static void downLoadSingleFile(String fileUrl, String fileName, String uploadUrl,ZipArchiveOutputStream zous) {
|
||||
InputStream inputStream = null;
|
||||
try {
|
||||
// 创建ZIP条目:每个文件在ZIP中都是一个独立条目
|
||||
ZipArchiveEntry entry = new ZipArchiveEntry(fileName);
|
||||
zous.putArchiveEntry(entry);
|
||||
|
||||
// 获取文件输入流:区分普通文件和快捷方式
|
||||
if (fileUrl.endsWith(".url")) {
|
||||
// 处理快捷方式:生成.url文件内容
|
||||
inputStream = FileDownloadUtils.createInternetShortcut(fileName, fileUrl, "");
|
||||
} else {
|
||||
// 普通文件下载:从URL或本地路径获取流
|
||||
inputStream = getDownInputStream(fileUrl,uploadUrl);
|
||||
}
|
||||
|
||||
if (inputStream != null) {
|
||||
// 将文件流写入ZIP
|
||||
IOUtils.copy(inputStream, zous);
|
||||
}
|
||||
// 关闭当前ZIP条目
|
||||
zous.closeArchiveEntry();
|
||||
} catch (IOException e) {
|
||||
log.error("文件下载失败: {}", e);
|
||||
} finally {
|
||||
// 确保输入流关闭
|
||||
IoUtil.close(inputStream);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下载文件输入流
|
||||
* 功能:根据URL类型(HTTP或本地)获取文件流
|
||||
* @param fileUrl 文件URL(支持HTTP和本地路径)
|
||||
* @return 文件输入流,失败返回null
|
||||
*/
|
||||
public static InputStream getDownInputStream(String fileUrl, String uploadUrl) {
|
||||
try {
|
||||
// 处理HTTP URL:通过网络下载
|
||||
if (oConvertUtils.isNotEmpty(fileUrl) && fileUrl.startsWith(CommonConstant.STR_HTTP)) {
|
||||
URL url = new URL(fileUrl);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setConnectTimeout(5000); // 连接超时5秒
|
||||
connection.setReadTimeout(30000); // 读取超时30秒
|
||||
return connection.getInputStream();
|
||||
} else {
|
||||
// 处理本地文件:直接读取文件系统
|
||||
String downloadFilePath = uploadUrl + File.separator + fileUrl;
|
||||
// 安全检查:防止下载危险文件类型
|
||||
SsrfFileTypeFilter.checkDownloadFileType(downloadFilePath);
|
||||
return new BufferedInputStream(new FileInputStream(downloadFilePath));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// 异常时返回null,上层会处理空流情况
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件扩展名
|
||||
* 功能:从文件名中提取扩展名
|
||||
* @param fileName 文件名
|
||||
* @return 文件扩展名(不含点),如"txt"、"png"
|
||||
*/
|
||||
public static String getFileExtension(String fileName) {
|
||||
int dotIndex = fileName.lastIndexOf('.');
|
||||
return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建快捷方式(.url文件内容)
|
||||
* 功能:生成Internet快捷方式文件内容
|
||||
* @param name 快捷方式名称
|
||||
* @param url 目标URL地址
|
||||
* @param icon 图标路径(可选)
|
||||
* @return 包含.url文件内容的输入流
|
||||
*/
|
||||
public static InputStream createInternetShortcut(String name, String url, String icon) {
|
||||
StringWriter sw = new StringWriter();
|
||||
try {
|
||||
// 按照Windows快捷方式格式写入内容
|
||||
sw.write("[InternetShortcut]\n");
|
||||
sw.write("URL=" + url + "\n");
|
||||
if (oConvertUtils.isNotEmpty(icon)) {
|
||||
sw.write("IconFile=" + icon + "\n");
|
||||
}
|
||||
// 将字符串内容转换为输入流
|
||||
return new ByteArrayInputStream(sw.toString().getBytes(StandardCharsets.UTF_8));
|
||||
} finally {
|
||||
IoUtil.close(sw);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 从URL中提取文件名
|
||||
* 功能:从HTTP URL或本地路径中提取纯文件名
|
||||
* @param fileUrl 文件URL
|
||||
* @return 文件名(不含路径)
|
||||
*/
|
||||
public static String getFileNameFromUrl(String fileUrl) {
|
||||
try {
|
||||
// 处理HTTP URL:从路径部分提取文件名
|
||||
if (fileUrl.startsWith(CommonConstant.STR_HTTP)) {
|
||||
URL url = new URL(fileUrl);
|
||||
String path = url.getPath();
|
||||
return path.substring(path.lastIndexOf('/') + 1);
|
||||
}
|
||||
|
||||
// 处理本地文件路径:从文件路径提取文件名
|
||||
return fileUrl.substring(fileUrl.lastIndexOf(File.separator) + 1);
|
||||
} catch (Exception e) {
|
||||
// 如果解析失败,使用时间戳作为文件名
|
||||
return "file_" + System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 生成ZIP中的文件名
|
||||
* 功能:避免文件名冲突,为多个文件添加序号
|
||||
* @param fileUrl 文件URL(用于提取原始文件名)
|
||||
* @param index 文件序号(从0开始)
|
||||
* @param total 文件总数
|
||||
* @return 处理后的文件名(带序号)
|
||||
*/
|
||||
public static String generateFileName(String fileUrl, int index, int total) {
|
||||
// 从URL中提取原始文件名
|
||||
String originalFileName = getFileNameFromUrl(fileUrl);
|
||||
|
||||
// 如果只有一个文件,直接使用原始文件名
|
||||
if (total == 1) {
|
||||
return originalFileName;
|
||||
}
|
||||
|
||||
// 多个文件时,使用序号+原始文件名
|
||||
String extension = getFileExtension(originalFileName);
|
||||
String nameWithoutExtension = originalFileName.replace("." + extension, "");
|
||||
|
||||
return String.format("%s_%d.%s", nameWithoutExtension, index + 1, extension);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,175 +0,0 @@
|
||||
package org.jeecg.common.util;
|
||||
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jeecg.common.system.vo.LoginUser;
|
||||
|
||||
/**
|
||||
* 登录用户工具类
|
||||
* 替代原有的Shiro SecurityUtils工具类
|
||||
* @author jeecg-boot
|
||||
*/
|
||||
@Slf4j
|
||||
public class LoginUserUtils {
|
||||
|
||||
/**
|
||||
* Session中存储登录用户信息的key
|
||||
*/
|
||||
private static final String SESSION_KEY_LOGIN_USER = "loginUser";
|
||||
|
||||
/**
|
||||
* 执行登录并设置用户信息到Session(推荐)
|
||||
*
|
||||
* <p>此方法会:
|
||||
* <ul>
|
||||
* <li>1. 调用 StpUtil.login(username) 生成token和session</li>
|
||||
* <li>2. 将 LoginUser 存入 Session 缓存(清除不必要的字段(密码等15个字段)</li>
|
||||
* <li>3. 返回生成的 token</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param sysUser 完整的用户对象(从数据库查询得到)
|
||||
* @return 生成的 token
|
||||
*/
|
||||
public static String doLogin(LoginUser sysUser) {
|
||||
if (sysUser == null) {
|
||||
throw new IllegalArgumentException("用户对象不能为空");
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. 获取 username
|
||||
String username = sysUser.getUsername();
|
||||
|
||||
if (username == null || username.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("用户名不能为空");
|
||||
}
|
||||
|
||||
// 2. Sa-Token 登录(使用 username 作为 loginId)
|
||||
StpUtil.login(username);
|
||||
|
||||
// 3. 用户信息到 LoginUser 并存入 Session
|
||||
setSessionUser(sysUser);
|
||||
|
||||
// 4. 返回生成的 token
|
||||
return StpUtil.getTokenValue();
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("登录失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录用户信息
|
||||
*
|
||||
* <p>说明:
|
||||
* <ul>
|
||||
* <li>对于需要认证的接口:Sa-Token Filter 已经校验过登录状态,此方法必然能获取到用户</li>
|
||||
* <li>对于已排除拦截的接口:如果未登录或获取失败则返回 null,由业务代码自行判断处理</li>
|
||||
* </ul>
|
||||
*
|
||||
* @return 登录用户对象,如果未登录或session中没有则返回null
|
||||
*/
|
||||
public static LoginUser getSessionUser() {
|
||||
// 尝试从Sa-Token的Session中获取用户信息
|
||||
Object loginUser = StpUtil.getSession().get(SESSION_KEY_LOGIN_USER);
|
||||
if (loginUser instanceof LoginUser) {
|
||||
return (LoginUser) loginUser;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据指定的 token 获取登录用户信息
|
||||
*
|
||||
* <p>适用场景:已排除拦截的接口(如 WebSocket),需要显式传入 token 来获取用户信息
|
||||
*
|
||||
* <p>实现方式:临时切换到该 token 对应的会话,然后获取用户信息
|
||||
*
|
||||
* @param token JWT token
|
||||
* @return 登录用户对象,如果 token 无效或session中没有则返回null
|
||||
*/
|
||||
public static LoginUser getSessionUser(String token) {
|
||||
try {
|
||||
// 根据 token 获取登录ID
|
||||
Object loginId = StpUtil.getLoginIdByToken(token);
|
||||
if (loginId == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 临时切换到该 token 对应的登录会话
|
||||
StpUtil.switchTo(loginId);
|
||||
|
||||
// 直接调用无参方法获取用户信息
|
||||
return getSessionUser();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.debug("根据token获取用户信息失败: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 设置当前登录用户信息到Session
|
||||
*
|
||||
* <p>为减少 Redis 存储和保障安全,只保留必要的核心字段:
|
||||
* <ul>
|
||||
* <li>id, username, realname - 基础用户信息</li>
|
||||
* <li>orgCode, orgId, departIds - 部门和数据权限</li>
|
||||
* <li>roleCode - 角色权限</li>
|
||||
* <li>loginTenantId, relTenantIds - 多租户</li>
|
||||
* <li>avatar - 用户头像</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>⚠️ 注意:调用此方法前需要先调用 StpUtil.login()
|
||||
*
|
||||
* @param loginUser 登录用户对象
|
||||
*/
|
||||
public static void setSessionUser(LoginUser loginUser) {
|
||||
if (loginUser == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ⚠️ 安全与性能:清除不必要的字段,减少 Redis 存储
|
||||
loginUser.setPassword(null); // 密码(安全)
|
||||
loginUser.setWorkNo(null); // 工号
|
||||
loginUser.setBirthday(null); // 生日
|
||||
loginUser.setSex(null); // 性别
|
||||
loginUser.setEmail(null); // 邮箱
|
||||
loginUser.setPhone(null); // 手机号
|
||||
loginUser.setStatus(null); // 状态
|
||||
loginUser.setDelFlag(null); // 删除标志
|
||||
loginUser.setActivitiSync(null); // 工作流同步
|
||||
loginUser.setCreateTime(null); // 创建时间
|
||||
loginUser.setUserIdentity(null); // 用户身份
|
||||
loginUser.setPost(null); // 职务
|
||||
loginUser.setTelephone(null); // 座机
|
||||
loginUser.setRelTenantIds(null); // 关联租户
|
||||
loginUser.setMainDepPostId(null); // 主岗位
|
||||
|
||||
StpUtil.getSession().set(SESSION_KEY_LOGIN_USER, loginUser);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录用户名(推荐使用此方法,语义更清晰)
|
||||
* @return 用户名(username)
|
||||
*/
|
||||
public static String getUsername() {
|
||||
return StpUtil.getLoginIdAsString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否已登录
|
||||
* @return true-已登录,false-未登录
|
||||
*/
|
||||
public static boolean isLogin() {
|
||||
return StpUtil.isLogin();
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
*/
|
||||
public static void logout() {
|
||||
StpUtil.logout();
|
||||
}
|
||||
}
|
||||
|
||||
@ -55,11 +55,13 @@ public class MinioUtil {
|
||||
*/
|
||||
public static String upload(MultipartFile file, String bizPath, String customBucket) throws Exception {
|
||||
String fileUrl = "";
|
||||
// 业务路径过滤,防止攻击
|
||||
//update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
|
||||
bizPath = StrAttackFilter.filter(bizPath);
|
||||
//update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
|
||||
|
||||
// 文件安全校验,防止上传漏洞文件
|
||||
SsrfFileTypeFilter.checkUploadFileType(file, bizPath);
|
||||
//update-begin-author:liusq date:20210809 for: 过滤上传文件类型
|
||||
SsrfFileTypeFilter.checkUploadFileType(file);
|
||||
//update-end-author:liusq date:20210809 for: 过滤上传文件类型
|
||||
|
||||
String newBucket = bucketName;
|
||||
if(oConvertUtils.isNotEmpty(customBucket)){
|
||||
|
||||
@ -2,7 +2,6 @@ package org.jeecg.common.util;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
@ -17,7 +16,6 @@ import java.util.List;
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@Lazy(false)
|
||||
public class PmsUtil {
|
||||
|
||||
|
||||
|
||||
@ -4,7 +4,7 @@ import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@ -56,22 +56,12 @@ public class RestUtil {
|
||||
private final static RestTemplate RT;
|
||||
|
||||
static {
|
||||
//update-begin---author:chenrui ---date:20251011 for:[issues/8859]online表单java增强失效------------
|
||||
// 使用 Apache HttpClient 避免 JDK HttpURLConnection 的 too many bytes written 问题
|
||||
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
//update-end---author:chenrui ---date:20251011 for:[issues/8859]online表单java增强失效------------
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
|
||||
requestFactory.setConnectTimeout(30000);
|
||||
requestFactory.setReadTimeout(30000);
|
||||
RT = new RestTemplate(requestFactory);
|
||||
//update-begin---author:chenrui ---date:20251011 for:[issues/8859]online表单java增强失效------------
|
||||
// 解决乱码问题(替换 StringHttpMessageConverter 为 UTF-8)
|
||||
for (int i = 0; i < RT.getMessageConverters().size(); i++) {
|
||||
if (RT.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
|
||||
RT.getMessageConverters().set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
|
||||
break;
|
||||
}
|
||||
}
|
||||
//update-end---author:chenrui ---date:20251011 for:[issues/8859]online表单java增强失效------------
|
||||
// 解决乱码问题
|
||||
RT.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static RestTemplate getRestTemplate() {
|
||||
@ -231,72 +221,6 @@ public class RestUtil {
|
||||
return RT.exchange(url, method, request, responseType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送请求(支持自定义超时时间)
|
||||
*
|
||||
* @param url 请求地址
|
||||
* @param method 请求方式
|
||||
* @param headers 请求头 可空
|
||||
* @param variables 请求url参数 可空
|
||||
* @param params 请求body参数 可空
|
||||
* @param responseType 返回类型
|
||||
* @param timeout 超时时间(毫秒),如果为0或负数则使用默认超时
|
||||
* @return ResponseEntity<responseType>
|
||||
*/
|
||||
public static <T> ResponseEntity<T> request(String url, HttpMethod method, HttpHeaders headers,
|
||||
JSONObject variables, Object params, Class<T> responseType, int timeout) {
|
||||
log.info(" RestUtil --- request --- url = "+ url + ", timeout = " + timeout);
|
||||
|
||||
if (StringUtils.isEmpty(url)) {
|
||||
throw new RuntimeException("url 不能为空");
|
||||
}
|
||||
if (method == null) {
|
||||
throw new RuntimeException("method 不能为空");
|
||||
}
|
||||
if (headers == null) {
|
||||
headers = new HttpHeaders();
|
||||
}
|
||||
|
||||
// 创建自定义RestTemplate(如果需要设置超时)
|
||||
RestTemplate restTemplate = RT;
|
||||
if (timeout > 0) {
|
||||
//update-begin---author:chenrui ---date:20251011 for:[issues/8859]online表单java增强失效------------
|
||||
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
//update-end---author:chenrui ---date:20251011 for:[issues/8859]online表单java增强失效------------
|
||||
requestFactory.setConnectTimeout(timeout);
|
||||
requestFactory.setReadTimeout(timeout);
|
||||
restTemplate = new RestTemplate(requestFactory);
|
||||
//update-begin---author:chenrui ---date:20251011 for:[issues/8859]online表单java增强失效------------
|
||||
// 解决乱码问题(替换 StringHttpMessageConverter 为 UTF-8)
|
||||
for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) {
|
||||
if (restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
|
||||
restTemplate.getMessageConverters().set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
|
||||
break;
|
||||
}
|
||||
}
|
||||
//update-end---author:chenrui ---date:20251011 for:[issues/8859]online表单java增强失效------------
|
||||
}
|
||||
|
||||
// 请求体
|
||||
String body = "";
|
||||
if (params != null) {
|
||||
if (params instanceof JSONObject) {
|
||||
body = ((JSONObject) params).toJSONString();
|
||||
} else {
|
||||
body = params.toString();
|
||||
}
|
||||
}
|
||||
|
||||
// 拼接 url 参数
|
||||
if (variables != null && !variables.isEmpty()) {
|
||||
url += ("?" + asUrlVariables(variables));
|
||||
}
|
||||
|
||||
// 发送请求
|
||||
HttpEntity<String> request = new HttpEntity<>(body, headers);
|
||||
return restTemplate.exchange(url, method, request, responseType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取JSON请求头
|
||||
*/
|
||||
|
||||
@ -8,7 +8,6 @@ import org.jeecg.common.constant.ServiceNameConstants;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
@ -17,7 +16,6 @@ import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
* @Description: spring上下文工具类
|
||||
* @author: jeecg-boot
|
||||
*/
|
||||
@Lazy(false)
|
||||
@Component
|
||||
public class SpringContextUtils implements ApplicationContextAware {
|
||||
|
||||
|
||||
@ -16,13 +16,7 @@ import java.util.regex.Pattern;
|
||||
* @author zhoujf
|
||||
*/
|
||||
@Slf4j
|
||||
public class SqlInjectionUtil {
|
||||
|
||||
/**
|
||||
* sql注入黑名单数据库名
|
||||
*/
|
||||
public final static String XSS_STR_TABLE = "peformance_schema|information_schema";
|
||||
|
||||
public class SqlInjectionUtil {
|
||||
/**
|
||||
* 默认—sql注入关键词
|
||||
*/
|
||||
@ -173,28 +167,7 @@ public class SqlInjectionUtil {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否存在SQL注入关键词字符串
|
||||
*
|
||||
* @param keyword
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("AlibabaUndefineMagicConstant")
|
||||
private static boolean isExistSqlInjectTableKeyword(String sql, String keyword) {
|
||||
// 需要匹配的,sql注入关键词
|
||||
String[] matchingTexts = new String[]{"`" + keyword, "(" + keyword, "(`" + keyword};
|
||||
for (String matchingText : matchingTexts) {
|
||||
String[] checkTexts = new String[]{" " + matchingText, "from" + matchingText};
|
||||
for (String checkText : checkTexts) {
|
||||
if (sql.contains(checkText)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* sql注入过滤处理,遇到注入关键字抛异常
|
||||
*
|
||||
@ -235,14 +208,6 @@ public class SqlInjectionUtil {
|
||||
throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value);
|
||||
}
|
||||
}
|
||||
String[] xssTableArr = XSS_STR_TABLE.split("\\|");
|
||||
for (String xssTableStr : xssTableArr) {
|
||||
if (isExistSqlInjectTableKeyword(value, xssTableStr)) {
|
||||
log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssTableStr);
|
||||
log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value);
|
||||
throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value);
|
||||
}
|
||||
}
|
||||
|
||||
// 三、SQL注入检测存在绕过风险 (正则校验)
|
||||
for (String regularOriginal : XSS_REGULAR_STR_ARRAY) {
|
||||
@ -279,14 +244,6 @@ public class SqlInjectionUtil {
|
||||
throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value);
|
||||
}
|
||||
}
|
||||
String[] xssTableArr = XSS_STR_TABLE.split("\\|");
|
||||
for (String xssTableStr : xssTableArr) {
|
||||
if (isExistSqlInjectTableKeyword(value, xssTableStr)) {
|
||||
log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssTableStr);
|
||||
log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value);
|
||||
throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value);
|
||||
}
|
||||
}
|
||||
|
||||
// 三、SQL注入检测存在绕过风险 (正则校验)
|
||||
for (String regularOriginal : XSS_REGULAR_STR_ARRAY) {
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
package org.jeecg.common.util;
|
||||
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jeecg.common.api.CommonAPI;
|
||||
@ -12,8 +12,6 @@ import org.jeecg.common.exception.JeecgBoot401Exception;
|
||||
import org.jeecg.common.system.util.JwtUtil;
|
||||
import org.jeecg.common.system.vo.LoginUser;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* @Author scott
|
||||
* @Date 2019/9/23 14:12
|
||||
@ -66,10 +64,6 @@ public class TokenUtils {
|
||||
if (tenantId == null) {
|
||||
tenantId = oConvertUtils.getString(request.getHeader(CommonConstant.TENANT_ID));
|
||||
}
|
||||
|
||||
if (oConvertUtils.isNotEmpty(tenantId) && "undefined".equals(tenantId)) {
|
||||
return null;
|
||||
}
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
@ -88,42 +82,68 @@ public class TokenUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证Token(已重写为Sa-Token实现)
|
||||
* 验证Token
|
||||
*/
|
||||
public static boolean verifyToken(HttpServletRequest request, CommonAPI commonApi) {
|
||||
public static boolean verifyToken(HttpServletRequest request, CommonAPI commonApi, RedisUtil redisUtil) {
|
||||
log.debug(" -- url --" + request.getRequestURL());
|
||||
String token = getTokenByRequest(request);
|
||||
return TokenUtils.verifyToken(token, commonApi);
|
||||
return TokenUtils.verifyToken(token, commonApi, redisUtil);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证Token(已重写为Sa-Token实现)
|
||||
* 验证Token
|
||||
*/
|
||||
public static boolean verifyToken(String token, CommonAPI commonApi) {
|
||||
public static boolean verifyToken(String token, CommonAPI commonApi, RedisUtil redisUtil) {
|
||||
if (StringUtils.isBlank(token)) {
|
||||
throw new JeecgBoot401Exception("token不能为空!");
|
||||
}
|
||||
|
||||
// 使用Sa-Token校验token
|
||||
Object username = StpUtil.getLoginIdByToken(token);
|
||||
// 解密获得username,用于和数据库进行对比
|
||||
String username = JwtUtil.getUsername(token);
|
||||
if (username == null) {
|
||||
throw new JeecgBoot401Exception("token非法无效!");
|
||||
}
|
||||
|
||||
// 查询用户信息
|
||||
LoginUser user = commonApi.getUserByName(username.toString());
|
||||
//LoginUser user = TokenUtils.getLoginUser(username, commonApi, redisUtil);
|
||||
LoginUser user = commonApi.getUserByName(username);
|
||||
if (user == null) {
|
||||
throw new JeecgBoot401Exception("用户不存在!");
|
||||
}
|
||||
|
||||
// 判断用户状态
|
||||
if (user.getStatus() != 1) {
|
||||
throw new JeecgBoot401Exception("账号已被锁定,请联系管理员!");
|
||||
}
|
||||
|
||||
// 校验token是否超时失效 & 或者账号密码是否错误
|
||||
if (!jwtTokenRefresh(token, username, user.getPassword(), redisUtil)) {
|
||||
throw new JeecgBoot401Exception(CommonConstant.TOKEN_IS_INVALID_MSG);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新token(保证用户在线操作不掉线)
|
||||
* @param token
|
||||
* @param userName
|
||||
* @param passWord
|
||||
* @param redisUtil
|
||||
* @return
|
||||
*/
|
||||
private static boolean jwtTokenRefresh(String token, String userName, String passWord, RedisUtil redisUtil) {
|
||||
String cacheToken = oConvertUtils.getString(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
|
||||
if (oConvertUtils.isNotEmpty(cacheToken)) {
|
||||
// 校验token有效性
|
||||
if (!JwtUtil.verify(cacheToken, userName, passWord)) {
|
||||
String newAuthorization = JwtUtil.sign(userName, passWord);
|
||||
// 设置Toekn缓存有效时间
|
||||
redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
|
||||
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取登录用户
|
||||
*
|
||||
@ -137,10 +157,11 @@ public class TokenUtils {
|
||||
//【重要】此处通过redis原生获取缓存用户,是为了解决微服务下system服务挂了,其他服务互调不通问题---
|
||||
if (redisUtil.hasKey(loginUserKey)) {
|
||||
try {
|
||||
loginUser = (LoginUser) redisUtil.get(loginUserKey);
|
||||
Object obj = redisUtil.get(loginUserKey);
|
||||
loginUser = (LoginUser) obj;
|
||||
//解密用户
|
||||
SensitiveInfoUtil.handlerObject(loginUser, false);
|
||||
} catch (IllegalAccessException e) {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
@ -149,5 +170,4 @@ public class TokenUtils {
|
||||
}
|
||||
return loginUser;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -68,13 +68,6 @@ public class DbTypeUtils {
|
||||
return dbTypeIf(dbType, DbType.ORACLE, DbType.ORACLE_12C, DbType.DM);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否是达梦
|
||||
*/
|
||||
public static boolean dbTypeIsDm(DbType dbType) {
|
||||
return dbTypeIf(dbType, DbType.DM);
|
||||
}
|
||||
|
||||
public static boolean dbTypeIsSqlServer(DbType dbType) {
|
||||
return dbTypeIf(dbType, DbType.SQL_SERVER, DbType.SQL_SERVER2005);
|
||||
}
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
package org.jeecg.common.util.encryption;
|
||||
|
||||
import java.util.Base64;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* @Description: AES 加密
|
||||
|
||||
@ -2,7 +2,6 @@ package org.jeecg.common.util.filter;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jeecg.common.exception.JeecgBootException;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
@ -35,7 +34,6 @@ public class SsrfFileTypeFilter {
|
||||
FILE_TYPE_WHITE_LIST.add("bmp");
|
||||
FILE_TYPE_WHITE_LIST.add("svg");
|
||||
FILE_TYPE_WHITE_LIST.add("ico");
|
||||
FILE_TYPE_WHITE_LIST.add("heic");
|
||||
|
||||
//文本文件
|
||||
FILE_TYPE_WHITE_LIST.add("txt");
|
||||
@ -150,38 +148,29 @@ public class SsrfFileTypeFilter {
|
||||
public static void checkDownloadFileType(String filePath) throws IOException {
|
||||
//文件后缀
|
||||
String suffix = getFileTypeBySuffix(filePath);
|
||||
log.debug(" 【文件下载校验】文件后缀 suffix: {}", suffix);
|
||||
log.info("suffix:{}", suffix);
|
||||
boolean isAllowExtension = FILE_TYPE_WHITE_LIST.contains(suffix.toLowerCase());
|
||||
//是否允许下载的文件
|
||||
if (!isAllowExtension) {
|
||||
throw new JeecgBootException("下载失败,存在非法文件类型:" + suffix);
|
||||
throw new IOException("下载失败,存在非法文件类型:" + suffix);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 上传文件类型过滤
|
||||
*
|
||||
* @param file
|
||||
*/
|
||||
public static void checkUploadFileType(MultipartFile file) throws Exception {
|
||||
checkUploadFileType(file, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件类型过滤
|
||||
*
|
||||
* @param file
|
||||
*/
|
||||
public static void checkUploadFileType(MultipartFile file, String customPath) throws Exception {
|
||||
//1. 路径安全校验
|
||||
validatePathSecurity(customPath);
|
||||
//2. 校验文件后缀和头
|
||||
String suffix = getFileType(file, customPath);
|
||||
log.info("【文件上传校验】文件后缀 suffix: {},customPath:{}", suffix, customPath);
|
||||
//获取文件真是后缀
|
||||
String suffix = getFileType(file);
|
||||
|
||||
log.info("suffix:{}", suffix);
|
||||
boolean isAllowExtension = FILE_TYPE_WHITE_LIST.contains(suffix.toLowerCase());
|
||||
//是否允许下载的文件
|
||||
if (!isAllowExtension) {
|
||||
throw new JeecgBootException("上传失败,存在非法文件类型:" + suffix);
|
||||
throw new Exception("上传失败,存在非法文件类型:" + suffix);
|
||||
}
|
||||
}
|
||||
|
||||
@ -193,7 +182,7 @@ public class SsrfFileTypeFilter {
|
||||
* @throws Exception
|
||||
*/
|
||||
|
||||
private static String getFileType(MultipartFile file, String customPath) throws Exception {
|
||||
private static String getFileType(MultipartFile file) throws Exception {
|
||||
//update-begin-author:liusq date:20230404 for: [issue/4672]方法造成的文件被占用,注释掉此方法tomcat就能自动清理掉临时文件
|
||||
String fileExtendName = null;
|
||||
InputStream is = null;
|
||||
@ -213,7 +202,7 @@ public class SsrfFileTypeFilter {
|
||||
break;
|
||||
}
|
||||
}
|
||||
log.debug("-----获取到的指定文件类型------"+fileExtendName);
|
||||
log.info("-----获取到的指定文件类型------"+fileExtendName);
|
||||
// 如果不是上述类型,则判断扩展名
|
||||
if (StringUtils.isBlank(fileExtendName)) {
|
||||
String fileName = file.getOriginalFilename();
|
||||
@ -224,6 +213,7 @@ public class SsrfFileTypeFilter {
|
||||
// 如果有扩展名,则返回扩展名
|
||||
return getFileTypeBySuffix(fileName);
|
||||
}
|
||||
log.info("-----最終的文件类型------"+fileExtendName);
|
||||
is.close();
|
||||
return fileExtendName;
|
||||
} catch (Exception e) {
|
||||
@ -258,34 +248,4 @@ public class SsrfFileTypeFilter {
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 路径安全校验
|
||||
*/
|
||||
private static void validatePathSecurity(String customPath) throws JeecgBootException {
|
||||
if (customPath == null || customPath.trim().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 统一分隔符为 /
|
||||
String normalized = customPath.replace("\\", "/");
|
||||
|
||||
// 1. 防止路径遍历攻击
|
||||
if (normalized.contains("..") || normalized.contains("~")) {
|
||||
throw new JeecgBootException("上传业务路径包含非法字符!");
|
||||
}
|
||||
|
||||
// 2. 限制路径深度
|
||||
int depth = normalized.split("/").length;
|
||||
if (depth > 5) {
|
||||
throw new JeecgBootException("上传业务路径深度超出限制!");
|
||||
}
|
||||
|
||||
// 3. 限制字符集(只允许字母、数字、下划线、横线、斜杠)
|
||||
if (!normalized.matches("^[a-zA-Z0-9/_-]+$")) {
|
||||
throw new JeecgBootException("上传业务路径包含非法字符!");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -7,7 +7,6 @@ import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
import org.jeecg.common.constant.SymbolConstant;
|
||||
import org.jeecg.config.mybatis.MybatisPlusSaasConfig;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
@ -474,23 +473,6 @@ public class oConvertUtils {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符串是否为JSON格式
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static boolean isJson(String str) {
|
||||
if (str == null || str.trim().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
com.alibaba.fastjson.JSON.parse(str);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Map对象
|
||||
*/
|
||||
@ -1149,24 +1131,7 @@ public class oConvertUtils {
|
||||
* @date 2020/9/12 15:50
|
||||
*/
|
||||
public static <T> boolean isIn(T obj, T... objs) {
|
||||
if (isEmpty(objs)) {
|
||||
return false;
|
||||
}
|
||||
for (T obj1 : objs) {
|
||||
if (isEqual(obj, obj1)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断租户ID是否有效
|
||||
* @param tenantId
|
||||
* @return
|
||||
*/
|
||||
public static boolean isEffectiveTenant(String tenantId) {
|
||||
return MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL && isNotEmpty(tenantId) && !("0").equals(tenantId);
|
||||
return isIn(obj, objs);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -97,8 +97,9 @@ public class OssBootUtil {
|
||||
* @return oss 中的相对文件路径
|
||||
*/
|
||||
public static String upload(MultipartFile file, String fileDir,String customBucket) throws Exception {
|
||||
// 文件安全校验,防止上传漏洞文件
|
||||
//update-begin-author:liusq date:20210809 for: 过滤上传文件类型
|
||||
SsrfFileTypeFilter.checkUploadFileType(file);
|
||||
//update-end-author:liusq date:20210809 for: 过滤上传文件类型
|
||||
|
||||
String filePath = null;
|
||||
initOss(endPoint, accessKeyId, accessKeySecret);
|
||||
|
||||
@ -3,8 +3,6 @@ package org.jeecg.common.util.security;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.jeecg.common.exception.JeecgSqlInjectionException;
|
||||
import org.jeecg.common.util.SqlInjectionUtil;
|
||||
import org.jeecg.common.util.oConvertUtils;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.regex.Matcher;
|
||||
@ -68,8 +66,6 @@ public abstract class AbstractQueryBlackListHandler {
|
||||
if(flag == false){
|
||||
return false;
|
||||
}
|
||||
Set<String> xssTableSet = new HashSet<>(Arrays.asList(SqlInjectionUtil.XSS_STR_TABLE.split("\\|")));
|
||||
|
||||
for (QueryTable table : list) {
|
||||
String name = table.getName();
|
||||
String fieldRule = ruleMap.get(name);
|
||||
@ -85,16 +81,6 @@ public abstract class AbstractQueryBlackListHandler {
|
||||
}
|
||||
|
||||
}
|
||||
// 判断是否调用了黑名单数据库
|
||||
String dbName = table.getDbName();
|
||||
if (oConvertUtils.isNotEmpty(dbName)) {
|
||||
dbName = dbName.toLowerCase().trim();
|
||||
if (xssTableSet.contains(dbName)) {
|
||||
flag = false;
|
||||
log.warn("sql黑名单校验,数据库【" + dbName + "】禁止查询");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 返回黑名单校验结果(不合法直接抛出异常)
|
||||
@ -149,8 +135,6 @@ public abstract class AbstractQueryBlackListHandler {
|
||||
* 查询的表的信息
|
||||
*/
|
||||
protected class QueryTable {
|
||||
//数据库名
|
||||
private String dbName;
|
||||
//表名
|
||||
private String name;
|
||||
//表的别名
|
||||
@ -174,14 +158,6 @@ public abstract class AbstractQueryBlackListHandler {
|
||||
this.fields.add(field);
|
||||
}
|
||||
|
||||
public String getDbName() {
|
||||
return dbName;
|
||||
}
|
||||
|
||||
public void setDbName(String dbName) {
|
||||
this.dbName = dbName;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@ -3,14 +3,13 @@ package org.jeecg.config;
|
||||
import org.jeecgframework.core.util.ApplicationContextUtil;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
|
||||
/**
|
||||
* @Author: Scott
|
||||
* @Date: 2018/2/7
|
||||
* @description: autopoi 配置类
|
||||
*/
|
||||
@Lazy(false)
|
||||
|
||||
@Configuration
|
||||
public class AutoPoiConfig {
|
||||
|
||||
|
||||
@ -25,7 +25,6 @@ import lombok.extern.slf4j.Slf4j;
|
||||
* @Version:1.0
|
||||
*/
|
||||
@Slf4j
|
||||
@Lazy(false)
|
||||
@Service
|
||||
public class AutoPoiDictConfig implements AutoPoiDictServiceI {
|
||||
final static String EXCEL_SPLIT_TAG = "_";
|
||||
|
||||
@ -40,10 +40,6 @@ public class JeecgBaseConfig {
|
||||
*/
|
||||
private Firewall firewall;
|
||||
|
||||
/**
|
||||
* shiro拦截排除
|
||||
*/
|
||||
private Shiro shiro;
|
||||
/**
|
||||
* 上传文件配置
|
||||
*/
|
||||
@ -74,7 +70,7 @@ public class JeecgBaseConfig {
|
||||
/**
|
||||
* 百度开放API配置
|
||||
*/
|
||||
private BaiduApi baiduApi;
|
||||
private BaiduApi baiduApi;
|
||||
|
||||
public String getCustomResourcePrefixPath() {
|
||||
return customResourcePrefixPath;
|
||||
@ -108,14 +104,6 @@ public class JeecgBaseConfig {
|
||||
this.signatureSecret = signatureSecret;
|
||||
}
|
||||
|
||||
public Shiro getShiro() {
|
||||
return shiro;
|
||||
}
|
||||
|
||||
public void setShiro(Shiro shiro) {
|
||||
this.shiro = shiro;
|
||||
}
|
||||
|
||||
public Path getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
@ -1,29 +0,0 @@
|
||||
package org.jeecg.config;
|
||||
|
||||
import org.jeecg.config.vo.GaoDeApi;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
|
||||
/**
|
||||
* 高德账号配置
|
||||
*/
|
||||
@Lazy(false)
|
||||
@Configuration("jeecgGaodeBaseConfig")
|
||||
@ConfigurationProperties(prefix = "jeecg.jmreport")
|
||||
public class JeecgGaodeBaseConfig {
|
||||
|
||||
/**
|
||||
* 高德开放API配置
|
||||
*/
|
||||
private GaoDeApi gaoDeApi;
|
||||
|
||||
public GaoDeApi getGaoDeApi() {
|
||||
return gaoDeApi;
|
||||
}
|
||||
|
||||
public void setGaoDeApi(GaoDeApi gaoDeApi) {
|
||||
this.gaoDeApi = gaoDeApi;
|
||||
}
|
||||
|
||||
}
|
||||
@ -2,14 +2,12 @@ package org.jeecg.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 设置静态参数初始化
|
||||
* @author: jeecg-boot
|
||||
*/
|
||||
@Lazy(false)
|
||||
@Component
|
||||
@Data
|
||||
public class StaticConfig {
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
//package org.jeecg.config;
|
||||
//
|
||||
//
|
||||
//import io.swagger.v3.oas.annotations.Operation;
|
||||
//import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
|
||||
//import org.jeecg.common.constant.CommonConstant;
|
||||
//import org.jeecg.config.mybatis.MybatisPlusSaasConfig;
|
||||
//import org.springframework.beans.BeansException;
|
||||
//import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
//import org.springframework.context.annotation.Bean;
|
||||
@ -19,13 +18,15 @@
|
||||
//import springfox.documentation.builders.ParameterBuilder;
|
||||
//import springfox.documentation.builders.PathSelectors;
|
||||
//import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
//import springfox.documentation.oas.annotations.EnableOpenApi;
|
||||
//import springfox.documentation.schema.ModelRef;
|
||||
//import springfox.documentation.service.*;
|
||||
//import springfox.documentation.spi.DocumentationType;
|
||||
//import springfox.documentation.spi.service.contexts.SecurityContext;
|
||||
//import springfox.documentation.spring.web.plugins.Docket;
|
||||
//import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
|
||||
//import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
|
||||
//import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
|
||||
//import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
//
|
||||
//import java.lang.reflect.Field;
|
||||
//import java.util.ArrayList;
|
||||
@ -37,7 +38,8 @@
|
||||
// * @Author scott
|
||||
// */
|
||||
//@Configuration
|
||||
//@EnableSwagger2WebMvc
|
||||
//@EnableSwagger2 //开启 Swagger2
|
||||
//@EnableKnife4j //开启 knife4j,可以不写
|
||||
//@Import(BeanValidatorPluginsConfiguration.class)
|
||||
//public class Swagger2Config implements WebMvcConfigurer {
|
||||
//
|
||||
@ -95,14 +97,6 @@
|
||||
// List<Parameter> pars = new ArrayList<>();
|
||||
// tokenPar.name(CommonConstant.X_ACCESS_TOKEN).description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
|
||||
// pars.add(tokenPar.build());
|
||||
// //update-begin-author:liusq---date:2024-08-15--for: 开启多租户时,全局参数增加租户id
|
||||
// if(MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL){
|
||||
// ParameterBuilder tenantPar = new ParameterBuilder();
|
||||
// tenantPar.name(CommonConstant.TENANT_ID).description("租户ID").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
|
||||
// pars.add(tenantPar.build());
|
||||
// }
|
||||
// //update-end-author:liusq---date:2024-08-15--for: 开启多租户时,全局参数增加租户id
|
||||
//
|
||||
// return pars;
|
||||
// }
|
||||
//
|
||||
@ -157,7 +151,7 @@
|
||||
//
|
||||
// @Override
|
||||
// public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
// if (bean instanceof WebMvcRequestHandlerProvider) {
|
||||
// if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
|
||||
// customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
|
||||
// }
|
||||
// return bean;
|
||||
|
||||
@ -10,13 +10,11 @@ import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
import org.springdoc.core.customizers.OperationCustomizer;
|
||||
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
|
||||
import org.springdoc.core.filters.GlobalOpenApiMethodFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@ -63,71 +61,42 @@ public class Swagger3Config implements WebMvcConfigurer {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OperationCustomizer operationCustomizer() {
|
||||
return (operation, handlerMethod) -> {
|
||||
String path = getFullPath(handlerMethod);
|
||||
if (!isExcludedPath(path)) {
|
||||
operation.addSecurityItem(new SecurityRequirement().addList(CommonConstant.X_ACCESS_TOKEN));
|
||||
}else{
|
||||
log.info("忽略加入 X_ACCESS_TOKEN 的 PATH:" + path);
|
||||
public GlobalOpenApiCustomizer globalOpenApiCustomizer() {
|
||||
return openApi -> {
|
||||
// 全局添加鉴权参数
|
||||
if (openApi.getPaths() != null) {
|
||||
openApi.getPaths().forEach((path, pathItem) -> {
|
||||
//log.debug("path: {}", path);
|
||||
// 检查当前路径是否在排除列表中
|
||||
boolean isExcluded = excludedPaths.stream().anyMatch(excludedPath ->
|
||||
excludedPath.equals(path) ||
|
||||
(excludedPath.endsWith("**") && path.startsWith(excludedPath.substring(0, excludedPath.length() - 2)))
|
||||
);
|
||||
|
||||
if (!isExcluded) {
|
||||
// 接口添加鉴权参数
|
||||
pathItem.readOperations()
|
||||
.forEach(operation ->
|
||||
operation.addSecurityItem(new SecurityRequirement().addList(CommonConstant.X_ACCESS_TOKEN))
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
return operation;
|
||||
};
|
||||
}
|
||||
|
||||
private String getFullPath(HandlerMethod handlerMethod) {
|
||||
StringBuilder fullPath = new StringBuilder();
|
||||
|
||||
// 获取类级别的路径
|
||||
RequestMapping classMapping = handlerMethod.getBeanType().getAnnotation(RequestMapping.class);
|
||||
if (classMapping != null && classMapping.value().length > 0) {
|
||||
fullPath.append(classMapping.value()[0]);
|
||||
}
|
||||
|
||||
// 获取方法级别的路径
|
||||
RequestMapping methodMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
|
||||
if (methodMapping != null && methodMapping.value().length > 0) {
|
||||
String methodPath = methodMapping.value()[0];
|
||||
// 确保路径正确拼接,处理斜杠
|
||||
if (!fullPath.toString().endsWith("/") && !methodPath.startsWith("/")) {
|
||||
fullPath.append("/");
|
||||
}
|
||||
fullPath.append(methodPath);
|
||||
}
|
||||
|
||||
return fullPath.toString();
|
||||
}
|
||||
|
||||
|
||||
private boolean isExcludedPath(String path) {
|
||||
return excludedPaths.stream()
|
||||
.anyMatch(pattern -> {
|
||||
if (pattern.endsWith("/**")) {
|
||||
// 处理通配符匹配
|
||||
String basePath = pattern.substring(0, pattern.length() - 3);
|
||||
return path.startsWith(basePath);
|
||||
}
|
||||
// 精确匹配
|
||||
return pattern.equals(path);
|
||||
});
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OpenAPI customOpenAPI() {
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("JeecgBoot 后台服务API接口文档")
|
||||
.version("3.8.3")
|
||||
.version("3.8.0")
|
||||
.contact(new Contact().name("北京国炬信息技术有限公司").url("www.jeccg.com").email("jeecgos@163.com"))
|
||||
.description("后台API接口")
|
||||
.description( "后台API接口")
|
||||
.termsOfService("NO terms of service")
|
||||
.license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0.html")))
|
||||
.addSecurityItem(new SecurityRequirement().addList(CommonConstant.X_ACCESS_TOKEN))
|
||||
.components(new Components().addSecuritySchemes(CommonConstant.X_ACCESS_TOKEN,
|
||||
new SecurityScheme()
|
||||
.name(CommonConstant.X_ACCESS_TOKEN)
|
||||
.type(SecurityScheme.Type.APIKEY)
|
||||
.in(SecurityScheme.In.HEADER) // 关键:指定为 header
|
||||
));
|
||||
new SecurityScheme().name(CommonConstant.X_ACCESS_TOKEN).type(SecurityScheme.Type.HTTP)));
|
||||
}
|
||||
}
|
||||
@ -1,19 +1,19 @@
|
||||
//package org.jeecg.config;
|
||||
//
|
||||
//import io.undertow.server.DefaultByteBufferPool;
|
||||
//import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
|
||||
//import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
|
||||
//import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
||||
//import org.springframework.stereotype.Component;
|
||||
//
|
||||
//@Component
|
||||
//public class UndertowCustomizer implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
|
||||
// @Override
|
||||
// public void customize(UndertowServletWebServerFactory factory) {
|
||||
// factory.addDeploymentInfoCustomizers(deploymentInfo -> {
|
||||
// WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
|
||||
// webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(false, 1024));
|
||||
// deploymentInfo.addServletContextAttribute("io.undertow.websockets.jsr.WebSocketDeploymentInfo", webSocketDeploymentInfo);
|
||||
// });
|
||||
// }
|
||||
//}
|
||||
package org.jeecg.config;
|
||||
|
||||
import io.undertow.server.DefaultByteBufferPool;
|
||||
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
|
||||
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
|
||||
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class UndertowCustomizer implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
|
||||
@Override
|
||||
public void customize(UndertowServletWebServerFactory factory) {
|
||||
factory.addDeploymentInfoCustomizers(deploymentInfo -> {
|
||||
WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
|
||||
webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(false, 1024));
|
||||
deploymentInfo.addServletContextAttribute("io.undertow.websockets.jsr.WebSocketDeploymentInfo", webSocketDeploymentInfo);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -11,19 +11,22 @@ import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
|
||||
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.Resource;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
import org.springframework.boot.actuate.web.exchanges.InMemoryHttpExchangeRepository;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
@ -47,7 +50,6 @@ import java.util.concurrent.TimeUnit;
|
||||
* @Author qinfeng
|
||||
*
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
public class WebMvcConfiguration implements WebMvcConfigurer {
|
||||
|
||||
@ -59,14 +61,6 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
|
||||
@Autowired(required = false)
|
||||
private PrometheusMeterRegistry prometheusMeterRegistry;
|
||||
|
||||
/**
|
||||
* meterRegistryPostProcessor
|
||||
* for [QQYUN-12558]【监控】系统监控的头两个tab不好使,接口404
|
||||
*/
|
||||
@Autowired(required = false)
|
||||
@Qualifier("meterRegistryPostProcessor")
|
||||
private BeanPostProcessor meterRegistryPostProcessor;
|
||||
|
||||
/**
|
||||
* 静态资源的配置 - 使得可以从磁盘中读取 Html、图片、视频、音频等
|
||||
*/
|
||||
@ -89,7 +83,7 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
|
||||
*/
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
registry.addViewController("/").setViewName("redirect:/doc.html");
|
||||
registry.addViewController("/").setViewName("doc.html");
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ -155,18 +149,12 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
|
||||
|
||||
|
||||
/**
|
||||
* 在Bean初始化完成后立即配置PrometheusMeterRegistry,避免在Meter注册后才配置MeterFilter
|
||||
* for [QQYUN-12558]【监控】系统监控的头两个tab不好使,接口404
|
||||
* @author chenrui
|
||||
* @date 2025/5/26 16:46
|
||||
* 解决metrics端点不显示jvm信息的问题(zyf)
|
||||
*/
|
||||
@PostConstruct
|
||||
public void initPrometheusMeterRegistry() {
|
||||
// 确保在应用启动早期就配置MeterFilter,避免警告
|
||||
if (null != meterRegistryPostProcessor && null != prometheusMeterRegistry) {
|
||||
meterRegistryPostProcessor.postProcessAfterInitialization(prometheusMeterRegistry, "prometheusMeterRegistry");
|
||||
log.info("PrometheusMeterRegistry配置完成");
|
||||
}
|
||||
@Bean
|
||||
@ConditionalOnBean(name = "meterRegistryPostProcessor")
|
||||
InitializingBean forcePrometheusPostProcessor(BeanPostProcessor meterRegistryPostProcessor) {
|
||||
return () -> meterRegistryPostProcessor.postProcessAfterInitialization(prometheusMeterRegistry, "");
|
||||
}
|
||||
|
||||
// /**
|
||||
|
||||
@ -24,18 +24,23 @@ public class WebsocketFilter implements Filter {
|
||||
|
||||
private static CommonAPI commonApi;
|
||||
|
||||
private static RedisUtil redisUtil;
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
|
||||
if (commonApi == null) {
|
||||
commonApi = SpringContextUtils.getBean(CommonAPI.class);
|
||||
}
|
||||
if (redisUtil == null) {
|
||||
redisUtil = SpringContextUtils.getBean(RedisUtil.class);
|
||||
}
|
||||
HttpServletRequest request = (HttpServletRequest)servletRequest;
|
||||
String token = request.getHeader(TOKEN_KEY);
|
||||
|
||||
log.debug("Websocket连接 Token安全校验,Path = {},token:{}", request.getRequestURI(), token);
|
||||
|
||||
try {
|
||||
TokenUtils.verifyToken(token, commonApi);
|
||||
TokenUtils.verifyToken(token, commonApi, redisUtil);
|
||||
} catch (Exception exception) {
|
||||
//log.error("Websocket连接 Token安全校验失败,IP:{}, Token:{}, Path = {},异常:{}", oConvertUtils.getIpAddrByRequest(request), token, request.getRequestURI(), exception.getMessage());
|
||||
log.debug("Websocket连接 Token安全校验失败,IP:{}, Token:{}, Path = {},异常:{}", oConvertUtils.getIpAddrByRequest(request), token, request.getRequestURI(), exception.getMessage());
|
||||
|
||||
@ -8,14 +8,12 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
@Configuration
|
||||
public class LowCodeModeConfiguration implements WebMvcConfigurer {
|
||||
|
||||
private final LowCodeModeInterceptor lowCodeModeInterceptor;
|
||||
|
||||
public LowCodeModeConfiguration(LowCodeModeInterceptor lowCodeModeInterceptor) {
|
||||
this.lowCodeModeInterceptor = lowCodeModeInterceptor;
|
||||
public LowCodeModeInterceptor payInterceptor() {
|
||||
return new LowCodeModeInterceptor();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(lowCodeModeInterceptor).addPathPatterns(LowCodeUrlsEnum.getLowCodeInterceptUrls());
|
||||
registry.addInterceptor(payInterceptor()).addPathPatterns(LowCodeUrlsEnum.getLowCodeInterceptUrls());
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,7 +2,6 @@ package org.jeecg.config.firewall.interceptor;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jeecg.common.util.LoginUserUtils;
|
||||
import org.jeecg.common.api.CommonAPI;
|
||||
import org.jeecg.common.api.vo.Result;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
@ -11,7 +10,8 @@ import org.jeecg.common.system.vo.LoginUser;
|
||||
import org.jeecg.common.util.CommonUtils;
|
||||
import org.jeecg.common.util.SpringContextUtils;
|
||||
import org.jeecg.config.JeecgBaseConfig;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.jeecg.config.security.utils.SecureUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
@ -38,7 +38,6 @@ import java.util.Set;
|
||||
* @date 20230904
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class LowCodeModeInterceptor implements HandlerInterceptor {
|
||||
/**
|
||||
* 低代码开发模式
|
||||
@ -48,27 +47,23 @@ public class LowCodeModeInterceptor implements HandlerInterceptor {
|
||||
|
||||
@Resource
|
||||
private JeecgBaseConfig jeecgBaseConfig;
|
||||
|
||||
@Autowired
|
||||
private CommonAPI commonAPI;
|
||||
|
||||
/**
|
||||
* 在请求处理之前进行调用
|
||||
*/
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
|
||||
CommonAPI commonAPI = null;
|
||||
log.info("低代码模式,拦截请求路径:" + request.getRequestURI());
|
||||
|
||||
//1、验证是否开启低代码开发模式控制
|
||||
if (jeecgBaseConfig == null) {
|
||||
jeecgBaseConfig = SpringContextUtils.getBean(JeecgBaseConfig.class);
|
||||
}
|
||||
if (commonAPI == null) {
|
||||
commonAPI = SpringContextUtils.getBean(CommonAPI.class);
|
||||
}
|
||||
|
||||
if (jeecgBaseConfig.getFirewall()!=null && LowCodeModeInterceptor.LOW_CODE_MODE_PROD.equals(jeecgBaseConfig.getFirewall().getLowCodeMode())) {
|
||||
String requestURI = request.getRequestURI().substring(request.getContextPath().length());
|
||||
log.info("低代码模式,拦截请求路径:" + requestURI);
|
||||
LoginUser loginUser = LoginUserUtils.getSessionUser();
|
||||
LoginUser loginUser = SecureUtil.currentUser();
|
||||
Set<String> hasRoles = null;
|
||||
if (loginUser == null) {
|
||||
loginUser = commonAPI.getUserByName(JwtUtil.getUserNameByToken(SpringContextUtils.getHttpServletRequest()));
|
||||
|
||||
@ -6,13 +6,13 @@ import org.apache.ibatis.executor.Executor;
|
||||
import org.apache.ibatis.mapping.MappedStatement;
|
||||
import org.apache.ibatis.mapping.SqlCommandType;
|
||||
import org.apache.ibatis.plugin.*;
|
||||
import org.jeecg.common.util.LoginUserUtils;
|
||||
import org.jeecg.common.config.TenantContext;
|
||||
import org.jeecg.common.constant.TenantConstant;
|
||||
import org.jeecg.common.system.vo.LoginUser;
|
||||
import org.jeecg.common.util.SpringContextUtils;
|
||||
import org.jeecg.common.util.TokenUtils;
|
||||
import org.jeecg.common.util.oConvertUtils;
|
||||
import org.jeecg.config.security.utils.SecureUtil;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
@ -192,7 +192,7 @@ public class MybatisInterceptor implements Interceptor {
|
||||
private LoginUser getLoginUser() {
|
||||
LoginUser sysUser = null;
|
||||
try {
|
||||
sysUser = LoginUserUtils.getSessionUser() != null ? LoginUserUtils.getSessionUser() : null;
|
||||
sysUser = SecureUtil.currentUser() != null ? SecureUtil.currentUser() : null;
|
||||
} catch (Exception e) {
|
||||
//e.printStackTrace();
|
||||
sysUser = null;
|
||||
|
||||
@ -1,16 +1,11 @@
|
||||
package org.jeecg.config.mybatis;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import me.zhyd.oauth.log.Log;
|
||||
import net.sf.jsqlparser.expression.Expression;
|
||||
import net.sf.jsqlparser.expression.LongValue;
|
||||
import org.jeecg.common.config.TenantContext;
|
||||
@ -20,27 +15,24 @@ import org.jeecg.common.util.SpringContextUtils;
|
||||
import org.jeecg.common.util.TokenUtils;
|
||||
import org.jeecg.common.util.oConvertUtils;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
|
||||
|
||||
|
||||
/**
|
||||
* 单数据源配置(jeecg.datasource.open = false时生效)
|
||||
* @Author zhoujf
|
||||
*
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@MapperScan(value={"org.jeecg.**.mapper*"})
|
||||
public class MybatisPlusSaasConfig {
|
||||
@Autowired
|
||||
private DataSource dataSource;
|
||||
|
||||
|
||||
/**
|
||||
* 是否开启系统模块的租户隔离
|
||||
* 控制范围:用户、角色、部门、我的部门、字典、分类字典、多数据源、职务、通知公告
|
||||
@ -130,23 +122,7 @@ public class MybatisPlusSaasConfig {
|
||||
//update-begin-author:zyf date:20220425 for:【VUEN-606】注入动态表名适配拦截器解决多表名问题
|
||||
interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor());
|
||||
//update-end-author:zyf date:20220425 for:【VUEN-606】注入动态表名适配拦截器解决多表名问题
|
||||
|
||||
//update-begin---author:scott ---date:2025-08-02 for:【issues/8666】升级mybatisPlus后SqlServer分页使用OFFSET ? ROWS FETCH NEXT ? ROWS ONLY,导致online报表报错---
|
||||
DbType dbType = null;
|
||||
try {
|
||||
dbType = JdbcUtils.getDbType(dataSource.getConnection().getMetaData().getURL());
|
||||
log.info("当前数据库类型: {}", dbType);
|
||||
} catch (SQLException e) {
|
||||
Log.error(e.getMessage(), e);
|
||||
}
|
||||
if (dbType!=null && (dbType == DbType.SQL_SERVER || dbType == DbType.SQL_SERVER2005)) {
|
||||
// 如果是SQL Server则覆盖为2005分页方式
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.SQL_SERVER2005));
|
||||
} else {
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
|
||||
}
|
||||
//update-end---author:scott ---date::2025-08-02 for:【issues/8666】升级mybatisPlus后SqlServer分页使用OFFSET ? ROWS FETCH NEXT ? ROWS ONLY,导致online报表报错---
|
||||
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
|
||||
//【jeecg-boot/issues/3847】增加@Version乐观锁支持
|
||||
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
|
||||
return interceptor;
|
||||
|
||||
@ -9,13 +9,11 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
|
||||
/**
|
||||
* Minio文件上传配置文件
|
||||
* @author: jeecg-boot
|
||||
*/
|
||||
@Lazy(false)
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = "jeecg.minio", name = "minio_url")
|
||||
|
||||
@ -6,13 +6,11 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
|
||||
/**
|
||||
* 云存储 配置
|
||||
* @author: jeecg-boot
|
||||
*/
|
||||
@Lazy(false)
|
||||
@Configuration
|
||||
@ConditionalOnProperty(prefix = "jeecg.oss", name = "endpoint")
|
||||
public class OssConfiguration {
|
||||
|
||||
@ -1,420 +0,0 @@
|
||||
package org.jeecg.config.satoken;
|
||||
|
||||
import cn.dev33.satoken.context.SaHolder;
|
||||
import cn.dev33.satoken.context.model.SaRequest;
|
||||
import cn.dev33.satoken.exception.NotLoginException;
|
||||
import cn.dev33.satoken.filter.SaServletFilter;
|
||||
import cn.dev33.satoken.interceptor.SaInterceptor;
|
||||
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
|
||||
import cn.dev33.satoken.router.SaHttpMethod;
|
||||
import cn.dev33.satoken.router.SaRouter;
|
||||
import cn.dev33.satoken.stp.StpLogic;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import jakarta.annotation.Resource;
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jeecg.common.api.CommonAPI;
|
||||
import org.jeecg.common.config.TenantContext;
|
||||
import org.jeecg.common.constant.CacheConstant;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
import org.jeecg.common.system.vo.LoginUser;
|
||||
import org.jeecg.common.util.*;
|
||||
import org.jeecg.config.JeecgBaseConfig;
|
||||
import org.jeecg.config.mybatis.MybatisPlusSaasConfig;
|
||||
import org.jeecg.config.satoken.ignore.InMemoryIgnoreAuth;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.context.annotation.Role;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author: jeecg-boot
|
||||
* @description: Sa-Token 配置类
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
|
||||
public class SaTokenConfig implements WebMvcConfigurer {
|
||||
|
||||
@Resource
|
||||
private JeecgBaseConfig jeecgBaseConfig;
|
||||
@Autowired
|
||||
private Environment env;
|
||||
@Autowired
|
||||
private CommonAPI commonAPI;
|
||||
@Autowired
|
||||
private RedisUtil redisUtil;
|
||||
|
||||
/**
|
||||
* Sa-Token 整合 jwt (Simple 模式)
|
||||
* 使用JWT-Simple模式生成标准JWT格式的token
|
||||
* 并支持从URL参数"token"读取token(兼容原系统)
|
||||
*/
|
||||
@Bean
|
||||
@Primary
|
||||
public StpLogic getStpLogicJwt() {
|
||||
return new StpLogicJwtForSimple() {
|
||||
/**
|
||||
* 获取当前请求的 Token 值
|
||||
* 优先级:Header > URL参数token > URL参数X-Access-Token
|
||||
*/
|
||||
@Override
|
||||
public String getTokenValue() {
|
||||
try {
|
||||
SaRequest request = SaHolder.getRequest();
|
||||
|
||||
// 1. 优先从Header中获取
|
||||
String tokenValue = request.getHeader(getConfigOrGlobal().getTokenName());
|
||||
if (oConvertUtils.isNotEmpty(tokenValue)) {
|
||||
return tokenValue;
|
||||
}
|
||||
|
||||
// 2. 从URL参数"token"获取(兼容原系统)
|
||||
tokenValue = request.getParam("token");
|
||||
if (oConvertUtils.isNotEmpty(tokenValue)) {
|
||||
return tokenValue;
|
||||
}
|
||||
|
||||
// 3. 从URL参数"X-Access-Token"获取
|
||||
tokenValue = request.getParam(getConfigOrGlobal().getTokenName());
|
||||
if (oConvertUtils.isNotEmpty(tokenValue)) {
|
||||
return tokenValue;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("获取token失败: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// 4. 如果都没有,使用默认逻辑
|
||||
return super.getTokenValue();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册 Sa-Token 拦截器,打开注解式鉴权功能
|
||||
*/
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
// 注册 Sa-Token 拦截器,打开注解式鉴权功能
|
||||
registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**");
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册 Sa-Token 全局过滤器
|
||||
*/
|
||||
@Bean
|
||||
public SaServletFilter getSaServletFilter() {
|
||||
return new SaServletFilter()
|
||||
// 指定 [拦截路由] 与 [放行路由]
|
||||
.addInclude("/**")
|
||||
.setExcludeList(getExcludeUrls())
|
||||
// 认证函数: 每次请求执行
|
||||
.setAuth(obj -> {
|
||||
// 检查是否是免认证路径
|
||||
String servletPath = SaHolder.getRequest().getRequestPath();
|
||||
if (InMemoryIgnoreAuth.contains(servletPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 校验 token:如果请求中带有 token,先切换到对应的登录会话再校验
|
||||
try {
|
||||
String token = StpUtil.getTokenValue();
|
||||
if (oConvertUtils.isNotEmpty(token)) {
|
||||
// 根据 token 获取 loginId 并切换到对应的登录会话
|
||||
Object loginId = StpUtil.getLoginIdByToken(token);
|
||||
if (loginId != null) {
|
||||
StpUtil.switchTo(loginId);
|
||||
|
||||
// 需要手工自动续签,默认参数auto-renew:true 不好使
|
||||
long activeTimeout = StpUtil.stpLogic.getConfigOrGlobal().getActiveTimeout();
|
||||
if (activeTimeout > 0) {
|
||||
// 获取当前token的活跃剩余时间
|
||||
long tokenActiveTimeout = StpUtil.getTokenActiveTimeout();
|
||||
|
||||
// 如果剩余活跃时间少于总活跃时间的一半,进行续签
|
||||
if (tokenActiveTimeout > 0 && tokenActiveTimeout < (activeTimeout / 2)) {
|
||||
StpUtil.stpLogic.updateLastActiveToNow(token);
|
||||
log.info("【Sa-Token拦截器】Token续签成功,剩余活跃时间: {}秒", tokenActiveTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 如果获取 loginId 失败,说明 token 无效或未登录,让 checkLogin 抛出异常
|
||||
log.debug("切换登录会话失败: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// 最终校验登录状态
|
||||
StpUtil.checkLogin();
|
||||
|
||||
// 租户校验逻辑
|
||||
checkTenantAuthorization();
|
||||
})
|
||||
// 异常处理函数:每次认证函数发生异常时执行此函数
|
||||
.setError(e -> {
|
||||
log.warn("Sa-Token 认证失败:用户未登录或token无效");
|
||||
log.warn("请求路径: {}, Method: {},Token: {}", SaHolder.getRequest().getRequestPath(), SaHolder.getRequest().getMethod(), StpUtil.getTokenValue());
|
||||
|
||||
// 返回401状态码
|
||||
SaHolder.getResponse().setStatus(401).setHeader("Content-Type", "application/json;charset=UTF-8");
|
||||
return org.jeecg.common.system.util.JwtUtil.responseErrorJson(401, CommonConstant.TOKEN_IS_INVALID_MSG);
|
||||
})
|
||||
// 前置函数:在每次认证函数之前执行(BeforeAuth 不受 includeList 与 excludeList 的限制,所有请求都会进入)
|
||||
.setBeforeAuth(r -> {
|
||||
// 设置跨域配置
|
||||
Object cloudServer = env.getProperty(CommonConstant.CLOUD_SERVER_KEY);
|
||||
// 如果cloudServer为空 则说明是单体 需要加载跨域配置【微服务跨域切换】
|
||||
if (cloudServer == null) {
|
||||
SaHolder.getResponse()
|
||||
// 允许指定域访问跨域资源
|
||||
.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, SaHolder.getRequest().getHeader(HttpHeaders.ORIGIN))
|
||||
// 允许所有请求方式
|
||||
.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE, OPTIONS")
|
||||
// 有效时间
|
||||
.setHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600")
|
||||
// 允许的header参数
|
||||
.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, SaHolder.getRequest().getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS))
|
||||
// 允许携带凭证
|
||||
.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
|
||||
}
|
||||
|
||||
// OPTIONS预检请求,直接返回
|
||||
SaRouter.match(SaHttpMethod.OPTIONS).free(r2 -> {
|
||||
SaHolder.getResponse().setStatus(HttpStatus.OK.value());
|
||||
});
|
||||
|
||||
// 设置当前线程上下文的租户ID
|
||||
String tenantId = SaHolder.getRequest().getHeader(CommonConstant.TENANT_ID);
|
||||
TenantContext.setTenant(tenantId);
|
||||
log.info("===【TenantContext 线程设置】=== 请求路径: {}, 租户ID: {}", SaHolder.getRequest().getRequestPath(), tenantId);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* spring过滤装饰器 <br/>
|
||||
* 支持异步请求的过滤器装饰
|
||||
*/
|
||||
@Bean
|
||||
public FilterRegistrationBean<SaServletFilter> saTokenFilterRegistration() {
|
||||
FilterRegistrationBean<SaServletFilter> registration = new FilterRegistrationBean<>();
|
||||
registration.setFilter(getSaServletFilter());
|
||||
registration.setName("SaServletFilter");
|
||||
// 支持异步请求
|
||||
registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);
|
||||
// 拦截所有请求
|
||||
registration.addUrlPatterns("/*");
|
||||
registration.setOrder(1);
|
||||
registration.setAsyncSupported(true); // 支持异步请求
|
||||
return registration;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取排除URL列表
|
||||
*/
|
||||
private List<String> getExcludeUrls() {
|
||||
List<String> excludeUrls = new ArrayList<>();
|
||||
|
||||
// 支持yml方式,配置拦截排除
|
||||
if (jeecgBaseConfig != null && jeecgBaseConfig.getShiro() != null) {
|
||||
String shiroExcludeUrls = jeecgBaseConfig.getShiro().getExcludeUrls();
|
||||
if (oConvertUtils.isNotEmpty(shiroExcludeUrls)) {
|
||||
String[] permissionUrl = shiroExcludeUrls.split(",");
|
||||
excludeUrls.addAll(Arrays.asList(permissionUrl));
|
||||
}
|
||||
}
|
||||
|
||||
// 添加默认排除路径
|
||||
excludeUrls.addAll(Arrays.asList(
|
||||
"/sys/cas/client/validateLogin", // cas验证登录
|
||||
"/sys/randomImage/**", // 登录验证码接口排除
|
||||
"/sys/checkCaptcha", // 登录验证码接口排除
|
||||
"/sys/smsCheckCaptcha", // 短信次数发送太多验证码排除
|
||||
"/sys/login", // 登录接口排除
|
||||
"/sys/mLogin", // 登录接口排除
|
||||
"/sys/logout", // 登出接口排除
|
||||
"/sys/thirdLogin/**", // 第三方登录
|
||||
"/sys/getEncryptedString", // 获取加密串
|
||||
"/sys/sms", // 短信验证码
|
||||
"/sys/phoneLogin", // 手机登录
|
||||
"/sys/user/checkOnlyUser", // 校验用户是否存在
|
||||
"/sys/user/register", // 用户注册
|
||||
"/sys/user/phoneVerification", // 用户忘记密码验证手机号
|
||||
"/sys/user/passwordChange", // 用户更改密码
|
||||
"/auth/2step-code", // 登录验证码
|
||||
"/sys/common/static/**", // 图片预览 & 下载文件不限制token
|
||||
"/sys/common/pdf/**", // pdf预览
|
||||
"/generic/**", // pdf预览需要文件
|
||||
"/sys/getLoginQrcode/**", // 登录二维码
|
||||
"/sys/getQrcodeToken/**", // 监听扫码
|
||||
"/sys/checkAuth", // 授权接口排除
|
||||
"/openapi/call/**", // 开放平台接口排除
|
||||
|
||||
// 排除静态资源后缀
|
||||
"/",
|
||||
"/doc.html",
|
||||
"**/*.js",
|
||||
"**/*.css",
|
||||
"**/*.html",
|
||||
"**/*.svg",
|
||||
"**/*.pdf",
|
||||
"**/*.jpg",
|
||||
"**/*.png",
|
||||
"**/*.gif",
|
||||
"**/*.ico",
|
||||
"**/*.ttf",
|
||||
"**/*.woff",
|
||||
"**/*.woff2",
|
||||
"**/*.glb",
|
||||
"**/*.wasm",
|
||||
"**/*.js.map",
|
||||
"**/*.css.map",
|
||||
|
||||
"/druid/**",
|
||||
"/swagger-ui.html",
|
||||
"/swagger*/**",
|
||||
"/webjars/**",
|
||||
"/v3/**",
|
||||
|
||||
// 排除消息通告查看详情页面(用于第三方APP)
|
||||
"/sys/annountCement/show/**",
|
||||
|
||||
// 积木报表和积木BI排除
|
||||
"/jmreport/**",
|
||||
"/drag/lib/**",
|
||||
"/drag/list/**",
|
||||
"/drag/favicon.ico",
|
||||
"/drag/view",
|
||||
"/drag/page/queryById",
|
||||
"/drag/page/addVisitsNumber",
|
||||
"/drag/page/queryTemplateList",
|
||||
"/drag/share/view/**",
|
||||
"/drag/onlDragDatasetHead/getAllChartData",
|
||||
"/drag/onlDragDatasetHead/getTotalData",
|
||||
"/drag/onlDragDatasetHead/getMapDataByCode",
|
||||
"/drag/onlDragDatasetHead/getTotalDataByCompId",
|
||||
"/drag/mock/json/**",
|
||||
"/drag/onlDragDatasetHead/getDictByCodes",
|
||||
"/drag/onlDragDatasetHead/queryAllById",
|
||||
"/jimubi/view",
|
||||
"/jimubi/share/view/**",
|
||||
|
||||
// 大屏模板例子
|
||||
"/test/bigScreen/**",
|
||||
"/bigscreen/template1/**",
|
||||
"/bigscreen/template2/**",
|
||||
|
||||
// websocket排除
|
||||
"/websocket/**", // 系统通知和公告
|
||||
"/newsWebsocket/**", // CMS模块
|
||||
"/vxeSocket/**", // JVxeTable无痕刷新示例
|
||||
"/dragChannelSocket/**", // 仪表盘(按钮通信)
|
||||
|
||||
// App vue3版本查询版本接口
|
||||
"/sys/version/app3version",
|
||||
|
||||
// 测试模块排除
|
||||
"/test/seata/**",
|
||||
|
||||
// 错误路径排除
|
||||
"/error",
|
||||
|
||||
// 企业微信证书排除
|
||||
"/WW_verify*"
|
||||
));
|
||||
|
||||
return excludeUrls;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验用户的tenant_id和前端传过来的是否一致
|
||||
*
|
||||
* <p>实现逻辑:
|
||||
* <ul>
|
||||
* <li>1. 获取当前登录用户信息</li>
|
||||
* <li>2. 检查用户是否配置了租户信息</li>
|
||||
* <li>3. 获取前端请求头中的租户ID</li>
|
||||
* <li>4. 校验用户所属租户中是否包含当前请求的租户ID</li>
|
||||
* <li>5. 如果校验失败,从数据库重新查询用户信息并再次校验</li>
|
||||
* <li>6. 最终校验失败则抛出异常</li>
|
||||
* </ul>
|
||||
*
|
||||
* @throws NotLoginException 租户授权变更异常
|
||||
*/
|
||||
private void checkTenantAuthorization() {
|
||||
log.debug("------ 租户校验开始 ------");
|
||||
// 如果未开启租户控制,直接返回
|
||||
if (!MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 获取当前登录用户信息
|
||||
LoginUser loginUser = TokenUtils.getLoginUser(LoginUserUtils.getUsername(), commonAPI, redisUtil);
|
||||
if (loginUser == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String username = loginUser.getUsername();
|
||||
String userTenantIds = loginUser.getRelTenantIds();
|
||||
|
||||
// 如果用户未配置租户信息,直接返回
|
||||
if (oConvertUtils.isEmpty(userTenantIds)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取前端请求头中的租户ID
|
||||
String loginTenantId = TokenUtils.getTenantIdByRequest(SpringContextUtils.getHttpServletRequest());
|
||||
log.info("登录租户:{}", loginTenantId);
|
||||
log.info("用户拥有那些租户:{}", userTenantIds);
|
||||
|
||||
// 登录用户无租户,前端header中租户ID值为 0
|
||||
String str = "0";
|
||||
if (oConvertUtils.isEmpty(loginTenantId) || str.equals(loginTenantId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
String[] userTenantIdsArray = userTenantIds.split(",");
|
||||
if (!oConvertUtils.isIn(loginTenantId, userTenantIdsArray)) {
|
||||
boolean isAuthorization = false;
|
||||
|
||||
//========================================================================
|
||||
// 查询用户信息(如果租户不匹配从数据库中重新查询一次用户信息)
|
||||
String loginUserKey = CacheConstant.SYS_USERS_CACHE + "::" + username;
|
||||
redisUtil.del(loginUserKey);
|
||||
|
||||
LoginUser loginUserFromDb = commonAPI.getUserByName(username);
|
||||
LoginUserUtils.setSessionUser(loginUserFromDb);
|
||||
if (loginUserFromDb != null && oConvertUtils.isNotEmpty(loginUserFromDb.getRelTenantIds())) {
|
||||
String[] newArray = loginUserFromDb.getRelTenantIds().split(",");
|
||||
if (oConvertUtils.isIn(loginTenantId, newArray)) {
|
||||
isAuthorization = true;
|
||||
}
|
||||
}
|
||||
//========================================================================
|
||||
|
||||
if (!isAuthorization) {
|
||||
log.info("租户异常——登录租户:{}", loginTenantId);
|
||||
log.info("租户异常——用户拥有租户组:{}", userTenantIds);
|
||||
throw new NotLoginException("登录租户授权变更,请重新登陆!", StpUtil.TYPE, NotLoginException.KICK_OUT);
|
||||
}
|
||||
}
|
||||
|
||||
}catch (Exception e) {
|
||||
log.error("租户校验异常:{}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,174 +0,0 @@
|
||||
package org.jeecg.config.satoken;
|
||||
|
||||
import cn.dev33.satoken.dao.SaTokenDao;
|
||||
import cn.dev33.satoken.SaManager;
|
||||
import cn.dev33.satoken.stp.StpInterface;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jeecg.common.api.CommonAPI;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @description: Sa-Token 权限认证接口实现(带缓存)
|
||||
*
|
||||
* <p>⚠️ 重要说明:</p>
|
||||
* <ul>
|
||||
* <li><strong>Sa-Token 的 StpInterface 默认不提供缓存能力</strong>,需要自己实现缓存逻辑</li>
|
||||
* <li>本实现采用 <strong>[账号id -> 权限/角色列表]</strong> 缓存模型</li>
|
||||
* <li>缓存键格式:
|
||||
* <ul>
|
||||
* <li>用户权限缓存:satoken:user-permission:{username}</li>
|
||||
* <li>用户角色缓存:satoken:user-role:{username}</li>
|
||||
* </ul>
|
||||
* </li>
|
||||
* <li>缓存过期时间:30天</li>
|
||||
* <li>⚠️ 当修改用户的角色或权限时,需要手动清除缓存</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>清除缓存示例:</p>
|
||||
* <pre>
|
||||
* // 清除单个用户的权限和角色缓存
|
||||
* StpInterfaceImpl.clearUserCache("admin");
|
||||
*
|
||||
* // 清除多个用户的缓存
|
||||
* StpInterfaceImpl.clearUserCache(Arrays.asList("admin", "user1", "user2"));
|
||||
* </pre>
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class StpInterfaceImpl implements StpInterface {
|
||||
|
||||
@Lazy
|
||||
@Resource
|
||||
private CommonAPI commonApi;
|
||||
|
||||
/**
|
||||
* 缓存过期时间(秒):30天
|
||||
*/
|
||||
private static final long CACHE_TIMEOUT = 60 * 60 * 24 * 30;
|
||||
|
||||
/**
|
||||
* 权限缓存键前缀
|
||||
*/
|
||||
private static final String PERMISSION_CACHE_PREFIX = "satoken:user-permission:";
|
||||
|
||||
/**
|
||||
* 角色缓存键前缀
|
||||
*/
|
||||
private static final String ROLE_CACHE_PREFIX = "satoken:user-role:";
|
||||
|
||||
/**
|
||||
* 返回一个账号所拥有的权限码集合(带缓存)
|
||||
*
|
||||
* @param loginId 账号id(这里是 username)
|
||||
* @param loginType 账号类型
|
||||
* @return 权限码集合
|
||||
*/
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<String> getPermissionList(Object loginId, String loginType) {
|
||||
String username = loginId.toString();
|
||||
String cacheKey = PERMISSION_CACHE_PREFIX + username;
|
||||
|
||||
SaTokenDao dao = SaManager.getSaTokenDao();
|
||||
|
||||
// 1. 先从缓存获取
|
||||
List<String> permissionList = (List<String>) dao.getObject(cacheKey);
|
||||
|
||||
if (permissionList == null) {
|
||||
// 2. 缓存不存在,从数据库查询
|
||||
log.warn("权限缓存未命中,查询数据库 [ username={} ]", username);
|
||||
|
||||
String userId = commonApi.getUserIdByName(username);
|
||||
if (userId == null) {
|
||||
log.warn("用户不存在: {}", username);
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
Set<String> permissionSet = commonApi.queryUserAuths(userId);
|
||||
permissionList = new ArrayList<>(permissionSet);
|
||||
|
||||
// 3. 将结果缓存起来
|
||||
dao.setObject(cacheKey, permissionList, CACHE_TIMEOUT);
|
||||
log.info("权限已缓存 [ username={}, permissions={} ]", username, permissionList.size());
|
||||
} else {
|
||||
log.debug("权限缓存命中 [ username={}, permissions={} ]", username, permissionList.size());
|
||||
}
|
||||
|
||||
return permissionList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回一个账号所拥有的角色标识集合(带缓存)
|
||||
*
|
||||
* @param loginId 账号id(这里是 username)
|
||||
* @param loginType 账号类型
|
||||
* @return 角色标识集合
|
||||
*/
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<String> getRoleList(Object loginId, String loginType) {
|
||||
String username = loginId.toString();
|
||||
String cacheKey = ROLE_CACHE_PREFIX + username;
|
||||
|
||||
SaTokenDao dao = SaManager.getSaTokenDao();
|
||||
|
||||
// 1. 先从缓存获取
|
||||
List<String> roleList = (List<String>) dao.getObject(cacheKey);
|
||||
|
||||
if (roleList == null) {
|
||||
// 2. 缓存不存在,从数据库查询
|
||||
log.warn("角色缓存未命中,查询数据库 [ username={} ]", username);
|
||||
|
||||
String userId = commonApi.getUserIdByName(username);
|
||||
if (userId == null) {
|
||||
log.warn("用户不存在: {}", username);
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
Set<String> roleSet = commonApi.queryUserRolesById(userId);
|
||||
roleList = new ArrayList<>(roleSet);
|
||||
|
||||
// 3. 将结果缓存起来
|
||||
dao.setObject(cacheKey, roleList, CACHE_TIMEOUT);
|
||||
log.info("角色已缓存 [ username={}, roles={} ]", username, roleList.size());
|
||||
} else {
|
||||
log.debug("角色缓存命中 [ username={}, roles={} ]", username, roleList.size());
|
||||
}
|
||||
|
||||
return roleList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除单个用户的权限和角色缓存
|
||||
* <p>使用场景:修改用户的角色分配后</p>
|
||||
*
|
||||
* @param username 用户名
|
||||
*/
|
||||
public static void clearUserCache(String username) {
|
||||
SaTokenDao dao = SaManager.getSaTokenDao();
|
||||
dao.deleteObject(PERMISSION_CACHE_PREFIX + username);
|
||||
dao.deleteObject(ROLE_CACHE_PREFIX + username);
|
||||
log.info("已清除用户缓存 [ username={} ]", username);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量清除多个用户的权限和角色缓存
|
||||
* <p>使用场景:修改角色权限后,清除拥有该角色的所有用户的缓存</p>
|
||||
*
|
||||
* @param usernameList 用户名列表
|
||||
*/
|
||||
public static void clearUserCache(List<String> usernameList) {
|
||||
SaTokenDao dao = SaManager.getSaTokenDao();
|
||||
for (String username : usernameList) {
|
||||
dao.deleteObject(PERMISSION_CACHE_PREFIX + username);
|
||||
dao.deleteObject(ROLE_CACHE_PREFIX + username);
|
||||
}
|
||||
log.info("已批量清除用户缓存 [ count={} ]", usernameList.size());
|
||||
}
|
||||
}
|
||||
@ -1,104 +0,0 @@
|
||||
package org.jeecg.config.satoken.ignore;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jeecg.config.satoken.IgnoreAuth;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 在spring boot初始化时,根据@RestController注解获取当前spring容器中的bean
|
||||
* @author eightmonth
|
||||
* @date 2024/4/18 11:35
|
||||
*/
|
||||
@Slf4j
|
||||
@Lazy(false)
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class IgnoreAuthPostProcessor implements InitializingBean {
|
||||
|
||||
private RequestMappingHandlerMapping requestMappingHandlerMapping;
|
||||
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
List<String> ignoreAuthUrls = new ArrayList<>();
|
||||
|
||||
// 优化:直接从HandlerMethod过滤,避免重复扫描
|
||||
requestMappingHandlerMapping.getHandlerMethods().values().stream()
|
||||
.filter(handlerMethod -> handlerMethod.getMethod().isAnnotationPresent(IgnoreAuth.class))
|
||||
.forEach(handlerMethod -> {
|
||||
Class<?> clazz = handlerMethod.getBeanType();
|
||||
Method method = handlerMethod.getMethod();
|
||||
ignoreAuthUrls.addAll(processIgnoreAuthMethod(clazz, method));
|
||||
});
|
||||
|
||||
log.info("Init Token ignoreAuthUrls Config [ 集合 ] :{}", ignoreAuthUrls);
|
||||
if (!CollectionUtils.isEmpty(ignoreAuthUrls)) {
|
||||
InMemoryIgnoreAuth.set(ignoreAuthUrls);
|
||||
}
|
||||
|
||||
// 计算方法的耗时
|
||||
long endTime = System.currentTimeMillis();
|
||||
long elapsedTime = endTime - startTime;
|
||||
log.info("Init Token ignoreAuthUrls Config [ 耗时 ] :" + elapsedTime + "ms");
|
||||
}
|
||||
|
||||
// 优化:新方法处理单个@IgnoreAuth方法,减少重复注解检查
|
||||
private List<String> processIgnoreAuthMethod(Class<?> clazz, Method method) {
|
||||
RequestMapping base = clazz.getAnnotation(RequestMapping.class);
|
||||
String[] baseUrl = Objects.nonNull(base) ? base.value() : new String[]{};
|
||||
|
||||
String[] uri = null;
|
||||
if (method.isAnnotationPresent(RequestMapping.class)) {
|
||||
uri = method.getAnnotation(RequestMapping.class).value();
|
||||
} else if (method.isAnnotationPresent(GetMapping.class)) {
|
||||
uri = method.getAnnotation(GetMapping.class).value();
|
||||
} else if (method.isAnnotationPresent(PostMapping.class)) {
|
||||
uri = method.getAnnotation(PostMapping.class).value();
|
||||
} else if (method.isAnnotationPresent(PutMapping.class)) {
|
||||
uri = method.getAnnotation(PutMapping.class).value();
|
||||
} else if (method.isAnnotationPresent(DeleteMapping.class)) {
|
||||
uri = method.getAnnotation(DeleteMapping.class).value();
|
||||
} else if (method.isAnnotationPresent(PatchMapping.class)) {
|
||||
uri = method.getAnnotation(PatchMapping.class).value();
|
||||
}
|
||||
|
||||
return uri != null ? rebuildUrl(baseUrl, uri) : Collections.emptyList();
|
||||
}
|
||||
|
||||
private List<String> rebuildUrl(String[] bases, String[] uris) {
|
||||
List<String> urls = new ArrayList<>();
|
||||
if (bases.length > 0) {
|
||||
for (String base : bases) {
|
||||
for (String uri : uris) {
|
||||
// 如果uri包含路径占位符, 则需要将其替换为*
|
||||
if (uri.matches(".*\\{.*}.*")) {
|
||||
uri = uri.replaceAll("\\{.*?}", "*");
|
||||
}
|
||||
urls.add(prefix(base) + prefix(uri));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Arrays.stream(uris).forEach(uri -> {
|
||||
urls.add(prefix(uri));
|
||||
});
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
private String prefix(String seg) {
|
||||
return seg.startsWith("/") ? seg : "/"+seg;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,90 @@
|
||||
package org.jeecg.config.security;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
||||
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
|
||||
import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat;
|
||||
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* spring authorization server 注册客户端便捷工具类
|
||||
* @author eightmonth@qq.com
|
||||
* @date 2024/3/7 11:22
|
||||
*/
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class ClientService {
|
||||
|
||||
private RegisteredClientRepository registeredClientRepository;
|
||||
|
||||
/**
|
||||
* 修改客户端token有效期
|
||||
* 认证码、设备码有效期与accessToken有效期保持一致
|
||||
*/
|
||||
public void updateTokenValidation(String clientId, Long accessTokenValidation, Long refreshTokenValidation){
|
||||
RegisteredClient registeredClient = findByClientId(clientId);
|
||||
RegisteredClient.Builder builder = RegisteredClient.from(registeredClient);
|
||||
TokenSettings tokenSettings = TokenSettings.builder()
|
||||
.idTokenSignatureAlgorithm(SignatureAlgorithm.RS256)
|
||||
.accessTokenTimeToLive(Duration.ofSeconds(accessTokenValidation))
|
||||
.accessTokenFormat(OAuth2TokenFormat.SELF_CONTAINED)
|
||||
.reuseRefreshTokens(true)
|
||||
.refreshTokenTimeToLive(Duration.ofSeconds(refreshTokenValidation))
|
||||
.authorizationCodeTimeToLive(Duration.ofSeconds(accessTokenValidation))
|
||||
.deviceCodeTimeToLive(Duration.ofSeconds(accessTokenValidation))
|
||||
.build();
|
||||
builder.tokenSettings(tokenSettings);
|
||||
registeredClientRepository.save(builder.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改客户端授权类型
|
||||
* @param clientId
|
||||
* @param grantTypes
|
||||
*/
|
||||
public void updateGrantType(String clientId, Set<AuthorizationGrantType> grantTypes) {
|
||||
RegisteredClient registeredClient = findByClientId(clientId);
|
||||
RegisteredClient.Builder builder = RegisteredClient.from(registeredClient);
|
||||
for (AuthorizationGrantType grantType : grantTypes) {
|
||||
builder.authorizationGrantType(grantType);
|
||||
}
|
||||
registeredClientRepository.save(builder.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改客户端重定向uri
|
||||
* @param clientId
|
||||
* @param redirectUris
|
||||
*/
|
||||
public void updateRedirectUris(String clientId, String redirectUris) {
|
||||
RegisteredClient registeredClient = findByClientId(clientId);
|
||||
RegisteredClient.Builder builder = RegisteredClient.from(registeredClient);
|
||||
builder.redirectUri(redirectUris);
|
||||
registeredClientRepository.save(builder.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改客户端授权范围
|
||||
* @param clientId
|
||||
* @param scopes
|
||||
*/
|
||||
public void updateScopes(String clientId, Set<String> scopes) {
|
||||
RegisteredClient registeredClient = findByClientId(clientId);
|
||||
RegisteredClient.Builder builder = RegisteredClient.from(registeredClient);
|
||||
for (String scope : scopes) {
|
||||
builder.scope(scope);
|
||||
}
|
||||
registeredClientRepository.save(builder.build());
|
||||
}
|
||||
|
||||
public RegisteredClient findByClientId(String clientId) {
|
||||
return registeredClientRepository.findByClientId(clientId);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,45 @@
|
||||
package org.jeecg.config.security;
|
||||
|
||||
import io.undertow.servlet.spec.HttpServletRequestImpl;
|
||||
import io.undertow.util.HttpString;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 复制仪盘表请求query体携带的token
|
||||
* @author eightmonth
|
||||
* @date 2024/7/3 14:04
|
||||
*/
|
||||
@Component
|
||||
@Order(value = Integer.MIN_VALUE)
|
||||
public class CopyTokenFilter extends OncePerRequestFilter {
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
||||
// 以下为undertow定制代码,如切换其它servlet容器,需要同步更换
|
||||
HttpServletRequestImpl undertowRequest = (HttpServletRequestImpl) request;
|
||||
String token = request.getHeader("Authorization");
|
||||
if (StringUtils.hasText(token)) {
|
||||
undertowRequest.getExchange().getRequestHeaders().remove("Authorization");
|
||||
undertowRequest.getExchange().getRequestHeaders().add(new HttpString("Authorization"), "bearer " + token);
|
||||
} else {
|
||||
String bearerToken = request.getParameter("token");
|
||||
String headerBearerToken = request.getHeader("X-Access-Token");
|
||||
if (StringUtils.hasText(bearerToken)) {
|
||||
undertowRequest.getExchange().getRequestHeaders().add(new HttpString("Authorization"), "bearer " + bearerToken);
|
||||
} else if (StringUtils.hasText(headerBearerToken)) {
|
||||
undertowRequest.getExchange().getRequestHeaders().add(new HttpString("Authorization"), "bearer " + headerBearerToken);
|
||||
}
|
||||
}
|
||||
filterChain.doFilter(undertowRequest, response);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
package org.jeecg.config.security;
|
||||
|
||||
import org.jeecg.common.api.CommonAPI;
|
||||
import org.jeecg.common.system.vo.LoginUser;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* token只存储用户名与过期时间
|
||||
* 这里通过取用户名转全量用户信息存储到Security中
|
||||
* @author eightmonth@qq.com
|
||||
* @date 2024/7/15 11:05
|
||||
*/
|
||||
@Component
|
||||
public class JeecgAuthenticationConvert implements Converter<Jwt, AbstractAuthenticationToken> {
|
||||
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CommonAPI commonAPI;
|
||||
|
||||
@Override
|
||||
public AbstractAuthenticationToken convert(Jwt source) {
|
||||
String username = source.getClaims().get("username").toString();
|
||||
LoginUser loginUser = commonAPI.getUserByName(username);
|
||||
return new UsernamePasswordAuthenticationToken(loginUser, null, new ArrayList<>());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,135 @@
|
||||
package org.jeecg.config.security;
|
||||
|
||||
import org.jeecg.common.system.util.JwtUtil;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.security.oauth2.core.ClaimAccessor;
|
||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
|
||||
import org.springframework.security.oauth2.jwt.JwsHeader;
|
||||
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
||||
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
|
||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationGrantAuthenticationToken;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||
import org.springframework.security.oauth2.server.authorization.token.*;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.Temporal;
|
||||
import java.time.temporal.TemporalUnit;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author eightmonth@qq.com
|
||||
* @date 2024/7/11 17:10
|
||||
*/
|
||||
public class JeecgOAuth2AccessTokenGenerator implements OAuth2TokenGenerator<OAuth2AccessToken> {
|
||||
private final JwtEncoder jwtEncoder;
|
||||
|
||||
private OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer;
|
||||
|
||||
public JeecgOAuth2AccessTokenGenerator(JwtEncoder jwtEncoder) {
|
||||
this.jwtEncoder = jwtEncoder;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public OAuth2AccessToken generate(OAuth2TokenContext context) {
|
||||
if (!OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String issuer = null;
|
||||
if (context.getAuthorizationServerContext() != null) {
|
||||
issuer = context.getAuthorizationServerContext().getIssuer();
|
||||
}
|
||||
RegisteredClient registeredClient = context.getRegisteredClient();
|
||||
|
||||
Instant issuedAt = Instant.now();
|
||||
Instant expiresAt = issuedAt.plusMillis(JwtUtil.EXPIRE_TIME);
|
||||
|
||||
OAuth2TokenClaimsSet.Builder claimsBuilder = OAuth2TokenClaimsSet.builder();
|
||||
if (StringUtils.hasText(issuer)) {
|
||||
claimsBuilder.issuer(issuer);
|
||||
}
|
||||
claimsBuilder
|
||||
.subject(context.getPrincipal().getName())
|
||||
.audience(Collections.singletonList(registeredClient.getClientId()))
|
||||
.issuedAt(issuedAt)
|
||||
.expiresAt(expiresAt)
|
||||
.notBefore(issuedAt)
|
||||
.id(UUID.randomUUID().toString());
|
||||
if (!CollectionUtils.isEmpty(context.getAuthorizedScopes())) {
|
||||
claimsBuilder.claim(OAuth2ParameterNames.SCOPE, context.getAuthorizedScopes());
|
||||
}
|
||||
|
||||
if (this.accessTokenCustomizer != null) {
|
||||
OAuth2TokenClaimsContext.Builder accessTokenContextBuilder = OAuth2TokenClaimsContext.with(claimsBuilder)
|
||||
.registeredClient(context.getRegisteredClient())
|
||||
.principal(context.getPrincipal())
|
||||
.authorizationServerContext(context.getAuthorizationServerContext())
|
||||
.authorizedScopes(context.getAuthorizedScopes())
|
||||
.tokenType(context.getTokenType())
|
||||
.authorizationGrantType(context.getAuthorizationGrantType());
|
||||
if (context.getAuthorization() != null) {
|
||||
accessTokenContextBuilder.authorization(context.getAuthorization());
|
||||
}
|
||||
if (context.getAuthorizationGrant() != null) {
|
||||
accessTokenContextBuilder.authorizationGrant(context.getAuthorizationGrant());
|
||||
}
|
||||
|
||||
OAuth2TokenClaimsContext accessTokenContext = accessTokenContextBuilder.build();
|
||||
this.accessTokenCustomizer.customize(accessTokenContext);
|
||||
}
|
||||
|
||||
|
||||
OAuth2TokenClaimsSet accessTokenClaimsSet = claimsBuilder.build();
|
||||
OAuth2AuthorizationGrantAuthenticationToken oAuth2ResourceOwnerBaseAuthenticationToken = context.getAuthorizationGrant();
|
||||
String username = (String) oAuth2ResourceOwnerBaseAuthenticationToken.getAdditionalParameters().get("username");
|
||||
String tokenValue = jwtEncoder.encode(JwtEncoderParameters.from(JwsHeader.with(SignatureAlgorithm.ES256).keyId("jeecg").build(),
|
||||
JwtClaimsSet.builder().claim("username", username).expiresAt(expiresAt).build())).getTokenValue();
|
||||
|
||||
//此处可以做改造将tokenValue随机数换成用户信息,方便后续多系统token互通认证(通过解密token得到username)
|
||||
return new OAuth2AccessTokenClaims(OAuth2AccessToken.TokenType.BEARER, tokenValue,
|
||||
accessTokenClaimsSet.getIssuedAt(), accessTokenClaimsSet.getExpiresAt(), context.getAuthorizedScopes(),
|
||||
accessTokenClaimsSet.getClaims());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {@link OAuth2TokenCustomizer} that customizes the
|
||||
* {@link OAuth2TokenClaimsContext#getClaims() claims} for the
|
||||
* {@link OAuth2AccessToken}.
|
||||
* @param accessTokenCustomizer the {@link OAuth2TokenCustomizer} that customizes the
|
||||
* claims for the {@code OAuth2AccessToken}
|
||||
*/
|
||||
public void setAccessTokenCustomizer(OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer) {
|
||||
Assert.notNull(accessTokenCustomizer, "accessTokenCustomizer cannot be null");
|
||||
this.accessTokenCustomizer = accessTokenCustomizer;
|
||||
}
|
||||
|
||||
private static final class OAuth2AccessTokenClaims extends OAuth2AccessToken implements ClaimAccessor {
|
||||
|
||||
private final Map<String, Object> claims;
|
||||
|
||||
private OAuth2AccessTokenClaims(TokenType tokenType, String tokenValue, Instant issuedAt, Instant expiresAt,
|
||||
Set<String> scopes, Map<String, Object> claims) {
|
||||
super(tokenType, tokenValue, issuedAt, expiresAt, scopes);
|
||||
this.claims = claims;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getClaims() {
|
||||
return this.claims;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,104 @@
|
||||
package org.jeecg.config.security;
|
||||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jeecg.common.api.CommonAPI;
|
||||
import org.jeecg.common.system.vo.LoginUser;
|
||||
import org.jeecg.common.util.RedisUtil;
|
||||
import org.jeecg.config.security.utils.SecureUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.PatternMatchUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* spring authorization server自定义权限处理,根据@PreAuthorize注解,判断当前用户是否具备权限
|
||||
* @author EightMonth
|
||||
* @date 2024/1/10 17:00
|
||||
*/
|
||||
@Service("jps")
|
||||
@Slf4j
|
||||
public class JeecgPermissionService {
|
||||
private final String SPLIT = "::";
|
||||
private final String PERM_PREFIX = "jps" + SPLIT;
|
||||
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CommonAPI commonAPI;
|
||||
@Autowired
|
||||
private RedisUtil redisUtil;
|
||||
|
||||
/**
|
||||
* 判断接口是否有任意xxx,xxx权限
|
||||
* @param permissions 权限
|
||||
* @return {boolean}
|
||||
*/
|
||||
public boolean requiresPermissions(String... permissions) {
|
||||
if (ArrayUtil.isEmpty(permissions)) {
|
||||
return false;
|
||||
}
|
||||
LoginUser loginUser = SecureUtil.currentUser();
|
||||
|
||||
Object cache = redisUtil.get(buildKey("permission", loginUser.getId()));
|
||||
Set<String> permissionList;
|
||||
if (Objects.nonNull(cache)) {
|
||||
permissionList = (Set<String>) cache;
|
||||
} else {
|
||||
permissionList = commonAPI.queryUserAuths(loginUser.getId());
|
||||
redisUtil.set(buildKey("permission", loginUser.getId()), permissionList);
|
||||
}
|
||||
|
||||
boolean pass = permissionList.stream().filter(StringUtils::hasText)
|
||||
.anyMatch(x -> PatternMatchUtils.simpleMatch(permissions, x));
|
||||
if (!pass) {
|
||||
log.error("权限不足,缺少权限:"+ Arrays.toString(permissions));
|
||||
}
|
||||
return pass;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断接口是否有任意xxx,xxx角色
|
||||
* @param roles 角色
|
||||
* @return {boolean}
|
||||
*/
|
||||
public boolean requiresRoles(String... roles) {
|
||||
if (ArrayUtil.isEmpty(roles)) {
|
||||
return false;
|
||||
}
|
||||
LoginUser loginUser = SecureUtil.currentUser();
|
||||
|
||||
Object cache = redisUtil.get(buildKey("role", loginUser.getUsername()));
|
||||
Set<String> roleList;
|
||||
if (Objects.nonNull(cache)) {
|
||||
roleList = (Set<String>) cache;
|
||||
} else {
|
||||
roleList = commonAPI.queryUserRoles(loginUser.getUsername());
|
||||
redisUtil.set(buildKey("role", loginUser.getUsername()), roleList);
|
||||
}
|
||||
|
||||
boolean pass = roleList.stream().filter(StringUtils::hasText)
|
||||
.anyMatch(x -> PatternMatchUtils.simpleMatch(roles, x));
|
||||
if (!pass) {
|
||||
log.error("权限不足,缺少角色:" + Arrays.toString(roles));
|
||||
}
|
||||
return pass;
|
||||
}
|
||||
|
||||
/**
|
||||
* 由于缓存key是以人的维度,角色列表、权限列表在值中,jeecg是以权限列表绑定在角色上,形成的权限集合
|
||||
* 权限发生变更时,需要清理全部人的权限缓存
|
||||
*/
|
||||
public void clearCache() {
|
||||
redisUtil.removeAll(PERM_PREFIX);
|
||||
}
|
||||
|
||||
private String buildKey(String type, String username) {
|
||||
return PERM_PREFIX + type + SPLIT + username;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,54 @@
|
||||
package org.jeecg.config.security;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* spring authorization server 自定义redis保存授权范围信息
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class JeecgRedisOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {
|
||||
|
||||
private final RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
private final static Long TIMEOUT = 10L;
|
||||
|
||||
@Override
|
||||
public void save(OAuth2AuthorizationConsent authorizationConsent) {
|
||||
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
|
||||
|
||||
redisTemplate.opsForValue().set(buildKey(authorizationConsent), authorizationConsent, TIMEOUT,
|
||||
TimeUnit.MINUTES);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(OAuth2AuthorizationConsent authorizationConsent) {
|
||||
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
|
||||
redisTemplate.delete(buildKey(authorizationConsent));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) {
|
||||
Assert.hasText(registeredClientId, "registeredClientId cannot be empty");
|
||||
Assert.hasText(principalName, "principalName cannot be empty");
|
||||
return (OAuth2AuthorizationConsent) redisTemplate.opsForValue()
|
||||
.get(buildKey(registeredClientId, principalName));
|
||||
}
|
||||
|
||||
private static String buildKey(String registeredClientId, String principalName) {
|
||||
return "token:consent:" + registeredClientId + ":" + principalName;
|
||||
}
|
||||
|
||||
private static String buildKey(OAuth2AuthorizationConsent authorizationConsent) {
|
||||
return buildKey(authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName());
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,192 @@
|
||||
package org.jeecg.config.security;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.RedisSerializer;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* spring authorization server自定义redis保存认证信息
|
||||
* @author EightMonth
|
||||
*/
|
||||
@Component
|
||||
public class JeecgRedisOAuth2AuthorizationService implements OAuth2AuthorizationService{
|
||||
|
||||
private final static Long TIMEOUT = 10L;
|
||||
|
||||
private static final String AUTHORIZATION = "token";
|
||||
|
||||
private final RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
|
||||
|
||||
@Autowired
|
||||
private RedisConnectionFactory redisConnectionFactory;
|
||||
|
||||
/**
|
||||
* 因为保存sas的认证信息至redis,无法使用jeecg对redisTemplate的某些设置。
|
||||
* 如果在使用时修改redisTemplate属性,会发生线程安全问题,最终容易引起系统无法正常运行。
|
||||
* 所以重新建了一个redis client给到sas操作redis,并且该redis实例不注入spring 容器中
|
||||
*/
|
||||
@PostConstruct
|
||||
public void initSasRedis() {
|
||||
redisTemplate.setValueSerializer(RedisSerializer.java());
|
||||
redisTemplate.setConnectionFactory(redisConnectionFactory);
|
||||
redisTemplate.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(OAuth2Authorization authorization) {
|
||||
Assert.notNull(authorization, "authorization cannot be null");
|
||||
|
||||
if (isState(authorization)) {
|
||||
String token = authorization.getAttribute("state");
|
||||
redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.STATE, token), authorization, TIMEOUT,
|
||||
TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
if (isCode(authorization)) {
|
||||
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
|
||||
.getToken(OAuth2AuthorizationCode.class);
|
||||
OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken();
|
||||
long between = ChronoUnit.MINUTES.between(authorizationCodeToken.getIssuedAt(),
|
||||
authorizationCodeToken.getExpiresAt());
|
||||
redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue()),
|
||||
authorization, between, TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
if (isRefreshToken(authorization)) {
|
||||
OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken();
|
||||
long between = ChronoUnit.SECONDS.between(refreshToken.getIssuedAt(), refreshToken.getExpiresAt());
|
||||
redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue()),
|
||||
authorization, between, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
if (isAccessToken(authorization)) {
|
||||
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
|
||||
long between = ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt());
|
||||
redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue()),
|
||||
authorization, between, TimeUnit.SECONDS);
|
||||
|
||||
// 扩展记录 access-token 、username 的关系 1::token::username::admin::xxx
|
||||
String tokenUsername = String.format("%s::%s::%s", AUTHORIZATION, authorization.getPrincipalName(), accessToken.getTokenValue());
|
||||
redisTemplate.opsForValue().set(tokenUsername, accessToken.getTokenValue(), between, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(OAuth2Authorization authorization) {
|
||||
Assert.notNull(authorization, "authorization cannot be null");
|
||||
|
||||
List<String> keys = new ArrayList<>();
|
||||
if (isState(authorization)) {
|
||||
String token = authorization.getAttribute("state");
|
||||
keys.add(buildKey(OAuth2ParameterNames.STATE, token));
|
||||
}
|
||||
|
||||
if (isCode(authorization)) {
|
||||
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
|
||||
.getToken(OAuth2AuthorizationCode.class);
|
||||
OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken();
|
||||
keys.add(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue()));
|
||||
}
|
||||
|
||||
if (isRefreshToken(authorization)) {
|
||||
OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken();
|
||||
keys.add(buildKey(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue()));
|
||||
}
|
||||
|
||||
if (isAccessToken(authorization)) {
|
||||
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
|
||||
keys.add(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue()));
|
||||
|
||||
// 扩展记录 access-token 、username 的关系 1::token::username::admin::xxx
|
||||
String key = String.format("%s::%s::%s", AUTHORIZATION, authorization.getPrincipalName(), accessToken.getTokenValue());
|
||||
keys.add(key);
|
||||
}
|
||||
|
||||
redisTemplate.delete(keys);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public OAuth2Authorization findById(String id) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public OAuth2Authorization findByToken(String token, @Nullable OAuth2TokenType tokenType) {
|
||||
Assert.hasText(token, "token cannot be empty");
|
||||
Assert.notNull(tokenType, "tokenType cannot be empty");
|
||||
return (OAuth2Authorization) redisTemplate.opsForValue().get(buildKey(tokenType.getValue(), token));
|
||||
}
|
||||
|
||||
private String buildKey(String type, String id) {
|
||||
return String.format("%s::%s::%s", AUTHORIZATION, type, id);
|
||||
}
|
||||
|
||||
private static boolean isState(OAuth2Authorization authorization) {
|
||||
return Objects.nonNull(authorization.getAttribute("state"));
|
||||
}
|
||||
|
||||
private static boolean isCode(OAuth2Authorization authorization) {
|
||||
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
|
||||
.getToken(OAuth2AuthorizationCode.class);
|
||||
return Objects.nonNull(authorizationCode);
|
||||
}
|
||||
|
||||
private static boolean isRefreshToken(OAuth2Authorization authorization) {
|
||||
return Objects.nonNull(authorization.getRefreshToken());
|
||||
}
|
||||
|
||||
private static boolean isAccessToken(OAuth2Authorization authorization) {
|
||||
return Objects.nonNull(authorization.getAccessToken());
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展方法根据 username 查询是否存在存储的
|
||||
* @param authentication
|
||||
* @return
|
||||
*/
|
||||
public void removeByUsername(Authentication authentication) {
|
||||
// 根据 username查询对应access-token
|
||||
String authenticationName = authentication.getName();
|
||||
|
||||
// 扩展记录 access-token 、username 的关系 1::token::username::admin::xxx
|
||||
String tokenUsernameKey = String.format("%s::%s::*", AUTHORIZATION, authenticationName);
|
||||
Set<String> keys = redisTemplate.keys(tokenUsernameKey);
|
||||
if (CollUtil.isEmpty(keys)) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<Object> tokenList = redisTemplate.opsForValue().multiGet(keys);
|
||||
|
||||
for (Object token : tokenList) {
|
||||
// 根据token 查询存储的 OAuth2Authorization
|
||||
OAuth2Authorization authorization = this.findByToken((String) token, OAuth2TokenType.ACCESS_TOKEN);
|
||||
// 根据 OAuth2Authorization 删除相关令牌
|
||||
this.remove(authorization);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
package org.jeecg.config.security;
|
||||
|
||||
/**
|
||||
* 登录模式
|
||||
* @author EightMonth
|
||||
* @date 2024/1/10 17:43
|
||||
*/
|
||||
public class LoginType {
|
||||
|
||||
/**
|
||||
* 密码模式
|
||||
*/
|
||||
public static final String PASSWORD = "password";
|
||||
|
||||
|
||||
/**
|
||||
* 手机号+验证码模式
|
||||
*/
|
||||
public static final String PHONE = "phone";
|
||||
|
||||
|
||||
/**
|
||||
* app登录
|
||||
*/
|
||||
public static final String APP = "app";
|
||||
|
||||
/**
|
||||
* 扫码登录
|
||||
*/
|
||||
public static final String SCAN = "scan";
|
||||
|
||||
/**
|
||||
* 所有联合登录,比如github\钉钉\企业微信\微信
|
||||
*/
|
||||
public static final String SOCIAL = "social";
|
||||
|
||||
public static final String SELF = "self";
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
package org.jeecg.config.security;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.jeecg.common.system.util.JwtUtil;
|
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
|
||||
import org.springframework.security.oauth2.server.resource.BearerTokenErrors;
|
||||
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 当用户被强退时,使客户端token失效
|
||||
* @author eightmonth@qq.com
|
||||
* @date 2024/3/7 17:30
|
||||
*/
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class RedisTokenValidationFilter extends OncePerRequestFilter {
|
||||
private OAuth2AuthorizationService authorizationService;
|
||||
private JwtDecoder jwtDecoder;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
||||
// 从请求中获取token
|
||||
DefaultBearerTokenResolver defaultBearerTokenResolver = new DefaultBearerTokenResolver();
|
||||
String token = defaultBearerTokenResolver.resolve(request);
|
||||
|
||||
|
||||
if (Objects.nonNull(token)) {
|
||||
// 检查认证信息是否已被清除,如果已被清除,则令该token失效
|
||||
OAuth2Authorization oAuth2Authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
|
||||
if (Objects.isNull(oAuth2Authorization)) {
|
||||
throw new OAuth2AuthenticationException(BearerTokenErrors.invalidToken("认证信息已失效,请重新登录"));
|
||||
}
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,249 @@
|
||||
package org.jeecg.config.security;
|
||||
|
||||
import com.nimbusds.jose.jwk.Curve;
|
||||
import com.nimbusds.jose.jwk.ECKey;
|
||||
import com.nimbusds.jose.jwk.JWKSet;
|
||||
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.SneakyThrows;
|
||||
import org.jeecg.config.security.app.AppGrantAuthenticationConvert;
|
||||
import org.jeecg.config.security.app.AppGrantAuthenticationProvider;
|
||||
import org.jeecg.config.security.password.PasswordGrantAuthenticationConvert;
|
||||
import org.jeecg.config.security.password.PasswordGrantAuthenticationProvider;
|
||||
import org.jeecg.config.security.phone.PhoneGrantAuthenticationConvert;
|
||||
import org.jeecg.config.security.phone.PhoneGrantAuthenticationProvider;
|
||||
import org.jeecg.config.security.social.SocialGrantAuthenticationConvert;
|
||||
import org.jeecg.config.security.social.SocialGrantAuthenticationProvider;
|
||||
import org.jeecg.config.shiro.ignore.InMemoryIgnoreAuth;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
|
||||
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
|
||||
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
|
||||
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
|
||||
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
|
||||
import org.springframework.security.oauth2.server.authorization.token.*;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.interfaces.ECPrivateKey;
|
||||
import java.security.interfaces.ECPublicKey;
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* spring authorization server核心配置
|
||||
* @author eightmonth@qq.com
|
||||
* @date 2024/1/2 9:29
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableMethodSecurity
|
||||
@AllArgsConstructor
|
||||
public class SecurityConfig {
|
||||
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
private OAuth2AuthorizationService authorizationService;
|
||||
private JeecgAuthenticationConvert jeecgAuthenticationConvert;
|
||||
|
||||
@Bean
|
||||
@Order(1)
|
||||
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)
|
||||
throws Exception {
|
||||
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
|
||||
// 注册自定义登录类型
|
||||
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
|
||||
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new PasswordGrantAuthenticationConvert())
|
||||
.authenticationProvider(new PasswordGrantAuthenticationProvider(authorizationService, tokenGenerator())))
|
||||
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new PhoneGrantAuthenticationConvert())
|
||||
.authenticationProvider(new PhoneGrantAuthenticationProvider(authorizationService, tokenGenerator())))
|
||||
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new AppGrantAuthenticationConvert())
|
||||
.authenticationProvider(new AppGrantAuthenticationProvider(authorizationService, tokenGenerator())))
|
||||
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new SocialGrantAuthenticationConvert())
|
||||
.authenticationProvider(new SocialGrantAuthenticationProvider(authorizationService, tokenGenerator())))
|
||||
//开启OpenID Connect 1.0(其中oidc为OpenID Connect的缩写)。 访问 /.well-known/openid-configuration即可获取认证信息
|
||||
.oidc(Customizer.withDefaults());
|
||||
http
|
||||
//将需要认证的请求,重定向到login页面行登录认证。
|
||||
.exceptionHandling((exceptions) -> exceptions
|
||||
.defaultAuthenticationEntryPointFor(
|
||||
new LoginUrlAuthenticationEntryPoint("/sys/login"),
|
||||
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
|
||||
)
|
||||
);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(2)
|
||||
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
|
||||
throws Exception {
|
||||
http
|
||||
//设置所有请求都需要认证,未认证的请求都被重定向到login页面进行登录
|
||||
.authorizeHttpRequests((authorize) -> authorize
|
||||
.requestMatchers(InMemoryIgnoreAuth.get().stream().map(AntPathRequestMatcher::antMatcher).toList().toArray(new AntPathRequestMatcher[0])).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/cas/client/validateLogin")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/randomImage/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/checkCaptcha")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/login")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/mLogin")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/logout")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/thirdLogin/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/getEncryptedString")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/sms")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/phoneLogin")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/user/checkOnlyUser")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/user/register")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/user/phoneVerification")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/user/passwordChange")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/auth/2step-code")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/common/static/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/common/pdf/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/generic/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/getLoginQrcode/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/getQrcodeToken/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/checkAuth")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/doc.html")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.js")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.css")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.html")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.svg")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.pdf")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.jpg")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.png")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.gif")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.ico")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.ttf")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.woff")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.woff2")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/druid/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/swagger-ui.html")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/swagger**/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/webjars/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/v3/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/WW_verify*")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/annountCement/show/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/jmreport/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.js.map")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.css.map")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/api/getUserInfo")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/list")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/view")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/onlDragDatasetHead/getLoginUser")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/page/queryById")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/onlDragDatasetHead/getAllChartData")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/onlDragDatasetHead/getTotalData")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/mock/json/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/test/bigScreen/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/bigscreen/visual/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/bigscreen/category/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/bigscreen/map/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/bigscreen/template1/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/bigscreen/template1/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/websocket/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/newsWebsocket/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/vxeSocket/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/test/seata/**")).permitAll()
|
||||
.requestMatchers(AntPathRequestMatcher.antMatcher("/error")).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
|
||||
.cors(cors -> cors
|
||||
.configurationSource(req -> {
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
config.applyPermitDefaultValues();
|
||||
config.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
|
||||
return config;
|
||||
}))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jeecgAuthenticationConvert)));
|
||||
return http.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据库保存注册客户端信息
|
||||
*/
|
||||
@Bean
|
||||
public RegisteredClientRepository registeredClientRepository() {
|
||||
return new JdbcRegisteredClientRepository(jdbcTemplate);
|
||||
}
|
||||
|
||||
/**
|
||||
*配置 JWK,为JWT(id_token)提供加密密钥,用于加密/解密或签名/验签
|
||||
* JWK详细见:https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-key-41
|
||||
*/
|
||||
@Bean
|
||||
@SneakyThrows
|
||||
public JWKSource<SecurityContext> jwkSource() {
|
||||
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
|
||||
// 如果不设置secureRandom,会存在一个问题,当应用重启后,原有的token将会全部失效,因为重启的keyPair与之前已经不同
|
||||
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
|
||||
// 重要!生产环境需要修改!
|
||||
secureRandom.setSeed("jeecg".getBytes());
|
||||
keyPairGenerator.initialize(256, secureRandom);
|
||||
KeyPair keyPair = keyPairGenerator.generateKeyPair();
|
||||
ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
|
||||
ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
|
||||
|
||||
ECKey jwk = new ECKey.Builder(Curve.P_256, publicKey)
|
||||
.privateKey(privateKey)
|
||||
.keyID("jeecg")
|
||||
.build();
|
||||
JWKSet jwkSet = new JWKSet(jwk);
|
||||
return new ImmutableJWKSet<>(jwkSet);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return NoOpPasswordEncoder.getInstance();
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置jwt解析器
|
||||
*/
|
||||
@Bean
|
||||
public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
|
||||
return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
|
||||
}
|
||||
|
||||
/**
|
||||
*配置token生成器
|
||||
*/
|
||||
@Bean
|
||||
OAuth2TokenGenerator<?> tokenGenerator() {
|
||||
JwtGenerator jwtGenerator = new JwtGenerator(new NimbusJwtEncoder(jwkSource()));
|
||||
OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
|
||||
OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
|
||||
return new DelegatingOAuth2TokenGenerator(
|
||||
new JeecgOAuth2AccessTokenGenerator(new NimbusJwtEncoder(jwkSource())),
|
||||
new OAuth2RefreshTokenGenerator()
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,81 @@
|
||||
package org.jeecg.config.security.app;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.jeecg.config.security.LoginType;
|
||||
import org.jeecg.config.security.password.PasswordGrantAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||
import org.springframework.security.web.authentication.AuthenticationConverter;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* APP模式认证转换器
|
||||
* @author EightMonth
|
||||
* @date 2024/1/1
|
||||
*/
|
||||
public class AppGrantAuthenticationConvert implements AuthenticationConverter {
|
||||
@Override
|
||||
public Authentication convert(HttpServletRequest request) {
|
||||
|
||||
String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
|
||||
if (!LoginType.APP.equals(grantType)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
//从request中提取请求参数,然后存入MultiValueMap<String, String>
|
||||
MultiValueMap<String, String> parameters = getParameters(request);
|
||||
|
||||
// username (REQUIRED)
|
||||
String username = parameters.getFirst(OAuth2ParameterNames.USERNAME);
|
||||
if (!StringUtils.hasText(username) ||
|
||||
parameters.get(OAuth2ParameterNames.USERNAME).size() != 1) {
|
||||
throw new OAuth2AuthenticationException("无效请求,用户名不能为空!");
|
||||
}
|
||||
String password = parameters.getFirst(OAuth2ParameterNames.PASSWORD);
|
||||
if (!StringUtils.hasText(password) ||
|
||||
parameters.get(OAuth2ParameterNames.PASSWORD).size() != 1) {
|
||||
throw new OAuth2AuthenticationException("无效请求,密码不能为空!");
|
||||
}
|
||||
|
||||
//收集要传入PasswordGrantAuthenticationToken构造方法的参数,
|
||||
//该参数接下来在PasswordGrantAuthenticationProvider中使用
|
||||
Map<String, Object> additionalParameters = new HashMap<>();
|
||||
//遍历从request中提取的参数,排除掉grant_type、client_id、code等字段参数,其他参数收集到additionalParameters中
|
||||
parameters.forEach((key, value) -> {
|
||||
if (!key.equals(OAuth2ParameterNames.GRANT_TYPE) &&
|
||||
!key.equals(OAuth2ParameterNames.CLIENT_ID) &&
|
||||
!key.equals(OAuth2ParameterNames.CODE)) {
|
||||
additionalParameters.put(key, value.get(0));
|
||||
}
|
||||
});
|
||||
|
||||
//返回自定义的PasswordGrantAuthenticationToken对象
|
||||
return new PasswordGrantAuthenticationToken(clientPrincipal, additionalParameters);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*从request中提取请求参数,然后存入MultiValueMap<String, String>
|
||||
*/
|
||||
private static MultiValueMap<String, String> getParameters(HttpServletRequest request) {
|
||||
Map<String, String[]> parameterMap = request.getParameterMap();
|
||||
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size());
|
||||
parameterMap.forEach((key, values) -> {
|
||||
if (values.length > 0) {
|
||||
for (String value : values) {
|
||||
parameters.add(key, value);
|
||||
}
|
||||
}
|
||||
});
|
||||
return parameters;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,320 @@
|
||||
package org.jeecg.config.security.app;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jeecg.common.api.CommonAPI;
|
||||
import org.jeecg.common.constant.CacheConstant;
|
||||
import org.jeecg.common.constant.CommonConstant;
|
||||
import org.jeecg.common.exception.JeecgBootException;
|
||||
import org.jeecg.common.exception.JeecgCaptchaException;
|
||||
import org.jeecg.common.system.vo.LoginUser;
|
||||
import org.jeecg.common.system.vo.SysDepartModel;
|
||||
import org.jeecg.common.util.Md5Util;
|
||||
import org.jeecg.common.util.PasswordUtil;
|
||||
import org.jeecg.common.util.RedisUtil;
|
||||
import org.jeecg.common.util.oConvertUtils;
|
||||
import org.jeecg.config.JeecgBaseConfig;
|
||||
import org.jeecg.config.security.password.PasswordGrantAuthenticationToken;
|
||||
import org.jeecg.modules.base.service.BaseCommonService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.oauth2.core.*;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
|
||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
|
||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||
import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContextHolder;
|
||||
import org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext;
|
||||
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
|
||||
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* APP模式认证处理器,负责处理该认证模式下的核心逻辑
|
||||
* @author EightMonth
|
||||
* @date 2024/1/1
|
||||
*/
|
||||
@Slf4j
|
||||
public class AppGrantAuthenticationProvider implements AuthenticationProvider {
|
||||
|
||||
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
|
||||
|
||||
private final OAuth2AuthorizationService authorizationService;
|
||||
private final OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator;
|
||||
@Lazy
|
||||
@Autowired
|
||||
private CommonAPI commonAPI;
|
||||
@Autowired
|
||||
private RedisUtil redisUtil;
|
||||
@Autowired
|
||||
private JeecgBaseConfig jeecgBaseConfig;
|
||||
@Autowired
|
||||
private BaseCommonService baseCommonService;
|
||||
|
||||
public AppGrantAuthenticationProvider(OAuth2AuthorizationService authorizationService, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator) {
|
||||
Assert.notNull(authorizationService, "authorizationService cannot be null");
|
||||
Assert.notNull(tokenGenerator, "tokenGenerator cannot be null");
|
||||
this.authorizationService = authorizationService;
|
||||
this.tokenGenerator = tokenGenerator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||
AppGrantAuthenticationToken appGrantAuthenticationToken = (AppGrantAuthenticationToken) authentication;
|
||||
Map<String, Object> additionalParameter = appGrantAuthenticationToken.getAdditionalParameters();
|
||||
|
||||
// 授权类型
|
||||
AuthorizationGrantType authorizationGrantType = appGrantAuthenticationToken.getGrantType();
|
||||
// 用户名
|
||||
String username = (String) additionalParameter.get(OAuth2ParameterNames.USERNAME);
|
||||
// 密码
|
||||
String password = (String) additionalParameter.get(OAuth2ParameterNames.PASSWORD);
|
||||
//请求参数权限范围
|
||||
String requestScopesStr = (String)additionalParameter.getOrDefault(OAuth2ParameterNames.SCOPE, "*");
|
||||
//请求参数权限范围专场集合
|
||||
Set<String> requestScopeSet = Stream.of(requestScopesStr.split(" ")).collect(Collectors.toSet());
|
||||
// 验证码
|
||||
String captcha = (String) additionalParameter.get("captcha");
|
||||
String checkKey = (String) additionalParameter.get("checkKey");
|
||||
|
||||
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(appGrantAuthenticationToken);
|
||||
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
|
||||
|
||||
// 检查登录失败次数
|
||||
if(isLoginFailOvertimes(username)){
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("message", "该用户登录失败次数过多,请于10分钟后再次登录!");
|
||||
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
|
||||
}
|
||||
|
||||
if(captcha==null){
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("message", "验证码无效");
|
||||
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
|
||||
}
|
||||
String lowerCaseCaptcha = captcha.toLowerCase();
|
||||
// 加入密钥作为混淆,避免简单的拼接,被外部利用,用户自定义该密钥即可
|
||||
String origin = lowerCaseCaptcha+checkKey+jeecgBaseConfig.getSignatureSecret();
|
||||
String realKey = Md5Util.md5Encode(origin, "utf-8");
|
||||
Object checkCode = redisUtil.get(realKey);
|
||||
//当进入登录页时,有一定几率出现验证码错误 #1714
|
||||
if(checkCode==null || !checkCode.toString().equals(lowerCaseCaptcha)) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("message", "验证码错误");
|
||||
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
|
||||
}
|
||||
|
||||
if (!registeredClient.getAuthorizationGrantTypes().contains(authorizationGrantType)) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("message", "非法登录");
|
||||
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
|
||||
}
|
||||
|
||||
// 通过用户名获取用户信息
|
||||
LoginUser loginUser = commonAPI.getUserByName(username);
|
||||
//update-begin---author:eightmonth ---date:2024-04-30 for:【6168】master分支切sas分支登录发生错误-----------
|
||||
if (Objects.isNull(loginUser) || !StringUtils.hasText(loginUser.getSalt())) {
|
||||
redisUtil.del(CacheConstant.SYS_USERS_CACHE+"::"+username);
|
||||
loginUser = commonAPI.getUserByName(username);
|
||||
}
|
||||
//update-end---author:eightmonth ---date::2024-04-30 for:【6168】master分支切sas分支登录发生错误--------------
|
||||
// 检查用户可行性
|
||||
checkUserIsEffective(loginUser);
|
||||
|
||||
// 不使用spring security passwordEncoder针对密码进行匹配,使用自有加密匹配,针对 spring security使用noop传输
|
||||
password = PasswordUtil.encrypt(username, password, loginUser.getSalt());
|
||||
if (!password.equals(loginUser.getPassword())) {
|
||||
addLoginFailOvertimes(username);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("message", "用户名或密码不正确");
|
||||
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
|
||||
}
|
||||
|
||||
//由于在上面已验证过用户名、密码,现在构建一个已认证的对象UsernamePasswordAuthenticationToken
|
||||
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = UsernamePasswordAuthenticationToken.authenticated(loginUser,clientPrincipal,new ArrayList<>());
|
||||
|
||||
DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder()
|
||||
.registeredClient(registeredClient)
|
||||
.principal(usernamePasswordAuthenticationToken)
|
||||
.authorizationServerContext(AuthorizationServerContextHolder.getContext())
|
||||
.authorizationGrantType(authorizationGrantType)
|
||||
.authorizedScopes(requestScopeSet)
|
||||
.authorizationGrant(appGrantAuthenticationToken);
|
||||
|
||||
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.withRegisteredClient(registeredClient)
|
||||
.principalName(clientPrincipal.getName())
|
||||
.authorizedScopes(requestScopeSet)
|
||||
.attribute(Principal.class.getName(), username)
|
||||
.authorizationGrantType(authorizationGrantType);
|
||||
|
||||
|
||||
// ----- Access token -----
|
||||
OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
|
||||
OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
|
||||
if (generatedAccessToken == null) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("message", "无法生成访问token,请联系管理系。");
|
||||
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
|
||||
}
|
||||
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
|
||||
generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
|
||||
generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
|
||||
if (generatedAccessToken instanceof ClaimAccessor) {
|
||||
authorizationBuilder.token(accessToken, (metadata) -> {
|
||||
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims());
|
||||
});
|
||||
} else {
|
||||
authorizationBuilder.accessToken(accessToken);
|
||||
}
|
||||
|
||||
// ----- Refresh token -----
|
||||
OAuth2RefreshToken refreshToken = null;
|
||||
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) &&
|
||||
// 不向公共客户端颁发刷新令牌
|
||||
!clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
|
||||
|
||||
tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
|
||||
OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
|
||||
if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("message", "无法生成刷新token,请联系管理员。");
|
||||
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
|
||||
}
|
||||
|
||||
refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
|
||||
authorizationBuilder.refreshToken(refreshToken);
|
||||
}
|
||||
|
||||
OAuth2Authorization authorization = authorizationBuilder.build();
|
||||
|
||||
// 保存认证信息至redis
|
||||
authorizationService.save(authorization);
|
||||
|
||||
// 登录成功,删除redis中的验证码
|
||||
redisUtil.del(realKey);
|
||||
redisUtil.del(CommonConstant.LOGIN_FAIL + username);
|
||||
baseCommonService.addLog("用户名: " + username + ",登录成功!", CommonConstant.LOG_TYPE_1, null,loginUser);
|
||||
|
||||
JSONObject addition = new JSONObject(new LinkedHashMap<>());
|
||||
addition.put("token", accessToken.getTokenValue());
|
||||
// 设置租户
|
||||
JSONObject jsonObject = commonAPI.setLoginTenant(username);
|
||||
addition.putAll(jsonObject.getInnerMap());
|
||||
|
||||
// 设置登录用户信息
|
||||
addition.put("userInfo", loginUser);
|
||||
addition.put("sysAllDictItems", commonAPI.queryAllDictItems());
|
||||
|
||||
List<SysDepartModel> departs = commonAPI.queryUserDeparts(loginUser.getId());
|
||||
addition.put("departs", departs);
|
||||
if (departs == null || departs.size() == 0) {
|
||||
addition.put("multi_depart", 0);
|
||||
} else if (departs.size() == 1) {
|
||||
commonAPI.updateUserDepart(username, departs.get(0).getOrgCode(),null);
|
||||
addition.put("multi_depart", 1);
|
||||
} else {
|
||||
//查询当前是否有登录部门
|
||||
if(oConvertUtils.isEmpty(loginUser.getOrgCode())){
|
||||
commonAPI.updateUserDepart(username, departs.get(0).getOrgCode(),null);
|
||||
}
|
||||
addition.put("multi_depart", 2);
|
||||
}
|
||||
|
||||
// 兼容原有shiro登录结果处理
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("result", addition);
|
||||
map.put("code", 200);
|
||||
map.put("success", true);
|
||||
map.put("timestamp", System.currentTimeMillis());
|
||||
|
||||
// 返回access_token、refresh_token以及其它信息给到前端
|
||||
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, refreshToken, map);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> authentication) {
|
||||
return AppGrantAuthenticationToken.class.isAssignableFrom(authentication);
|
||||
}
|
||||
|
||||
private static OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(Authentication authentication) {
|
||||
OAuth2ClientAuthenticationToken clientPrincipal = null;
|
||||
if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getPrincipal().getClass())) {
|
||||
clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getPrincipal();
|
||||
}
|
||||
if (clientPrincipal != null && clientPrincipal.isAuthenticated()) {
|
||||
return clientPrincipal;
|
||||
}
|
||||
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录失败超出次数5 返回true
|
||||
* @param username
|
||||
* @return
|
||||
*/
|
||||
private boolean isLoginFailOvertimes(String username){
|
||||
String key = CommonConstant.LOGIN_FAIL + username;
|
||||
Object failTime = redisUtil.get(key);
|
||||
if(failTime!=null){
|
||||
Integer val = Integer.parseInt(failTime.toString());
|
||||
if(val>5){
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录登录失败次数
|
||||
* @param username
|
||||
*/
|
||||
private void addLoginFailOvertimes(String username){
|
||||
String key = CommonConstant.LOGIN_FAIL + username;
|
||||
Object failTime = redisUtil.get(key);
|
||||
Integer val = 0;
|
||||
if(failTime!=null){
|
||||
val = Integer.parseInt(failTime.toString());
|
||||
}
|
||||
// 10分钟
|
||||
redisUtil.set(key, ++val, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验用户是否有效
|
||||
*/
|
||||
private void checkUserIsEffective(LoginUser loginUser) {
|
||||
//情况1:根据用户信息查询,该用户不存在
|
||||
if (Objects.isNull(loginUser)) {
|
||||
baseCommonService.addLog("用户登录失败,用户不存在!", CommonConstant.LOG_TYPE_1, null);
|
||||
throw new JeecgBootException("该用户不存在,请注册");
|
||||
}
|
||||
//情况2:根据用户信息查询,该用户已注销
|
||||
//update-begin---author:王帅 Date:20200601 for:if条件永远为falsebug------------
|
||||
if (CommonConstant.DEL_FLAG_1.equals(loginUser.getDelFlag())) {
|
||||
//update-end---author:王帅 Date:20200601 for:if条件永远为falsebug------------
|
||||
baseCommonService.addLog("用户登录失败,用户名:" + loginUser.getUsername() + "已注销!", CommonConstant.LOG_TYPE_1, null);
|
||||
throw new JeecgBootException("该用户已注销");
|
||||
}
|
||||
//情况3:根据用户信息查询,该用户已冻结
|
||||
if (CommonConstant.USER_FREEZE.equals(loginUser.getStatus())) {
|
||||
baseCommonService.addLog("用户登录失败,用户名:" + loginUser.getUsername() + "已冻结!", CommonConstant.LOG_TYPE_1, null);
|
||||
throw new JeecgBootException("该用户已冻结");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
package org.jeecg.config.security.app;
|
||||
|
||||
import org.jeecg.config.security.LoginType;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
||||
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationGrantAuthenticationToken;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* APP模式认证专用token类型,方法spring authorization server进行认证流转,配合convert使用
|
||||
* @author EightMonth
|
||||
* @date 2024/1/1
|
||||
*/
|
||||
public class AppGrantAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
|
||||
|
||||
public AppGrantAuthenticationToken(Authentication clientPrincipal, Map<String, Object> additionalParameters) {
|
||||
super(new AuthorizationGrantType(LoginType.APP), clientPrincipal, additionalParameters);
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user