mirror of
https://github.com/dromara/RuoYi-Vue-Plus.git
synced 2025-09-24 07:19:46 +08:00
Compare commits
512 Commits
Author | SHA1 | Date | |
---|---|---|---|
098d3347a0 | |||
463048e017 | |||
79aee1d312 | |||
eb038e91dd | |||
308c22f922 | |||
457e59e61c | |||
a964ccbd10 | |||
0af532f4f1 | |||
4743eb1d3b | |||
23aafe1cfe | |||
3f2499feac | |||
fb97649151 | |||
b33b645ef0 | |||
9318f182b0 | |||
facbb7f28f | |||
4de45ce170 | |||
96d57bd263 | |||
bb4587fe05 | |||
19c83f02aa | |||
0e1fcbfe9c | |||
eda882433a | |||
e6847605cc | |||
5bdffdb368 | |||
0ad52b18b8 | |||
77f44574c0 | |||
ca06a2311d | |||
b8d9af65e2 | |||
bc2b4876b6 | |||
23b70ca0be | |||
44d776a76f | |||
f03c00b2c1 | |||
7f60ba9888 | |||
31569646b0 | |||
3fc37d6362 | |||
6d28072167 | |||
f124fbd6aa | |||
88a4a51956 | |||
4306ea4181 | |||
e19140462d | |||
20cc8a6d6c | |||
a9d7a42c65 | |||
f51e6d81b1 | |||
f119d082cf | |||
ecfaa9ad5c | |||
f32d0266ee | |||
7393a61305 | |||
2b0efd1f93 | |||
b615a3b088 | |||
85403e975f | |||
615ad918ca | |||
b886f3a04b | |||
588a47897a | |||
2869d590e6 | |||
6b14bce25e | |||
5aa346327f | |||
fcf8516f0d | |||
2a340d4d83 | |||
508d7a37e3 | |||
08fece39d8 | |||
857a0b1006 | |||
239d59c864 | |||
7297053dd6 | |||
bd872f624a | |||
86acb14f05 | |||
9825f349ac | |||
19fd562c24 | |||
b6d939a9ff | |||
1619edb8a1 | |||
782821aeb2 | |||
51498958fa | |||
51edb74474 | |||
d5ab2a7557 | |||
ee3525cfb2 | |||
e9bd0858e2 | |||
f46d881866 | |||
ee5e718f83 | |||
e25083aea4 | |||
e74f0ca6f8 | |||
52b0fa9a54 | |||
105c007f03 | |||
0a3d5fd5d4 | |||
ae3c02d4b2 | |||
9e17d07a17 | |||
dcfab4e011 | |||
0b78f9361d | |||
0c4e9dc813 | |||
d894cae073 | |||
84f553a911 | |||
05580deaa9 | |||
aac83bbb91 | |||
249f1f48a6 | |||
bfb92fe667 | |||
640dc43bbe | |||
8859d915b0 | |||
82fdb37c6b | |||
49c18dab63 | |||
f5b8a22bde | |||
b6b0f9c47d | |||
a2a2fa2311 | |||
34690e3e65 | |||
54f58257f9 | |||
58b6c4668f | |||
d0e7eb8409 | |||
77a7a8f30e | |||
08d4493994 | |||
f76738e02b | |||
ab147df2f1 | |||
5444ccc857 | |||
fc89d62f1a | |||
367d739e2d | |||
94467273c5 | |||
d6688a367d | |||
835de64bea | |||
113da3437b | |||
b0b6d01357 | |||
6cc24dc763 | |||
0cb3105cea | |||
00502a4689 | |||
ebb7242b71 | |||
0fbb96c4ac | |||
e942ffed71 | |||
319270bf2b | |||
8b69de0d54 | |||
f929513310 | |||
0d25b82087 | |||
c75857b1ea | |||
6d353869ef | |||
6ba7249a75 | |||
2ee543e2a4 | |||
871dfa9a67 | |||
17fe2d5863 | |||
d5b62a2126 | |||
a4a833f15f | |||
a4fe077a23 | |||
bfa77361b7 | |||
3dff529920 | |||
3681150010 | |||
f0b4fcbdf0 | |||
5c7e8c5381 | |||
a144fa449b | |||
4f9ceb0a80 | |||
12338fc0b4 | |||
6d2cc6e87d | |||
52598e5c5c | |||
903d810edc | |||
475b169952 | |||
ba1f66367b | |||
0b331796e2 | |||
b27f560b33 | |||
59edca8fca | |||
147a90302d | |||
b4b5aedc82 | |||
81293c9368 | |||
7c82b4c370 | |||
045e09f029 | |||
cbd59f84fd | |||
086b206139 | |||
d56e8d79ec | |||
d61459e912 | |||
33880f3e86 | |||
6186881615 | |||
20a3396128 | |||
e5ee98a6aa | |||
8985f1dba6 | |||
5e09884e99 | |||
0cb0a355bb | |||
26445851cc | |||
810691b5df | |||
5d18d02a9c | |||
65421639f1 | |||
a474e9e5d1 | |||
7b9358a4f0 | |||
456620b638 | |||
ff684cad44 | |||
0b4f6dd29b | |||
b4f512f667 | |||
7dda9974f1 | |||
95791254a9 | |||
e0253a4ea8 | |||
cfc2dba275 | |||
867e7bf665 | |||
7c448aed9f | |||
8a388a0d8b | |||
62a2e9de37 | |||
1184274246 | |||
51d66199b1 | |||
e7e988f97a | |||
a17211dc96 | |||
2c1769575c | |||
5d3af1a932 | |||
f2e0ffb2b2 | |||
2e32b748b6 | |||
512b5204bc | |||
44bef2d6d9 | |||
7e2257b224 | |||
0b04ac79d0 | |||
7b02ad3c00 | |||
9b507f06c4 | |||
6ce92e1669 | |||
d443304829 | |||
c84f24fe20 | |||
9175b7a4c1 | |||
1c011fbd7b | |||
56531afd1a | |||
b6e294c137 | |||
0f9936a542 | |||
9855f60f1f | |||
07adf67dfc | |||
125b03adfc | |||
528b65ae04 | |||
55fda94b6a | |||
67ab7a04ad | |||
94797a2d2b | |||
1bd40a0cff | |||
102003a52b | |||
6777ae046e | |||
a32f55a920 | |||
f3cc05e651 | |||
52a53791c8 | |||
e181e340e4 | |||
2cf2cc46f2 | |||
11bfde3dc1 | |||
dd6d4c67ed | |||
f13b9d2764 | |||
50ed9b327f | |||
49f101308f | |||
2154033879 | |||
ba1a540add | |||
ea23e604f9 | |||
7cf9c15984 | |||
a3f43f8ea3 | |||
3a933e6f2b | |||
9a15298e63 | |||
7367457500 | |||
831aec3af9 | |||
5b67b182c3 | |||
5fc0a298a5 | |||
69e3afc770 | |||
45d431f24e | |||
6a3a27026d | |||
0310637b07 | |||
9662d8a2ab | |||
e81d8527c4 | |||
02a8bfb5ae | |||
845e95bd07 | |||
5eea8fda26 | |||
b9133484f0 | |||
ef4beaceb0 | |||
68dff22b77 | |||
0d0ae31d52 | |||
bdcd889df4 | |||
ef57259386 | |||
416ca05be4 | |||
479b17a8c2 | |||
624fd87751 | |||
727df8dd94 | |||
8ae9fc10eb | |||
1ff6502ea9 | |||
594165da6a | |||
c03c72c7d0 | |||
78115e0504 | |||
cb9ed5add0 | |||
4bb416945b | |||
1375a19a46 | |||
125b50b33e | |||
65d25c6f64 | |||
3879fa5df2 | |||
df1cd7e07f | |||
2a9897057e | |||
ea5d657e31 | |||
a36a07ae6f | |||
acaa220a70 | |||
3ffd1e3b41 | |||
14cedccaf3 | |||
041d8399ba | |||
32171508e1 | |||
11c15c47d1 | |||
853fc6678b | |||
d6db49e621 | |||
405a98c8f3 | |||
cb296ef2cd | |||
bebd9e7a54 | |||
ae0bd608a9 | |||
31d445c6a1 | |||
f7f2c1730d | |||
2782c369c9 | |||
659db611ea | |||
9e5f7be1c5 | |||
bd4f7ff3aa | |||
155aa3ba5c | |||
31cd1258f8 | |||
18e3b424d6 | |||
d403688a0c | |||
17bf0c0623 | |||
b296486892 | |||
64dccb192c | |||
c15a27709d | |||
33de9f9337 | |||
aa0ebd45b9 | |||
2583632883 | |||
2472d531f5 | |||
fb43fb9af7 | |||
56a640a5c6 | |||
ffa702935c | |||
8482203c3b | |||
eb06eb7266 | |||
ea64f505af | |||
748411c8db | |||
90aad8ed9a | |||
6cc2da03e0 | |||
e1b94d6a28 | |||
1abd2e7d7e | |||
8352f18b3a | |||
9ff0b09d4d | |||
2e08825da8 | |||
cf81f641bd | |||
07891edd16 | |||
6ea777d584 | |||
040ecb2532 | |||
f5f8fa2471 | |||
c728116788 | |||
6438f80526 | |||
0b43cf4b1c | |||
8677f78a56 | |||
54606b05c0 | |||
6ad126cf64 | |||
654b84f4f2 | |||
9ddf0c6e76 | |||
7e3984e341 | |||
af77657a86 | |||
eb03afef41 | |||
1da98c8a82 | |||
a73c65eae9 | |||
5dc14666cc | |||
dd219ad295 | |||
4e871e02e6 | |||
cbc1030043 | |||
061c6e822d | |||
17d259dc52 | |||
0a319b31c8 | |||
8b1e34d800 | |||
e548a05cf0 | |||
089b089fce | |||
aa3e8c9986 | |||
497176d9d1 | |||
4e52369542 | |||
ba37178ebb | |||
343de424ab | |||
2d790f3c4d | |||
651b2e140b | |||
c859fa4c38 | |||
26e149a357 | |||
2ed765d204 | |||
8e091d712f | |||
812d9eb0e8 | |||
ed43774129 | |||
945202652a | |||
6954fdec0a | |||
148ad7a3d1 | |||
b209030f45 | |||
425dbd5604 | |||
4cf14ef5ac | |||
f429065ab4 | |||
9d35575051 | |||
b5ad057f06 | |||
ab2af1669c | |||
11615685b7 | |||
b017cb7b54 | |||
960bea96b4 | |||
979cfc9af0 | |||
ed8202891f | |||
6f5a368c86 | |||
c6c615308c | |||
105dfd96c1 | |||
65c51124f8 | |||
6309af9db8 | |||
5360ec6ec3 | |||
7c7cfc8c39 | |||
f3207649ff | |||
6086db3b0b | |||
fd4c91301e | |||
581d7144d6 | |||
a458c7056d | |||
7b8822f664 | |||
c8cd4e2d01 | |||
abe6b05c5c | |||
1b6b74c67b | |||
df5cbaaea8 | |||
9a14e90642 | |||
fb337f57b8 | |||
9f09083247 | |||
74e55720d7 | |||
e30e4fe447 | |||
5d38f4bb77 | |||
dbef39a7a6 | |||
f66b196046 | |||
bb59cb204d | |||
731bcc7e93 | |||
b3dbb19afc | |||
b4e1e32d20 | |||
c9cceb9e2d | |||
fe13fd899c | |||
81b2999dc4 | |||
598ece677d | |||
2142fc8876 | |||
67d96a63f1 | |||
efc46c17b2 | |||
acae5616f8 | |||
672320f38b | |||
f3cd3bb63f | |||
ea98435acd | |||
d545f8ddda | |||
d4685e5f95 | |||
e7907a4664 | |||
60862ffc3e | |||
154ee06d70 | |||
22d87c7c9d | |||
e8f8b41f8b | |||
079f90766f | |||
acc7f3dfe5 | |||
234d8989d7 | |||
acb6aeffd1 | |||
b8135557e5 | |||
d54772815b | |||
5f7f8a31e9 | |||
56798131b3 | |||
3b932cfa7b | |||
2d27100b5d | |||
5e1bd0d679 | |||
d954cf01f3 | |||
e655da45e2 | |||
c7246b3a84 | |||
bef6bb7004 | |||
ef8c567ab6 | |||
0fd001f229 | |||
55ce0e34c9 | |||
70bf1a48d0 | |||
7b4e8324a9 | |||
3913bf68c6 | |||
ea48115190 | |||
9fdd4d0fba | |||
bec97982a6 | |||
3a4990e3d4 | |||
995ddf6d98 | |||
1997a607ba | |||
3d406c2d07 | |||
591331b70c | |||
4273f2db34 | |||
cb913a9adc | |||
7c5898ddf6 | |||
a07e5d7833 | |||
9766f61cf8 | |||
58657e53bf | |||
391c92a6c6 | |||
65480ebe96 | |||
5e5fe434e2 | |||
b628c9b027 | |||
928e418f3f | |||
e5089dc126 | |||
6cff0375fb | |||
afa8a1f298 | |||
8c3462079b | |||
f1eeb08d90 | |||
cad250f02a | |||
13e60a6048 | |||
e115f5f2f4 | |||
348bd00fa3 | |||
2417517aee | |||
05880981f8 | |||
d4f8b93fe3 | |||
7f64fa7037 | |||
eca2be1a2e | |||
3d03a5b319 | |||
59385fc08d | |||
fcabba1087 | |||
2ac24d62a0 | |||
f0b9c21169 | |||
46e46e60a6 | |||
606290e185 | |||
845b57e931 | |||
e7ca94bab1 | |||
a7bb4ee50c | |||
339f85741f | |||
63374ee876 | |||
e77ede91b9 | |||
30d7651322 | |||
f101d70523 | |||
5cf84980e8 | |||
3035eb4a54 | |||
b4710edc18 | |||
3e2a6492f4 | |||
e11b1bb2ec | |||
57318cc55d | |||
8d3d93e537 | |||
df5edb67f0 | |||
12b40f2bbe | |||
8660db3bb3 | |||
649099a841 | |||
b4f91a9bbd | |||
f72ce39c13 | |||
f5420f1f07 | |||
2cf7c45ac5 | |||
4ceb79afa3 | |||
84671e5972 | |||
9c84530593 | |||
363af040d6 | |||
2ea30af4c4 | |||
6ccef6c1d0 | |||
2a9624d404 | |||
a1f404d548 | |||
c95a197028 | |||
82c62091aa |
@ -1,49 +0,0 @@
|
||||
### 使用版本(未按照模板填写直接删除)
|
||||
|
||||
- jdk版本(带上尾号): 例如 1.8.0_202
|
||||
- 框架版本(项目启动时输出的版本号): 例如 4.4.0
|
||||
- 其他依赖版本(你觉得有必要的):
|
||||
|
||||
### 问题前提
|
||||
|
||||
> 功能不好用 不会用 是否已经看过项目文档
|
||||
> 项目运行报错 是否已经拿着报错信息去百度 常见报错百度百度足以
|
||||
> 是否搜索过其他issue 一些已经解决的问题 会在issue内留下解决方法
|
||||
> 无法线上解决或者与框架无关的问题的欢迎加VIP群跟作者一对一谈
|
||||
|
||||
### 异常模块
|
||||
|
||||
> 此报错都涉及到那些系统模块
|
||||
|
||||
例如 ruoyi-system ruoyi-auth 等等
|
||||
|
||||
### 问题描述
|
||||
|
||||
> 越详细越容易直击问题所在
|
||||
|
||||
已知: XXX功能不好用 或 XXX数据不正常 等等
|
||||
|
||||
### 希望结果
|
||||
|
||||
> 想知道你觉得怎么样是正常或者合理的
|
||||
|
||||
希望功能可以有XXX结果 或者 XXX现象
|
||||
|
||||
### 重现步骤
|
||||
|
||||
> 作者并不知道这个问题是如何出现的
|
||||
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
|
||||
### 相关代码与报错信息(请勿发混乱格式)
|
||||
|
||||
> 代码可按照如下形式提供或者截图均可 越详细越好
|
||||
> 大多数问题都是 代码编写错误问题 逻辑问题 或者用法错误等问题
|
||||
|
||||
```java
|
||||
public class XXX {
|
||||
|
||||
}
|
||||
```
|
@ -9,8 +9,9 @@ body:
|
||||
label: 版本
|
||||
description: 你当前正在使用我们软件的哪个版本(pom文件内的版本号)?
|
||||
value: |
|
||||
jdk版本(带上尾号): 例如 17.0.8
|
||||
框架版本(项目启动时输出的版本号): 例如 5.1.1
|
||||
注意: 未填写版本号不予处理直接关闭或删除
|
||||
jdk版本(带上尾号):
|
||||
框架版本(项目启动时输出的版本号):
|
||||
其他依赖版本(你觉得有必要的):
|
||||
validations:
|
||||
required: true
|
||||
|
@ -2,7 +2,7 @@
|
||||
<configuration default="false" name="ruoyi-monitor-admin" type="docker-deploy" factoryName="dockerfile" server-name="Docker">
|
||||
<deployment type="dockerfile">
|
||||
<settings>
|
||||
<option name="imageTag" value="ruoyi/ruoyi-monitor-admin:5.1.2" />
|
||||
<option name="imageTag" value="ruoyi/ruoyi-monitor-admin:5.2.2" />
|
||||
<option name="buildOnly" value="true" />
|
||||
<option name="sourceFilePath" value="ruoyi-extend/ruoyi-monitor-admin/Dockerfile" />
|
||||
</settings>
|
||||
|
@ -1,12 +1,12 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="ruoyi-server" type="docker-deploy" factoryName="dockerfile" server-name="Docker">
|
||||
<configuration default="false" name="ruoyi-server" type="docker-deploy" factoryName="dockerfile" server-name="演示机">
|
||||
<deployment type="dockerfile">
|
||||
<settings>
|
||||
<option name="imageTag" value="ruoyi/ruoyi-server:5.1.2" />
|
||||
<option name="imageTag" value="ruoyi/ruoyi-server:5.2.2" />
|
||||
<option name="buildOnly" value="true" />
|
||||
<option name="sourceFilePath" value="ruoyi-admin/Dockerfile" />
|
||||
</settings>
|
||||
</deployment>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
</component>
|
@ -1,10 +1,10 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="ruoyi-powerjob-server" type="docker-deploy" factoryName="dockerfile" server-name="Docker">
|
||||
<configuration default="false" name="ruoyi-snailjob-server" type="docker-deploy" factoryName="dockerfile" server-name="Docker">
|
||||
<deployment type="dockerfile">
|
||||
<settings>
|
||||
<option name="imageTag" value="ruoyi/ruoyi-powerjob-server:5.1.2" />
|
||||
<option name="imageTag" value="ruoyi/ruoyi-snailjob-server:5.2.2" />
|
||||
<option name="buildOnly" value="true" />
|
||||
<option name="sourceFilePath" value="ruoyi-extend/ruoyi-powerjob-server/Dockerfile" />
|
||||
<option name="sourceFilePath" value="ruoyi-extend/ruoyi-snailjob-server/Dockerfile" />
|
||||
</settings>
|
||||
</deployment>
|
||||
<method v="2" />
|
41
README.md
41
README.md
@ -9,8 +9,8 @@
|
||||
[](https://gitee.com/dromara/RuoYi-Vue-Plus/blob/master/LICENSE)
|
||||
[](https://www.jetbrains.com/?from=RuoYi-Vue-Plus)
|
||||
<br>
|
||||
[](https://gitee.com/dromara/RuoYi-Vue-Plus)
|
||||
[]()
|
||||
[](https://gitee.com/dromara/RuoYi-Vue-Plus)
|
||||
[]()
|
||||
[]()
|
||||
[]()
|
||||
|
||||
@ -23,7 +23,15 @@
|
||||
|
||||
> 前端项目地址: [plus-ui](https://gitee.com/JavaLionLi/plus-ui)
|
||||
|
||||
> 文档地址: [plus-doc](https://plus-doc.dromara.org) - [plus-doc(国内备用)](https://dromara.gitee.io/plus-doc)
|
||||
> 文档地址: [plus-doc](https://plus-doc.dromara.org)
|
||||
|
||||
## 赞助商
|
||||
|
||||
MaxKey 业界领先单点登录产品 - https://gitee.com/dromara/MaxKey <br>
|
||||
CCFlow 驰聘低代码-流程-表单 - https://gitee.com/opencc/RuoYi-JFlow <br>
|
||||
数舵科技 软件定制开发APP小程序等 - http://www.shuduokeji.com/ <br>
|
||||
引迈信息 软件开发平台 - https://www.jnpfsoft.com/index.html?from=plus-doc <br>
|
||||
[如何成为赞助商 加群联系作者详谈](https://plus-doc.dromara.org/#/common/add_group)
|
||||
|
||||
# 本框架与RuoYi的功能差异
|
||||
|
||||
@ -48,15 +56,16 @@
|
||||
| 数据加解密 | 采用 注解 + mybatis 拦截器 对存取数据期间自动加解密<br/>支持多种策略 如BASE64、AES、RSA、SM2、SM4等 | 无 |
|
||||
| 接口传输加密 | 采用 动态 AES + RSA 加密请求 body 每一次请求秘钥都不同大幅度降低可破解性 | 无 |
|
||||
| 数据翻译 | 采用 注解 + jackson 序列化期间动态修改数据 数据进行翻译<br/>支持多种模式: `映射翻译` `直接翻译` `其他扩展条件翻译` 接口化两步即可完成自定义扩展 内置多种翻译实现 | 无 |
|
||||
| 多数据源框架 | 采用 dynamic-datasource 支持世面大部分数据库<br/>通过yml配置即可动态管理异构不同种类的数据库 也可通过前端页面添加数据源<br/>支持spel表达式从请求头参数等条件切换数据源 | 基于 druid 手动编写代码配置数据源 配置繁琐 支持性差 |
|
||||
| 多数据源框架 | 采用 dynamic-datasource 支持市面大部分数据库<br/>通过yml配置即可动态管理异构不同种类的数据库 也可通过前端页面添加数据源<br/>支持spel表达式从请求头参数等条件切换数据源 | 基于 druid 手动编写代码配置数据源 配置繁琐 支持性差 |
|
||||
| 多数据源事务 | 采用 dynamic-datasource 支持多数据源不同种类的数据库事务回滚 | 不支持 |
|
||||
| 数据库连接池 | 采用 HikariCP Spring官方内置连接池 配置简单 以性能与稳定性闻名天下 | 采用 druid bug众多 社区维护差 活跃度低 配置众多繁琐性能一般 |
|
||||
| 数据库主键 | 采用 雪花ID 基于时间戳的 有序增长 唯一ID 再也不用为分库分表 数据合并主键冲突重复而发愁 | 采用 数据库自增ID 支持数据量有限 不支持多数据源主键唯一 |
|
||||
| WebSocket协议 | 基于 Spring 封装的 WebSocket 协议 扩展了Token鉴权与分布式会话同步 不再只是基于单机的废物 | 无 |
|
||||
| SSE推送 | 采用 Spring SSE 实现 扩展了Token鉴权与分布式会话同步 | 无 |
|
||||
| 序列化 | 采用 Jackson Spring官方内置序列化 靠谱!!! | 采用 fastjson bugjson 远近闻名 |
|
||||
| 分布式幂等 | 参考美团GTIS防重系统简化实现(细节可看文档) | 手动编写注解基于aop实现 |
|
||||
| 分布式锁 | 采用 Lock4j 底层基于 Redisson | 无 |
|
||||
| 分布式任务调度 | 采用 PowerJob 天生支持分布式 统一的管理中心 | 采用 Quartz 基于数据库锁性能差 集群需要做很多配置与改造 |
|
||||
| 分布式任务调度 | 采用 SnailJob 天生支持分布式 统一的管理中心 支持多种数据库 支持分片重试DAG任务流等 | 采用 Quartz 基于数据库锁性能差 集群需要做很多配置与改造 |
|
||||
| 文件存储 | 采用 Minio 分布式文件存储 天生支持多机、多硬盘、多分片、多副本存储<br/>支持权限管理 安全可靠 文件可加密存储 | 采用 本机文件存储 文件裸漏 易丢失泄漏 不支持集群有单点效应 |
|
||||
| 云存储 | 采用 AWS S3 协议客户端 支持 七牛、阿里、腾讯 等一切支持S3协议的厂家 | 不支持 |
|
||||
| 短信 | 采用 sms4j 短信融合包 支持数十种短信厂家 只需在yml配置好厂家密钥即可使用 可多厂家共用 | 不支持 |
|
||||
@ -64,6 +73,7 @@
|
||||
| 接口文档 | 采用 SpringDoc、javadoc 无注解零入侵基于java注释<br/>只需把注释写好 无需再写一大堆的文档注解了 | 采用 Springfox 已停止维护 需要编写大量的注解来支持文档生成 |
|
||||
| 校验框架 | 采用 Validation 支持注解与工具类校验 注解支持国际化 | 仅支持注解 且注解不支持国际化 |
|
||||
| Excel框架 | 采用 Alibaba EasyExcel 基于插件化<br/>框架对其增加了很多功能 例如 自动合并相同内容 自动排列布局 字典翻译等 | 基于 POI 手写实现 功能有限 复杂 扩展性差 |
|
||||
| 工作流支持 | 支持各种复杂审批 转办 委派 加减签 会签 或签 票签 等功能 | 无 |
|
||||
| 工具类框架 | 采用 Hutool、Lombok 上百种工具覆盖90%的使用需求 基于注解自动生成 get set 等简化框架大量代码 | 手写工具稳定性差易出问题 工具数量有限 代码臃肿需自己手写 get set 等 |
|
||||
| 监控框架 | 采用 SpringBoot-Admin 基于SpringBoot官方 actuator 探针机制<br/>实时监控服务状态 框架还为其扩展了在线日志查看监控 | 无 |
|
||||
| 链路追踪 | 采用 Apache SkyWalking 还在为请求不知道去哪了 到哪出了问题而烦恼吗<br/>用了它即可实时查看请求经过的每一处每一个节点 | 无 |
|
||||
@ -115,13 +125,12 @@
|
||||
>
|
||||
>[部署项目 必看](https://plus-doc.dromara.org/#/ruoyi-vue-plus/quickstart/deploy)
|
||||
>>[https://plus-doc.dromara.org/#/ruoyi-vue-plus/quickstart/deploy](https://plus-doc.dromara.org/#/ruoyi-vue-plus/quickstart/deploy)
|
||||
>
|
||||
>
|
||||
>[如何加群](https://plus-doc.dromara.org/#/common/add_group)
|
||||
>>[https://plus-doc.dromara.org/#/common/add_group](https://plus-doc.dromara.org/#/common/add_group)
|
||||
>
|
||||
>[参考文档 Wiki](https://plus-doc.dromara.org)
|
||||
>>[https://plus-doc.dromara.org](https://plus-doc.dromara.org)
|
||||
>
|
||||
>[参考文档(国内备份)](https://dromara.gitee.io/plus-doc)
|
||||
>>[https://dromara.gitee.io/plus-doc](https://dromara.gitee.io/plus-doc)
|
||||
|
||||
|
||||
## 软件架构图
|
||||
|
||||
@ -131,18 +140,6 @@
|
||||
|
||||
[参与贡献的方式 https://plus-doc.dromara.org/#/common/contribution](https://plus-doc.dromara.org/#/common/contribution)
|
||||
|
||||
### 其他
|
||||
|
||||
* 定期同步升级 RuoYi-Vue 有用的更新
|
||||
* GitHub 地址 [RuoYi-Vue-Plus](https://github.com/dromara/RuoYi-Vue-Plus)
|
||||
* 微服务 分支 [RuoYi-Cloud-Plus](https://gitee.com/JavaLionLi/RuoYi-Cloud-Plus)
|
||||
* 前端项目 地址 [plus-ui](https://gitee.com/JavaLionLi/plus-ui)
|
||||
* 用户扩展项目 [扩展项目列表](https://plus-doc.dromara.org/#/ruoyi-vue-plus/extend-project/list)
|
||||
|
||||
## 加群与捐献
|
||||
>[加群与捐献](https://plus-doc.dromara.org/#/ruoyi-vue-plus/other/group_chat)
|
||||
>>[https://plus-doc.dromara.org/#/ruoyi-vue-plus/other/group_chat](https://plus-doc.dromara.org/#/ruoyi-vue-plus/other/group_chat)
|
||||
|
||||
## 捐献作者
|
||||
作者为兼职做开源,平时还需要工作,如果帮到了您可以请作者吃个盒饭
|
||||
<img src="https://foruda.gitee.com/images/1678975784848381069/d8661ed9_1766278.png" width="300px" height="450px" />
|
||||
|
143
pom.xml
143
pom.xml
@ -13,42 +13,46 @@
|
||||
<description>RuoYi-Vue-Plus多租户管理系统</description>
|
||||
|
||||
<properties>
|
||||
<revision>5.1.2</revision>
|
||||
<spring-boot.version>3.1.7</spring-boot.version>
|
||||
<revision>5.2.2</revision>
|
||||
<spring-boot.version>3.2.9</spring-boot.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>17</java.version>
|
||||
<spring-boot.mybatis>3.0.3</spring-boot.mybatis>
|
||||
<springdoc.version>2.2.0</springdoc.version>
|
||||
<mybatis.version>3.5.16</mybatis.version>
|
||||
<springdoc.version>2.6.0</springdoc.version>
|
||||
<therapi-javadoc.version>0.15.0</therapi-javadoc.version>
|
||||
<poi.version>5.2.3</poi.version>
|
||||
<easyexcel.version>3.3.3</easyexcel.version>
|
||||
<easyexcel.version>4.0.2</easyexcel.version>
|
||||
<velocity.version>2.3</velocity.version>
|
||||
<satoken.version>1.37.0</satoken.version>
|
||||
<mybatis-plus.version>3.5.4</mybatis-plus.version>
|
||||
<satoken.version>1.38.0</satoken.version>
|
||||
<mybatis-plus.version>3.5.7</mybatis-plus.version>
|
||||
<p6spy.version>3.9.1</p6spy.version>
|
||||
<hutool.version>5.8.22</hutool.version>
|
||||
<hutool.version>5.8.31</hutool.version>
|
||||
<okhttp.version>4.10.0</okhttp.version>
|
||||
<spring-boot-admin.version>3.1.8</spring-boot-admin.version>
|
||||
<redisson.version>3.24.3</redisson.version>
|
||||
<lock4j.version>2.2.5</lock4j.version>
|
||||
<dynamic-ds.version>4.2.0</dynamic-ds.version>
|
||||
<alibaba-ttl.version>2.14.4</alibaba-ttl.version>
|
||||
<powerjob.version>4.3.6</powerjob.version>
|
||||
<mapstruct-plus.version>1.3.5</mapstruct-plus.version>
|
||||
<spring-boot-admin.version>3.2.3</spring-boot-admin.version>
|
||||
<redisson.version>3.34.1</redisson.version>
|
||||
<lock4j.version>2.2.7</lock4j.version>
|
||||
<dynamic-ds.version>4.3.1</dynamic-ds.version>
|
||||
<snailjob.version>1.1.2</snailjob.version>
|
||||
<mapstruct-plus.version>1.4.4</mapstruct-plus.version>
|
||||
<mapstruct-plus.lombok.version>0.2.0</mapstruct-plus.lombok.version>
|
||||
<lombok.version>1.18.30</lombok.version>
|
||||
<lombok.version>1.18.34</lombok.version>
|
||||
<bouncycastle.version>1.76</bouncycastle.version>
|
||||
<justauth.version>1.16.6</justauth.version>
|
||||
<!-- 离线IP地址定位库 -->
|
||||
<ip2region.version>2.7.0</ip2region.version>
|
||||
<undertow.version>2.3.15.Final</undertow.version>
|
||||
|
||||
<!-- OSS 配置 -->
|
||||
<aws-java-sdk-s3.version>1.12.600</aws-java-sdk-s3.version>
|
||||
<aws.sdk.version>2.25.15</aws.sdk.version>
|
||||
<aws.crt.version>0.29.13</aws.crt.version>
|
||||
<!-- SMS 配置 -->
|
||||
<sms4j.version>2.2.0</sms4j.version>
|
||||
<sms4j.version>3.3.2</sms4j.version>
|
||||
<!-- 限制框架中的fastjson版本 -->
|
||||
<fastjson.version>1.2.83</fastjson.version>
|
||||
<!-- 面向运行时的D-ORM依赖 -->
|
||||
<anyline.version>8.7.2-20240808</anyline.version>
|
||||
<!--工作流配置-->
|
||||
<flowable.version>7.0.1</flowable.version>
|
||||
|
||||
<!-- 插件版本 -->
|
||||
<maven-jar-plugin.version>3.2.2</maven-jar-plugin.version>
|
||||
@ -110,6 +114,14 @@
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.flowable</groupId>
|
||||
<artifactId>flowable-bom</artifactId>
|
||||
<version>${flowable.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- JustAuth 的依赖配置-->
|
||||
<dependency>
|
||||
<groupId>me.zhyd.oauth</groupId>
|
||||
@ -144,26 +156,10 @@
|
||||
<version>${lombok.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>${poi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>easyexcel</artifactId>
|
||||
<version>${easyexcel.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml-schemas</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- velocity代码生成使用模板 -->
|
||||
@ -205,14 +201,14 @@
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mybatis.spring.boot</groupId>
|
||||
<artifactId>mybatis-spring-boot-starter</artifactId>
|
||||
<version>${spring-boot.mybatis}</version>
|
||||
<groupId>org.mybatis</groupId>
|
||||
<artifactId>mybatis</artifactId>
|
||||
<version>${mybatis.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
</dependency>
|
||||
|
||||
@ -235,10 +231,23 @@
|
||||
<version>${okhttp.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- AWS SDK for Java 2.x -->
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-s3</artifactId>
|
||||
<version>${aws-java-sdk-s3.version}</version>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>s3</artifactId>
|
||||
<version>${aws.sdk.version}</version>
|
||||
</dependency>
|
||||
<!-- 使用AWS基于 CRT 的 S3 客户端 -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk.crt</groupId>
|
||||
<artifactId>aws-crt</artifactId>
|
||||
<version>${aws.crt.version}</version>
|
||||
</dependency>
|
||||
<!-- 基于 AWS CRT 的 S3 客户端的性能增强的 S3 传输管理器 -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>s3-transfer-manager</artifactId>
|
||||
<version>${aws.sdk.version}</version>
|
||||
</dependency>
|
||||
<!--短信sms4j-->
|
||||
<dependency>
|
||||
@ -271,22 +280,16 @@
|
||||
<version>${lock4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- PowerJob -->
|
||||
<!-- SnailJob Client -->
|
||||
<dependency>
|
||||
<groupId>tech.powerjob</groupId>
|
||||
<artifactId>powerjob-worker-spring-boot-starter</artifactId>
|
||||
<version>${powerjob.version}</version>
|
||||
<groupId>com.aizuda</groupId>
|
||||
<artifactId>snail-job-client-starter</artifactId>
|
||||
<version>${snailjob.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>tech.powerjob</groupId>
|
||||
<artifactId>powerjob-official-processors</artifactId>
|
||||
<version>${powerjob.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>transmittable-thread-local</artifactId>
|
||||
<version>${alibaba-ttl.version}</version>
|
||||
<groupId>com.aizuda</groupId>
|
||||
<artifactId>snail-job-client-job-core</artifactId>
|
||||
<version>${snailjob.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 加密包引入 -->
|
||||
@ -309,6 +312,28 @@
|
||||
<version>${ip2region.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.undertow</groupId>
|
||||
<artifactId>undertow-core</artifactId>
|
||||
<version>${undertow.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.undertow</groupId>
|
||||
<artifactId>undertow-servlet</artifactId>
|
||||
<version>${undertow.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.undertow</groupId>
|
||||
<artifactId>undertow-websockets-jsr</artifactId>
|
||||
<version>${undertow.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<artifactId>commons-compress</artifactId>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<version>1.26.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
@ -339,6 +364,13 @@
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 工作流模块 -->
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-workflow</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
@ -398,6 +430,7 @@
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<argLine>-Dfile.encoding=UTF-8</argLine>
|
||||
<!-- 根据打包环境执行对应的@Tag测试方法 -->
|
||||
<groups>${profiles.active}</groups>
|
||||
<!-- 排除标签 -->
|
||||
|
@ -1,7 +1,9 @@
|
||||
# 贝尔实验室 Spring 官方推荐镜像 JDK下载地址 https://bell-sw.com/pages/downloads/
|
||||
FROM bellsoft/liberica-openjdk-debian:17.0.11-cds
|
||||
#FROM bellsoft/liberica-openjdk-debian:21.0.3-cds
|
||||
#FROM findepi/graalvm:java17-native
|
||||
FROM openjdk:17.0.2-oraclelinux8
|
||||
|
||||
MAINTAINER Lion Li
|
||||
LABEL maintainer="Lion Li"
|
||||
|
||||
RUN mkdir -p /ruoyi/server/logs \
|
||||
/ruoyi/server/temp \
|
||||
@ -19,6 +21,6 @@ ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -Dserver.port=${SERVER_P
|
||||
# 应用名称 如果想区分集群节点监控 改成不同的名称即可
|
||||
#-Dskywalking.agent.service_name=ruoyi-server \
|
||||
#-javaagent:/ruoyi/skywalking/agent/skywalking-agent.jar \
|
||||
-jar app.jar \
|
||||
-XX:+HeapDumpOnOutOfMemoryError -Xlog:gc*,:time,tags,level -XX:+UseZGC ${JAVA_OPTS}
|
||||
-XX:+HeapDumpOnOutOfMemoryError -XX:+UseZGC ${JAVA_OPTS} \
|
||||
-jar app.jar
|
||||
|
||||
|
@ -22,21 +22,28 @@
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
</dependency>
|
||||
<!-- Oracle -->
|
||||
<dependency>
|
||||
<groupId>com.oracle.database.jdbc</groupId>
|
||||
<artifactId>ojdbc8</artifactId>
|
||||
</dependency>
|
||||
<!-- PostgreSql -->
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
</dependency>
|
||||
<!-- SqlServer -->
|
||||
<dependency>
|
||||
<groupId>com.microsoft.sqlserver</groupId>
|
||||
<artifactId>mssql-jdbc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- <!– mp支持的数据库均支持 只需要增加对应的jdbc依赖即可 –>-->
|
||||
<!-- <!– Oracle –>-->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>com.oracle.database.jdbc</groupId>-->
|
||||
<!-- <artifactId>ojdbc8</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
<!-- <!– 兼容oracle低版本 –>-->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>com.oracle.database.nls</groupId>-->
|
||||
<!-- <artifactId>orai18n</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
<!-- <!– PostgreSql –>-->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.postgresql</groupId>-->
|
||||
<!-- <artifactId>postgresql</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
<!-- <!– SqlServer –>-->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>com.microsoft.sqlserver</groupId>-->
|
||||
<!-- <artifactId>mssql-jdbc</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
@ -53,6 +60,11 @@
|
||||
<artifactId>ruoyi-common-ratelimiter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-mail</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-system</artifactId>
|
||||
@ -75,6 +87,12 @@
|
||||
<artifactId>ruoyi-demo</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 工作流模块 -->
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-workflow</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>de.codecentric</groupId>
|
||||
<artifactId>spring-boot-admin-starter-client</artifactId>
|
||||
@ -86,11 +104,6 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>me.zhyd.oauth</groupId>
|
||||
<artifactId>JustAuth</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- skywalking 整合 logback -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.apache.skywalking</groupId>-->
|
||||
|
@ -1,6 +1,8 @@
|
||||
package org.dromara.web.controller;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaIgnore;
|
||||
import cn.dev33.satoken.exception.NotLoginException;
|
||||
import cn.hutool.core.codec.Base64;
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
@ -22,10 +24,11 @@ import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import org.dromara.common.social.config.properties.SocialLoginConfigProperties;
|
||||
import org.dromara.common.social.config.properties.SocialProperties;
|
||||
import org.dromara.common.social.utils.SocialUtils;
|
||||
import org.dromara.common.sse.dto.SseMessageDto;
|
||||
import org.dromara.common.sse.utils.SseMessageUtils;
|
||||
import org.dromara.common.tenant.helper.TenantHelper;
|
||||
import org.dromara.common.websocket.utils.WebSocketUtils;
|
||||
import org.dromara.system.domain.SysClient;
|
||||
import org.dromara.system.domain.bo.SysTenantBo;
|
||||
import org.dromara.system.domain.vo.SysClientVo;
|
||||
import org.dromara.system.domain.vo.SysTenantVo;
|
||||
import org.dromara.system.service.ISysClientService;
|
||||
import org.dromara.system.service.ISysConfigService;
|
||||
@ -41,7 +44,10 @@ import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ -81,7 +87,7 @@ public class AuthController {
|
||||
// 授权类型和客户端id
|
||||
String clientId = loginBody.getClientId();
|
||||
String grantType = loginBody.getGrantType();
|
||||
SysClient client = clientService.queryByClientId(clientId);
|
||||
SysClientVo client = clientService.queryByClientId(clientId);
|
||||
// 查询不到 client 或 client 内不包含 grantType
|
||||
if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
|
||||
log.info("客户端id: {} 认证类型:{} 异常!.", clientId, grantType);
|
||||
@ -96,8 +102,11 @@ public class AuthController {
|
||||
|
||||
Long userId = LoginHelper.getUserId();
|
||||
scheduledExecutorService.schedule(() -> {
|
||||
WebSocketUtils.sendMessage(userId, "欢迎登录RuoYi-Vue-Plus后台管理系统");
|
||||
}, 3, TimeUnit.SECONDS);
|
||||
SseMessageDto dto = new SseMessageDto();
|
||||
dto.setMessage("欢迎登录RuoYi-Vue-Plus后台管理系统");
|
||||
dto.setUserIds(List.of(userId));
|
||||
SseMessageUtils.publishMessage(dto);
|
||||
}, 5, TimeUnit.SECONDS);
|
||||
return R.ok(loginVo);
|
||||
}
|
||||
|
||||
@ -108,13 +117,18 @@ public class AuthController {
|
||||
* @return 结果
|
||||
*/
|
||||
@GetMapping("/binding/{source}")
|
||||
public R<String> authBinding(@PathVariable("source") String source) {
|
||||
public R<String> authBinding(@PathVariable("source") String source,
|
||||
@RequestParam String tenantId, @RequestParam String domain) {
|
||||
SocialLoginConfigProperties obj = socialProperties.getType().get(source);
|
||||
if (ObjectUtil.isNull(obj)) {
|
||||
return R.fail(source + "平台账号暂不支持");
|
||||
}
|
||||
AuthRequest authRequest = SocialUtils.getAuthRequest(source, socialProperties);
|
||||
String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("tenantId", tenantId);
|
||||
map.put("domain", domain);
|
||||
map.put("state", AuthStateUtils.createState());
|
||||
String authorizeUrl = authRequest.authorize(Base64.encode(JsonUtils.toJsonString(map), StandardCharsets.UTF_8));
|
||||
return R.ok("操作成功", authorizeUrl);
|
||||
}
|
||||
|
||||
@ -181,8 +195,26 @@ public class AuthController {
|
||||
*/
|
||||
@GetMapping("/tenant/list")
|
||||
public R<LoginTenantVo> tenantList(HttpServletRequest request) throws Exception {
|
||||
// 返回对象
|
||||
LoginTenantVo result = new LoginTenantVo();
|
||||
boolean enable = TenantHelper.isEnable();
|
||||
result.setTenantEnabled(enable);
|
||||
// 如果未开启租户这直接返回
|
||||
if (!enable) {
|
||||
return R.ok(result);
|
||||
}
|
||||
|
||||
List<SysTenantVo> tenantList = tenantService.queryList(new SysTenantBo());
|
||||
List<TenantListVo> voList = MapstructUtils.convert(tenantList, TenantListVo.class);
|
||||
try {
|
||||
// 如果只超管返回所有租户
|
||||
if (LoginHelper.isSuperAdmin()) {
|
||||
result.setVoList(voList);
|
||||
return R.ok(result);
|
||||
}
|
||||
} catch (NotLoginException ignored) {
|
||||
}
|
||||
|
||||
// 获取域名
|
||||
String host;
|
||||
String referer = request.getHeader("referer");
|
||||
@ -195,11 +227,8 @@ public class AuthController {
|
||||
// 根据域名进行筛选
|
||||
List<TenantListVo> list = StreamUtils.filter(voList, vo ->
|
||||
StringUtils.equals(vo.getDomain(), host));
|
||||
// 返回对象
|
||||
LoginTenantVo vo = new LoginTenantVo();
|
||||
vo.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
|
||||
vo.setTenantEnabled(TenantHelper.isEnable());
|
||||
return R.ok(vo);
|
||||
result.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
|
||||
return R.ok(result);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -5,6 +5,9 @@ import cn.hutool.captcha.AbstractCaptcha;
|
||||
import cn.hutool.captcha.generator.CodeGenerator;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.common.core.constant.Constants;
|
||||
import org.dromara.common.core.constant.GlobalConstants;
|
||||
import org.dromara.common.core.domain.R;
|
||||
@ -21,11 +24,7 @@ import org.dromara.common.web.enums.CaptchaType;
|
||||
import org.dromara.sms4j.api.SmsBlend;
|
||||
import org.dromara.sms4j.api.entity.SmsResponse;
|
||||
import org.dromara.sms4j.core.factory.SmsFactory;
|
||||
import org.dromara.sms4j.provider.enumerate.SupplierType;
|
||||
import org.dromara.web.domain.vo.CaptchaVo;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.expression.Expression;
|
||||
import org.springframework.expression.ExpressionParser;
|
||||
import org.springframework.expression.spel.standard.SpelExpressionParser;
|
||||
@ -66,11 +65,11 @@ public class CaptchaController {
|
||||
String templateId = "";
|
||||
LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
|
||||
map.put("code", code);
|
||||
SmsBlend smsBlend = SmsFactory.createSmsBlend(SupplierType.ALIBABA);
|
||||
SmsBlend smsBlend = SmsFactory.getSmsBlend("config1");
|
||||
SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, templateId, map);
|
||||
if (!"OK".equals(smsResponse.getCode())) {
|
||||
if (!smsResponse.isSuccess()) {
|
||||
log.error("验证码短信发送异常 => {}", smsResponse);
|
||||
return R.fail(smsResponse.getMessage());
|
||||
return R.fail(smsResponse.getData().toString());
|
||||
}
|
||||
return R.ok();
|
||||
}
|
||||
@ -121,6 +120,7 @@ public class CaptchaController {
|
||||
AbstractCaptcha captcha = SpringUtils.getBean(captchaProperties.getCategory().getClazz());
|
||||
captcha.setGenerator(codeGenerator);
|
||||
captcha.createCode();
|
||||
// 如果是数学验证码,使用SpEL表达式处理验证码结果
|
||||
String code = captcha.getCode();
|
||||
if (isMath) {
|
||||
ExpressionParser parser = new SpelExpressionParser();
|
||||
|
@ -13,10 +13,19 @@ import lombok.Data;
|
||||
@AutoMapper(target = SysTenantVo.class)
|
||||
public class TenantListVo {
|
||||
|
||||
/**
|
||||
* 租户编号
|
||||
*/
|
||||
private String tenantId;
|
||||
|
||||
/**
|
||||
* 企业名称
|
||||
*/
|
||||
private String companyName;
|
||||
|
||||
/**
|
||||
* 域名
|
||||
*/
|
||||
private String domain;
|
||||
|
||||
}
|
||||
|
@ -3,6 +3,8 @@ package org.dromara.web.listener;
|
||||
import cn.dev33.satoken.config.SaTokenConfig;
|
||||
import cn.dev33.satoken.listener.SaTokenListener;
|
||||
import cn.dev33.satoken.stp.SaLoginModel;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.http.useragent.UserAgent;
|
||||
import cn.hutool.http.useragent.UserAgentUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@ -10,7 +12,6 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.common.core.constant.CacheConstants;
|
||||
import org.dromara.common.core.constant.Constants;
|
||||
import org.dromara.common.core.domain.dto.UserOnlineDTO;
|
||||
import org.dromara.common.core.domain.model.LoginUser;
|
||||
import org.dromara.common.core.utils.MessageUtils;
|
||||
import org.dromara.common.core.utils.ServletUtils;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
@ -18,6 +19,7 @@ import org.dromara.common.core.utils.ip.AddressUtils;
|
||||
import org.dromara.common.log.event.LogininforEvent;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import org.dromara.common.tenant.helper.TenantHelper;
|
||||
import org.dromara.web.service.SysLoginService;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@ -43,7 +45,6 @@ public class UserActionListener implements SaTokenListener {
|
||||
public void doLogin(String loginType, Object loginId, String tokenValue, SaLoginModel loginModel) {
|
||||
UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
|
||||
String ip = ServletUtils.getClientIP();
|
||||
LoginUser user = LoginHelper.getLoginUser();
|
||||
UserOnlineDTO dto = new UserOnlineDTO();
|
||||
dto.setIpaddr(ip);
|
||||
dto.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
|
||||
@ -51,25 +52,29 @@ public class UserActionListener implements SaTokenListener {
|
||||
dto.setOs(userAgent.getOs().getName());
|
||||
dto.setLoginTime(System.currentTimeMillis());
|
||||
dto.setTokenId(tokenValue);
|
||||
dto.setUserName(user.getUsername());
|
||||
dto.setClientKey(user.getClientKey());
|
||||
dto.setDeviceType(user.getDeviceType());
|
||||
dto.setDeptName(user.getDeptName());
|
||||
if(tokenConfig.getTimeout() == -1) {
|
||||
RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto);
|
||||
} else {
|
||||
RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto, Duration.ofSeconds(tokenConfig.getTimeout()));
|
||||
}
|
||||
String username = (String) loginModel.getExtra(LoginHelper.USER_NAME_KEY);
|
||||
String tenantId = (String) loginModel.getExtra(LoginHelper.TENANT_KEY);
|
||||
dto.setUserName(username);
|
||||
dto.setClientKey((String) loginModel.getExtra(LoginHelper.CLIENT_KEY));
|
||||
dto.setDeviceType(loginModel.getDevice());
|
||||
dto.setDeptName((String) loginModel.getExtra(LoginHelper.DEPT_NAME_KEY));
|
||||
TenantHelper.dynamic(tenantId, () -> {
|
||||
if(tokenConfig.getTimeout() == -1) {
|
||||
RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto);
|
||||
} else {
|
||||
RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto, Duration.ofSeconds(tokenConfig.getTimeout()));
|
||||
}
|
||||
});
|
||||
// 记录登录日志
|
||||
LogininforEvent logininforEvent = new LogininforEvent();
|
||||
logininforEvent.setTenantId(user.getTenantId());
|
||||
logininforEvent.setUsername(user.getUsername());
|
||||
logininforEvent.setTenantId(tenantId);
|
||||
logininforEvent.setUsername(username);
|
||||
logininforEvent.setStatus(Constants.LOGIN_SUCCESS);
|
||||
logininforEvent.setMessage(MessageUtils.message("user.login.success"));
|
||||
logininforEvent.setRequest(ServletUtils.getRequest());
|
||||
SpringUtils.context().publishEvent(logininforEvent);
|
||||
// 更新登录信息
|
||||
loginService.recordLoginInfo(user.getUserId(), ip);
|
||||
loginService.recordLoginInfo((Long) loginModel.getExtra(LoginHelper.USER_KEY), ip);
|
||||
log.info("user doLogin, userId:{}, token:{}", loginId, tokenValue);
|
||||
}
|
||||
|
||||
@ -78,7 +83,10 @@ public class UserActionListener implements SaTokenListener {
|
||||
*/
|
||||
@Override
|
||||
public void doLogout(String loginType, Object loginId, String tokenValue) {
|
||||
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
|
||||
String tenantId = Convert.toStr(StpUtil.getExtra(tokenValue, LoginHelper.TENANT_KEY));
|
||||
TenantHelper.dynamic(tenantId, () -> {
|
||||
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
|
||||
});
|
||||
log.info("user doLogout, userId:{}, token:{}", loginId, tokenValue);
|
||||
}
|
||||
|
||||
@ -87,7 +95,10 @@ public class UserActionListener implements SaTokenListener {
|
||||
*/
|
||||
@Override
|
||||
public void doKickout(String loginType, Object loginId, String tokenValue) {
|
||||
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
|
||||
String tenantId = Convert.toStr(StpUtil.getExtra(tokenValue, LoginHelper.TENANT_KEY));
|
||||
TenantHelper.dynamic(tenantId, () -> {
|
||||
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
|
||||
});
|
||||
log.info("user doKickout, userId:{}, token:{}", loginId, tokenValue);
|
||||
}
|
||||
|
||||
@ -96,7 +107,10 @@ public class UserActionListener implements SaTokenListener {
|
||||
*/
|
||||
@Override
|
||||
public void doReplaced(String loginType, Object loginId, String tokenValue) {
|
||||
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
|
||||
String tenantId = Convert.toStr(StpUtil.getExtra(tokenValue, LoginHelper.TENANT_KEY));
|
||||
TenantHelper.dynamic(tenantId, () -> {
|
||||
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
|
||||
});
|
||||
log.info("user doReplaced, userId:{}, token:{}", loginId, tokenValue);
|
||||
}
|
||||
|
||||
|
@ -4,6 +4,7 @@ package org.dromara.web.service;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.dromara.system.domain.SysClient;
|
||||
import org.dromara.system.domain.vo.SysClientVo;
|
||||
import org.dromara.web.domain.vo.LoginVo;
|
||||
|
||||
/**
|
||||
@ -17,8 +18,13 @@ public interface IAuthStrategy {
|
||||
|
||||
/**
|
||||
* 登录
|
||||
*
|
||||
* @param body 登录对象
|
||||
* @param client 授权管理视图对象
|
||||
* @param grantType 授权类型
|
||||
* @return 登录验证信息
|
||||
*/
|
||||
static LoginVo login(String body, SysClient client, String grantType) {
|
||||
static LoginVo login(String body, SysClientVo client, String grantType) {
|
||||
// 授权类型和客户端id
|
||||
String beanName = grantType + BASE_NAME;
|
||||
if (!SpringUtils.containsBean(beanName)) {
|
||||
@ -30,7 +36,11 @@ public interface IAuthStrategy {
|
||||
|
||||
/**
|
||||
* 登录
|
||||
*
|
||||
* @param body 登录对象
|
||||
* @param client 授权管理视图对象
|
||||
* @return 登录验证信息
|
||||
*/
|
||||
LoginVo login(String body, SysClient client);
|
||||
LoginVo login(String body, SysClientVo client);
|
||||
|
||||
}
|
||||
|
@ -4,17 +4,20 @@ import cn.dev33.satoken.exception.NotLoginException;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.lang.Opt;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.lock.annotation.Lock4j;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import me.zhyd.oauth.model.AuthUser;
|
||||
import org.dromara.common.core.constant.CacheConstants;
|
||||
import org.dromara.common.core.constant.Constants;
|
||||
import org.dromara.common.core.constant.GlobalConstants;
|
||||
import org.dromara.common.core.constant.TenantConstants;
|
||||
import org.dromara.common.core.domain.dto.RoleDTO;
|
||||
import org.dromara.common.core.domain.model.LoginUser;
|
||||
import org.dromara.common.core.enums.LoginType;
|
||||
import org.dromara.common.core.enums.TenantStatus;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.exception.user.UserException;
|
||||
import org.dromara.common.core.utils.*;
|
||||
import org.dromara.common.log.event.LogininforEvent;
|
||||
@ -25,13 +28,9 @@ import org.dromara.common.tenant.exception.TenantException;
|
||||
import org.dromara.common.tenant.helper.TenantHelper;
|
||||
import org.dromara.system.domain.SysUser;
|
||||
import org.dromara.system.domain.bo.SysSocialBo;
|
||||
import org.dromara.system.domain.vo.SysSocialVo;
|
||||
import org.dromara.system.domain.vo.SysTenantVo;
|
||||
import org.dromara.system.domain.vo.SysUserVo;
|
||||
import org.dromara.system.domain.vo.*;
|
||||
import org.dromara.system.mapper.SysUserMapper;
|
||||
import org.dromara.system.service.ISysPermissionService;
|
||||
import org.dromara.system.service.ISysSocialService;
|
||||
import org.dromara.system.service.ISysTenantService;
|
||||
import org.dromara.system.service.*;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@ -59,6 +58,8 @@ public class SysLoginService {
|
||||
private final ISysTenantService tenantService;
|
||||
private final ISysPermissionService permissionService;
|
||||
private final ISysSocialService sysSocialService;
|
||||
private final ISysRoleService roleService;
|
||||
private final ISysDeptService deptService;
|
||||
private final SysUserMapper userMapper;
|
||||
|
||||
|
||||
@ -66,20 +67,28 @@ public class SysLoginService {
|
||||
* 绑定第三方用户
|
||||
*
|
||||
* @param authUserData 授权响应实体
|
||||
* @return 统一响应实体
|
||||
*/
|
||||
@Lock4j
|
||||
public void socialRegister(AuthUser authUserData) {
|
||||
String authId = authUserData.getSource() + authUserData.getUuid();
|
||||
// 第三方用户信息
|
||||
SysSocialBo bo = BeanUtil.toBean(authUserData, SysSocialBo.class);
|
||||
BeanUtil.copyProperties(authUserData.getToken(), bo);
|
||||
bo.setUserId(LoginHelper.getUserId());
|
||||
Long userId = LoginHelper.getUserId();
|
||||
bo.setUserId(userId);
|
||||
bo.setAuthId(authId);
|
||||
bo.setOpenId(authUserData.getUuid());
|
||||
bo.setUserName(authUserData.getUsername());
|
||||
bo.setNickName(authUserData.getNickname());
|
||||
List<SysSocialVo> checkList = sysSocialService.selectByAuthId(authId);
|
||||
if (CollUtil.isNotEmpty(checkList)) {
|
||||
throw new ServiceException("此三方账号已经被绑定!");
|
||||
}
|
||||
// 查询是否已经绑定用户
|
||||
List<SysSocialVo> list = sysSocialService.selectByAuthId(authId);
|
||||
SysSocialBo params = new SysSocialBo();
|
||||
params.setUserId(userId);
|
||||
params.setSource(bo.getSource());
|
||||
List<SysSocialVo> list = sysSocialService.queryList(params);
|
||||
if (CollUtil.isEmpty(list)) {
|
||||
// 没有绑定用户, 新增用户信息
|
||||
sysSocialService.insertByBo(bo);
|
||||
@ -87,6 +96,8 @@ public class SysLoginService {
|
||||
// 更新用户信息
|
||||
bo.setId(list.get(0).getId());
|
||||
sysSocialService.updateByBo(bo);
|
||||
// 如果要绑定的平台账号已经被绑定过了 是否抛异常自行决断
|
||||
// throw new ServiceException("此平台账号已经被绑定!");
|
||||
}
|
||||
}
|
||||
|
||||
@ -132,7 +143,6 @@ public class SysLoginService {
|
||||
SpringUtils.context().publishEvent(logininforEvent);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 构建登录用户
|
||||
*/
|
||||
@ -146,9 +156,13 @@ public class SysLoginService {
|
||||
loginUser.setUserType(user.getUserType());
|
||||
loginUser.setMenuPermission(permissionService.getMenuPermission(user.getUserId()));
|
||||
loginUser.setRolePermission(permissionService.getRolePermission(user.getUserId()));
|
||||
loginUser.setDeptName(ObjectUtil.isNull(user.getDept()) ? "" : user.getDept().getDeptName());
|
||||
List<RoleDTO> roles = BeanUtil.copyToList(user.getRoles(), RoleDTO.class);
|
||||
loginUser.setRoles(roles);
|
||||
if (ObjectUtil.isNotNull(user.getDeptId())) {
|
||||
Opt<SysDeptVo> deptOpt = Opt.of(user.getDeptId()).map(deptService::selectDeptById);
|
||||
loginUser.setDeptName(deptOpt.map(SysDeptVo::getDeptName).orElse(StringUtils.EMPTY));
|
||||
loginUser.setDeptCategory(deptOpt.map(SysDeptVo::getDeptCategory).orElse(StringUtils.EMPTY));
|
||||
}
|
||||
List<SysRoleVo> roles = roleService.selectRolesByUserId(user.getUserId());
|
||||
loginUser.setRoles(BeanUtil.copyToList(roles, RoleDTO.class));
|
||||
return loginUser;
|
||||
}
|
||||
|
||||
@ -170,7 +184,7 @@ public class SysLoginService {
|
||||
* 登录校验
|
||||
*/
|
||||
public void checkLogin(LoginType loginType, String tenantId, String username, Supplier<Boolean> supplier) {
|
||||
String errorKey = GlobalConstants.PWD_ERR_CNT_KEY + username;
|
||||
String errorKey = CacheConstants.PWD_ERR_CNT_KEY + username;
|
||||
String loginFail = Constants.LOGIN_FAIL;
|
||||
|
||||
// 获取用户登录错误次数,默认为0 (可自定义限制策略 例如: key + username + ip)
|
||||
|
@ -1,7 +1,6 @@
|
||||
package org.dromara.web.service;
|
||||
|
||||
import cn.dev33.satoken.secure.BCrypt;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.constant.Constants;
|
||||
@ -61,8 +60,7 @@ public class SysRegisterService {
|
||||
|
||||
boolean exist = TenantHelper.dynamic(tenantId, () -> {
|
||||
return userMapper.exists(new LambdaQueryWrapper<SysUser>()
|
||||
.eq(SysUser::getUserName, sysUser.getUserName())
|
||||
.ne(ObjectUtil.isNotNull(sysUser.getUserId()), SysUser::getUserId, sysUser.getUserId()));
|
||||
.eq(SysUser::getUserName, sysUser.getUserName()));
|
||||
});
|
||||
if (exist) {
|
||||
throw new UserException("user.register.save.error", username);
|
||||
@ -82,7 +80,7 @@ public class SysRegisterService {
|
||||
* @param uuid 唯一标识
|
||||
*/
|
||||
public void validateCaptcha(String tenantId, String username, String code, String uuid) {
|
||||
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
|
||||
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.blankToDefault(uuid, "");
|
||||
String captcha = RedisUtils.getCacheObject(verifyKey);
|
||||
RedisUtils.deleteObject(verifyKey);
|
||||
if (captcha == null) {
|
||||
|
@ -21,8 +21,8 @@ import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import org.dromara.common.tenant.helper.TenantHelper;
|
||||
import org.dromara.system.domain.SysClient;
|
||||
import org.dromara.system.domain.SysUser;
|
||||
import org.dromara.system.domain.vo.SysClientVo;
|
||||
import org.dromara.system.domain.vo.SysUserVo;
|
||||
import org.dromara.system.mapper.SysUserMapper;
|
||||
import org.dromara.web.domain.vo.LoginVo;
|
||||
@ -44,19 +44,18 @@ public class EmailAuthStrategy implements IAuthStrategy {
|
||||
private final SysUserMapper userMapper;
|
||||
|
||||
@Override
|
||||
public LoginVo login(String body, SysClient client) {
|
||||
public LoginVo login(String body, SysClientVo client) {
|
||||
EmailLoginBody loginBody = JsonUtils.parseObject(body, EmailLoginBody.class);
|
||||
ValidatorUtils.validate(loginBody);
|
||||
String tenantId = loginBody.getTenantId();
|
||||
String email = loginBody.getEmail();
|
||||
String emailCode = loginBody.getEmailCode();
|
||||
|
||||
// 通过邮箱查找用户
|
||||
SysUserVo user = loadUserByEmail(tenantId, email);
|
||||
|
||||
loginService.checkLogin(LoginType.EMAIL, tenantId, user.getUserName(), () -> !validateEmailCode(tenantId, email, emailCode));
|
||||
// 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
|
||||
LoginUser loginUser = loginService.buildLoginUser(user);
|
||||
LoginUser loginUser = TenantHelper.dynamic(tenantId, () -> {
|
||||
SysUserVo user = loadUserByEmail(email);
|
||||
loginService.checkLogin(LoginType.EMAIL, tenantId, user.getUserName(), () -> !validateEmailCode(tenantId, email, emailCode));
|
||||
// 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
|
||||
return loginService.buildLoginUser(user);
|
||||
});
|
||||
loginUser.setClientKey(client.getClientKey());
|
||||
loginUser.setDeviceType(client.getDeviceType());
|
||||
SaLoginModel model = new SaLoginModel();
|
||||
@ -88,20 +87,16 @@ public class EmailAuthStrategy implements IAuthStrategy {
|
||||
return code.equals(emailCode);
|
||||
}
|
||||
|
||||
private SysUserVo loadUserByEmail(String tenantId, String email) {
|
||||
return TenantHelper.dynamic(tenantId, () -> {
|
||||
SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
|
||||
.select(SysUser::getEmail, SysUser::getStatus)
|
||||
.eq(SysUser::getEmail, email));
|
||||
if (ObjectUtil.isNull(user)) {
|
||||
log.info("登录用户:{} 不存在.", email);
|
||||
throw new UserException("user.not.exists", email);
|
||||
} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
|
||||
log.info("登录用户:{} 已被停用.", email);
|
||||
throw new UserException("user.blocked", email);
|
||||
}
|
||||
return userMapper.selectUserByEmail(email);
|
||||
});
|
||||
private SysUserVo loadUserByEmail(String email) {
|
||||
SysUserVo user = userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getEmail, email));
|
||||
if (ObjectUtil.isNull(user)) {
|
||||
log.info("登录用户:{} 不存在.", email);
|
||||
throw new UserException("user.not.exists", email);
|
||||
} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
|
||||
log.info("登录用户:{} 已被停用.", email);
|
||||
throw new UserException("user.blocked", email);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -24,8 +24,8 @@ import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import org.dromara.common.tenant.helper.TenantHelper;
|
||||
import org.dromara.common.web.config.properties.CaptchaProperties;
|
||||
import org.dromara.system.domain.SysClient;
|
||||
import org.dromara.system.domain.SysUser;
|
||||
import org.dromara.system.domain.vo.SysClientVo;
|
||||
import org.dromara.system.domain.vo.SysUserVo;
|
||||
import org.dromara.system.mapper.SysUserMapper;
|
||||
import org.dromara.web.domain.vo.LoginVo;
|
||||
@ -48,7 +48,7 @@ public class PasswordAuthStrategy implements IAuthStrategy {
|
||||
private final SysUserMapper userMapper;
|
||||
|
||||
@Override
|
||||
public LoginVo login(String body, SysClient client) {
|
||||
public LoginVo login(String body, SysClientVo client) {
|
||||
PasswordLoginBody loginBody = JsonUtils.parseObject(body, PasswordLoginBody.class);
|
||||
ValidatorUtils.validate(loginBody);
|
||||
String tenantId = loginBody.getTenantId();
|
||||
@ -62,11 +62,12 @@ public class PasswordAuthStrategy implements IAuthStrategy {
|
||||
if (captchaEnabled) {
|
||||
validateCaptcha(tenantId, username, code, uuid);
|
||||
}
|
||||
|
||||
SysUserVo user = loadUserByUsername(tenantId, username);
|
||||
loginService.checkLogin(LoginType.PASSWORD, tenantId, username, () -> !BCrypt.checkpw(password, user.getPassword()));
|
||||
// 此处可根据登录用户的数据不同 自行创建 loginUser
|
||||
LoginUser loginUser = loginService.buildLoginUser(user);
|
||||
LoginUser loginUser = TenantHelper.dynamic(tenantId, () -> {
|
||||
SysUserVo user = loadUserByUsername(username);
|
||||
loginService.checkLogin(LoginType.PASSWORD, tenantId, username, () -> !BCrypt.checkpw(password, user.getPassword()));
|
||||
// 此处可根据登录用户的数据不同 自行创建 loginUser
|
||||
return loginService.buildLoginUser(user);
|
||||
});
|
||||
loginUser.setClientKey(client.getClientKey());
|
||||
loginUser.setDeviceType(client.getDeviceType());
|
||||
SaLoginModel model = new SaLoginModel();
|
||||
@ -94,7 +95,7 @@ public class PasswordAuthStrategy implements IAuthStrategy {
|
||||
* @param uuid 唯一标识
|
||||
*/
|
||||
private void validateCaptcha(String tenantId, String username, String code, String uuid) {
|
||||
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
|
||||
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.blankToDefault(uuid, "");
|
||||
String captcha = RedisUtils.getCacheObject(verifyKey);
|
||||
RedisUtils.deleteObject(verifyKey);
|
||||
if (captcha == null) {
|
||||
@ -107,20 +108,16 @@ public class PasswordAuthStrategy implements IAuthStrategy {
|
||||
}
|
||||
}
|
||||
|
||||
private SysUserVo loadUserByUsername(String tenantId, String username) {
|
||||
return TenantHelper.dynamic(tenantId, () -> {
|
||||
SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
|
||||
.select(SysUser::getUserName, SysUser::getStatus)
|
||||
.eq(SysUser::getUserName, username));
|
||||
if (ObjectUtil.isNull(user)) {
|
||||
log.info("登录用户:{} 不存在.", username);
|
||||
throw new UserException("user.not.exists", username);
|
||||
} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
|
||||
log.info("登录用户:{} 已被停用.", username);
|
||||
throw new UserException("user.blocked", username);
|
||||
}
|
||||
return userMapper.selectUserByUserName(username);
|
||||
});
|
||||
private SysUserVo loadUserByUsername(String username) {
|
||||
SysUserVo user = userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, username));
|
||||
if (ObjectUtil.isNull(user)) {
|
||||
log.info("登录用户:{} 不存在.", username);
|
||||
throw new UserException("user.not.exists", username);
|
||||
} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
|
||||
log.info("登录用户:{} 已被停用.", username);
|
||||
throw new UserException("user.blocked", username);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -21,8 +21,8 @@ import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import org.dromara.common.tenant.helper.TenantHelper;
|
||||
import org.dromara.system.domain.SysClient;
|
||||
import org.dromara.system.domain.SysUser;
|
||||
import org.dromara.system.domain.vo.SysClientVo;
|
||||
import org.dromara.system.domain.vo.SysUserVo;
|
||||
import org.dromara.system.mapper.SysUserMapper;
|
||||
import org.dromara.web.domain.vo.LoginVo;
|
||||
@ -44,19 +44,18 @@ public class SmsAuthStrategy implements IAuthStrategy {
|
||||
private final SysUserMapper userMapper;
|
||||
|
||||
@Override
|
||||
public LoginVo login(String body, SysClient client) {
|
||||
public LoginVo login(String body, SysClientVo client) {
|
||||
SmsLoginBody loginBody = JsonUtils.parseObject(body, SmsLoginBody.class);
|
||||
ValidatorUtils.validate(loginBody);
|
||||
String tenantId = loginBody.getTenantId();
|
||||
String phonenumber = loginBody.getPhonenumber();
|
||||
String smsCode = loginBody.getSmsCode();
|
||||
|
||||
// 通过手机号查找用户
|
||||
SysUserVo user = loadUserByPhonenumber(tenantId, phonenumber);
|
||||
|
||||
loginService.checkLogin(LoginType.SMS, tenantId, user.getUserName(), () -> !validateSmsCode(tenantId, phonenumber, smsCode));
|
||||
// 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
|
||||
LoginUser loginUser = loginService.buildLoginUser(user);
|
||||
LoginUser loginUser = TenantHelper.dynamic(tenantId, () -> {
|
||||
SysUserVo user = loadUserByPhonenumber(phonenumber);
|
||||
loginService.checkLogin(LoginType.SMS, tenantId, user.getUserName(), () -> !validateSmsCode(tenantId, phonenumber, smsCode));
|
||||
// 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
|
||||
return loginService.buildLoginUser(user);
|
||||
});
|
||||
loginUser.setClientKey(client.getClientKey());
|
||||
loginUser.setDeviceType(client.getDeviceType());
|
||||
SaLoginModel model = new SaLoginModel();
|
||||
@ -88,20 +87,16 @@ public class SmsAuthStrategy implements IAuthStrategy {
|
||||
return code.equals(smsCode);
|
||||
}
|
||||
|
||||
private SysUserVo loadUserByPhonenumber(String tenantId, String phonenumber) {
|
||||
return TenantHelper.dynamic(tenantId, () -> {
|
||||
SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
|
||||
.select(SysUser::getPhonenumber, SysUser::getStatus)
|
||||
.eq(SysUser::getPhonenumber, phonenumber));
|
||||
if (ObjectUtil.isNull(user)) {
|
||||
log.info("登录用户:{} 不存在.", phonenumber);
|
||||
throw new UserException("user.not.exists", phonenumber);
|
||||
} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
|
||||
log.info("登录用户:{} 已被停用.", phonenumber);
|
||||
throw new UserException("user.blocked", phonenumber);
|
||||
}
|
||||
return userMapper.selectUserByPhonenumber(phonenumber);
|
||||
});
|
||||
private SysUserVo loadUserByPhonenumber(String phonenumber) {
|
||||
SysUserVo user = userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, phonenumber));
|
||||
if (ObjectUtil.isNull(user)) {
|
||||
log.info("登录用户:{} 不存在.", phonenumber);
|
||||
throw new UserException("user.not.exists", phonenumber);
|
||||
} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
|
||||
log.info("登录用户:{} 已被停用.", phonenumber);
|
||||
throw new UserException("user.blocked", phonenumber);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -7,7 +7,6 @@ import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import cn.hutool.http.Method;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import me.zhyd.oauth.model.AuthResponse;
|
||||
@ -17,14 +16,14 @@ import org.dromara.common.core.domain.model.SocialLoginBody;
|
||||
import org.dromara.common.core.enums.UserStatus;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.exception.user.UserException;
|
||||
import org.dromara.common.core.utils.StreamUtils;
|
||||
import org.dromara.common.core.utils.ValidatorUtils;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import org.dromara.common.social.config.properties.SocialProperties;
|
||||
import org.dromara.common.social.utils.SocialUtils;
|
||||
import org.dromara.common.tenant.helper.TenantHelper;
|
||||
import org.dromara.system.domain.SysClient;
|
||||
import org.dromara.system.domain.SysUser;
|
||||
import org.dromara.system.domain.vo.SysClientVo;
|
||||
import org.dromara.system.domain.vo.SysSocialVo;
|
||||
import org.dromara.system.domain.vo.SysUserVo;
|
||||
import org.dromara.system.mapper.SysUserMapper;
|
||||
@ -59,7 +58,7 @@ public class SocialAuthStrategy implements IAuthStrategy {
|
||||
* @param client 客户端信息
|
||||
*/
|
||||
@Override
|
||||
public LoginVo login(String body, SysClient client) {
|
||||
public LoginVo login(String body, SysClientVo client) {
|
||||
SocialLoginBody loginBody = JsonUtils.parseObject(body, SocialLoginBody.class);
|
||||
ValidatorUtils.validate(loginBody);
|
||||
AuthResponse<AuthUser> response = SocialUtils.loginAuth(
|
||||
@ -83,16 +82,21 @@ public class SocialAuthStrategy implements IAuthStrategy {
|
||||
if (CollUtil.isEmpty(list)) {
|
||||
throw new ServiceException("你还没有绑定第三方账号,绑定后才可以登录!");
|
||||
}
|
||||
Optional<SysSocialVo> opt = list.stream().filter(x -> x.getTenantId().equals(loginBody.getTenantId())).findAny();
|
||||
if (opt.isEmpty()) {
|
||||
throw new ServiceException("对不起,你没有权限登录当前租户!");
|
||||
SysSocialVo social;
|
||||
if (TenantHelper.isEnable()) {
|
||||
Optional<SysSocialVo> opt = StreamUtils.findAny(list, x -> x.getTenantId().equals(loginBody.getTenantId()));
|
||||
if (opt.isEmpty()) {
|
||||
throw new ServiceException("对不起,你没有权限登录当前租户!");
|
||||
}
|
||||
social = opt.get();
|
||||
} else {
|
||||
social = list.get(0);
|
||||
}
|
||||
SysSocialVo social = opt.get();
|
||||
// 查找用户
|
||||
SysUserVo user = loadUser(social.getTenantId(), social.getUserId());
|
||||
|
||||
// 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
|
||||
LoginUser loginUser = loginService.buildLoginUser(user);
|
||||
LoginUser loginUser = TenantHelper.dynamic(social.getTenantId(), () -> {
|
||||
SysUserVo user = loadUser(social.getUserId());
|
||||
// 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
|
||||
return loginService.buildLoginUser(user);
|
||||
});
|
||||
loginUser.setClientKey(client.getClientKey());
|
||||
loginUser.setDeviceType(client.getDeviceType());
|
||||
SaLoginModel model = new SaLoginModel();
|
||||
@ -112,20 +116,16 @@ public class SocialAuthStrategy implements IAuthStrategy {
|
||||
return loginVo;
|
||||
}
|
||||
|
||||
private SysUserVo loadUser(String tenantId, Long userId) {
|
||||
return TenantHelper.dynamic(tenantId, () -> {
|
||||
SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
|
||||
.select(SysUser::getUserName, SysUser::getStatus)
|
||||
.eq(SysUser::getUserId, userId));
|
||||
if (ObjectUtil.isNull(user)) {
|
||||
log.info("登录用户:{} 不存在.", "");
|
||||
throw new UserException("user.not.exists", "");
|
||||
} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
|
||||
log.info("登录用户:{} 已被停用.", "");
|
||||
throw new UserException("user.blocked", "");
|
||||
}
|
||||
return userMapper.selectUserByUserName(user.getUserName());
|
||||
});
|
||||
private SysUserVo loadUser(Long userId) {
|
||||
SysUserVo user = userMapper.selectVoById(userId);
|
||||
if (ObjectUtil.isNull(user)) {
|
||||
log.info("登录用户:{} 不存在.", "");
|
||||
throw new UserException("user.not.exists", "");
|
||||
} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
|
||||
log.info("登录用户:{} 已被停用.", "");
|
||||
throw new UserException("user.blocked", "");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -12,6 +12,7 @@ import org.dromara.common.core.utils.ValidatorUtils;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import org.dromara.system.domain.SysClient;
|
||||
import org.dromara.system.domain.vo.SysClientVo;
|
||||
import org.dromara.system.domain.vo.SysUserVo;
|
||||
import org.dromara.web.domain.vo.LoginVo;
|
||||
import org.dromara.web.service.IAuthStrategy;
|
||||
@ -19,7 +20,7 @@ import org.dromara.web.service.SysLoginService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* 邮件认证策略
|
||||
* 小程序认证策略
|
||||
*
|
||||
* @author Michelle.Chung
|
||||
*/
|
||||
@ -31,7 +32,7 @@ public class XcxAuthStrategy implements IAuthStrategy {
|
||||
private final SysLoginService loginService;
|
||||
|
||||
@Override
|
||||
public LoginVo login(String body, SysClient client) {
|
||||
public LoginVo login(String body, SysClientVo client) {
|
||||
XcxLoginBody loginBody = JsonUtils.parseObject(body, XcxLoginBody.class);
|
||||
ValidatorUtils.validate(loginBody);
|
||||
// xcxCode 为 小程序调用 wx.login 授权后获取
|
||||
|
@ -5,24 +5,26 @@ spring.boot.admin.client:
|
||||
url: http://localhost:9090/admin
|
||||
instance:
|
||||
service-host-type: IP
|
||||
metadata:
|
||||
username: ${spring.boot.admin.client.username}
|
||||
userpassword: ${spring.boot.admin.client.password}
|
||||
username: ruoyi
|
||||
password: 123456
|
||||
|
||||
--- # powerjob 配置
|
||||
powerjob:
|
||||
worker:
|
||||
# 如何开启调度中心请查看文档教程
|
||||
enabled: false
|
||||
# 需要先在 powerjob 登录页执行应用注册后才能使用
|
||||
app-name: ruoyi-worker
|
||||
allow-lazy-connect-server: false
|
||||
max-appended-wf-context-length: 4096
|
||||
max-result-length: 4096
|
||||
# 28080 端口 随着主应用端口飘逸 避免集群冲突
|
||||
port: 2${server.port}
|
||||
protocol: http
|
||||
server-address: 127.0.0.1:7700
|
||||
store-strategy: disk
|
||||
--- # snail-job 配置
|
||||
snail-job:
|
||||
enabled: true
|
||||
# 需要在 SnailJob 后台组管理创建对应名称的组,然后创建任务的时候选择对应的组,才能正确分派任务
|
||||
group: "ruoyi_group"
|
||||
# SnailJob 接入验证令牌 详见 script/sql/snail_job.sql `sj_group_config` 表
|
||||
token: "SJ_cKqBTPzCsWA3VyuCfFoccmuIEGXjr5KT"
|
||||
server:
|
||||
host: 127.0.0.1
|
||||
port: 17888
|
||||
# 详见 script/sql/snail_job.sql `sj_namespace` 表
|
||||
namespace: ${spring.profiles.active}
|
||||
# 随主应用端口飘逸
|
||||
port: 2${server.port}
|
||||
|
||||
--- # 数据源配置
|
||||
spring:
|
||||
@ -43,7 +45,7 @@ spring:
|
||||
driverClassName: com.mysql.cj.jdbc.Driver
|
||||
# jdbc 所有参数配置参考 https://lionli.blog.csdn.net/article/details/122018562
|
||||
# rewriteBatchedStatements=true 批处理优化 大幅提升批量插入更新删除性能(对数据库有性能损耗 使用批量操作应考虑性能问题)
|
||||
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
|
||||
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
username: root
|
||||
password: root
|
||||
# 从库数据源
|
||||
@ -51,7 +53,7 @@ spring:
|
||||
lazy: true
|
||||
type: ${spring.datasource.type}
|
||||
driverClassName: com.mysql.cj.jdbc.Driver
|
||||
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
|
||||
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
username:
|
||||
password:
|
||||
# oracle:
|
||||
@ -97,13 +99,14 @@ spring.data:
|
||||
port: 6379
|
||||
# 数据库索引
|
||||
database: 0
|
||||
# 密码(如没有密码请注释掉)
|
||||
# password:
|
||||
# redis 密码必须配置
|
||||
password: ruoyi123
|
||||
# 连接超时时间
|
||||
timeout: 10s
|
||||
# 是否开启ssl
|
||||
ssl.enabled: false
|
||||
|
||||
# redisson 配置
|
||||
redisson:
|
||||
# redis key前缀
|
||||
keyPrefix:
|
||||
@ -149,36 +152,40 @@ mail:
|
||||
connectionTimeout: 0
|
||||
|
||||
--- # sms 短信 支持 阿里云 腾讯云 云片 等等各式各样的短信服务商
|
||||
# https://wind.kim/doc/start 文档地址 各个厂商可同时使用
|
||||
# https://sms4j.com/doc3/ 差异配置文档地址 支持单厂商多配置,可以配置多个同时使用
|
||||
sms:
|
||||
# 阿里云 dysmsapi.aliyuncs.com
|
||||
alibaba:
|
||||
#请求地址 默认为 dysmsapi.aliyuncs.com 如无特殊改变可以不用设置
|
||||
requestUrl: dysmsapi.aliyuncs.com
|
||||
#阿里云的accessKey
|
||||
accessKeyId: xxxxxxx
|
||||
#阿里云的accessKeySecret
|
||||
accessKeySecret: xxxxxxx
|
||||
#短信签名
|
||||
signature: 测试
|
||||
tencent:
|
||||
#请求地址默认为 sms.tencentcloudapi.com 如无特殊改变可不用设置
|
||||
requestUrl: sms.tencentcloudapi.com
|
||||
#腾讯云的accessKey
|
||||
accessKeyId: xxxxxxx
|
||||
#腾讯云的accessKeySecret
|
||||
accessKeySecret: xxxxxxx
|
||||
#短信签名
|
||||
signature: 测试
|
||||
#短信sdkAppId
|
||||
sdkAppId: appid
|
||||
#地域信息默认为 ap-guangzhou 如无特殊改变可不用设置
|
||||
territory: ap-guangzhou
|
||||
# 配置源类型用于标定配置来源(interface,yaml)
|
||||
config-type: yaml
|
||||
# 用于标定yml中的配置是否开启短信拦截,接口配置不受此限制
|
||||
restricted: true
|
||||
# 短信拦截限制单手机号每分钟最大发送,只对开启了拦截的配置有效
|
||||
minute-max: 1
|
||||
# 短信拦截限制单手机号每日最大发送量,只对开启了拦截的配置有效
|
||||
account-max: 30
|
||||
# 以下配置来自于 org.dromara.sms4j.provider.config.BaseConfig类中
|
||||
blends:
|
||||
# 唯一ID 用于发送短信寻找具体配置 随便定义别用中文即可
|
||||
# 可以同时存在两个相同厂商 例如: ali1 ali2 两个不同的阿里短信账号 也可用于区分租户
|
||||
config1:
|
||||
# 框架定义的厂商名称标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
|
||||
supplier: alibaba
|
||||
# 有些称为accessKey有些称之为apiKey,也有称为sdkKey或者appId。
|
||||
access-key-id: 您的accessKey
|
||||
# 称为accessSecret有些称之为apiSecret
|
||||
access-key-secret: 您的accessKeySecret
|
||||
signature: 您的短信签名
|
||||
sdk-app-id: 您的sdkAppId
|
||||
config2:
|
||||
# 厂商标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
|
||||
supplier: tencent
|
||||
access-key-id: 您的accessKey
|
||||
access-key-secret: 您的accessKeySecret
|
||||
signature: 您的短信签名
|
||||
sdk-app-id: 您的sdkAppId
|
||||
|
||||
|
||||
--- # 三方授权
|
||||
justauth:
|
||||
enabled: true
|
||||
# 前端外网访问地址
|
||||
address: http://localhost:80
|
||||
type:
|
||||
@ -189,6 +196,13 @@ justauth:
|
||||
client-id: 876892492581044224
|
||||
client-secret: x1Y5MTMwNzIwMjMxNTM4NDc3Mzche8
|
||||
redirect-uri: ${justauth.address}/social-callback?source=maxkey
|
||||
topiam:
|
||||
# topiam 服务器地址
|
||||
server-url: http://127.0.0.1:1989/api/v1/authorize/y0q************spq***********8ol
|
||||
client-id: 449c4*********937************759
|
||||
client-secret: ac7***********1e0************28d
|
||||
redirect-uri: ${justauth.address}/social-callback?source=topiam
|
||||
scopes: [openid, email, phone, profile]
|
||||
qq:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
|
@ -8,24 +8,26 @@ spring.boot.admin.client:
|
||||
url: http://localhost:9090/admin
|
||||
instance:
|
||||
service-host-type: IP
|
||||
metadata:
|
||||
username: ${spring.boot.admin.client.username}
|
||||
userpassword: ${spring.boot.admin.client.password}
|
||||
username: ruoyi
|
||||
password: 123456
|
||||
|
||||
--- # powerjob 配置
|
||||
powerjob:
|
||||
worker:
|
||||
# 如何开启调度中心请查看文档教程
|
||||
enabled: false
|
||||
# 需要先在 powerjob 登录页执行应用注册后才能使用
|
||||
app-name: ruoyi-worker
|
||||
allow-lazy-connect-server: false
|
||||
max-appended-wf-context-length: 4096
|
||||
max-result-length: 4096
|
||||
# 28080 端口 随着主应用端口飘逸 避免集群冲突
|
||||
port: 2${server.port}
|
||||
protocol: http
|
||||
server-address: 127.0.0.1:7700
|
||||
store-strategy: disk
|
||||
--- # snail-job 配置
|
||||
snail-job:
|
||||
enabled: true
|
||||
# 需要在 SnailJob 后台组管理创建对应名称的组,然后创建任务的时候选择对应的组,才能正确分派任务
|
||||
group: "ruoyi_group"
|
||||
# SnailJob 接入验证令牌 详见 script/sql/snail_job.sql `sj_group_config` 表
|
||||
token: "SJ_cKqBTPzCsWA3VyuCfFoccmuIEGXjr5KT"
|
||||
server:
|
||||
host: 127.0.0.1
|
||||
port: 17888
|
||||
# 详见 script/sql/snail_job.sql `sj_namespace` 表
|
||||
namespace: ${spring.profiles.active}
|
||||
# 随主应用端口飘逸
|
||||
port: 2${server.port}
|
||||
|
||||
--- # 数据源配置
|
||||
spring:
|
||||
@ -46,7 +48,7 @@ spring:
|
||||
driverClassName: com.mysql.cj.jdbc.Driver
|
||||
# jdbc 所有参数配置参考 https://lionli.blog.csdn.net/article/details/122018562
|
||||
# rewriteBatchedStatements=true 批处理优化 大幅提升批量插入更新删除性能(对数据库有性能损耗 使用批量操作应考虑性能问题)
|
||||
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
|
||||
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
username: root
|
||||
password: root
|
||||
# 从库数据源
|
||||
@ -54,7 +56,7 @@ spring:
|
||||
lazy: true
|
||||
type: ${spring.datasource.type}
|
||||
driverClassName: com.mysql.cj.jdbc.Driver
|
||||
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
|
||||
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
username:
|
||||
password:
|
||||
# oracle:
|
||||
@ -100,13 +102,14 @@ spring.data:
|
||||
port: 6379
|
||||
# 数据库索引
|
||||
database: 0
|
||||
# 密码(如没有密码请注释掉)
|
||||
# password:
|
||||
# redis 密码必须配置
|
||||
password: ruoyi123
|
||||
# 连接超时时间
|
||||
timeout: 10s
|
||||
# 是否开启ssl
|
||||
ssl.enabled: false
|
||||
|
||||
# redisson 配置
|
||||
redisson:
|
||||
# redis key前缀
|
||||
keyPrefix:
|
||||
@ -152,35 +155,39 @@ mail:
|
||||
connectionTimeout: 0
|
||||
|
||||
--- # sms 短信 支持 阿里云 腾讯云 云片 等等各式各样的短信服务商
|
||||
# https://wind.kim/doc/start 文档地址 各个厂商可同时使用
|
||||
# https://sms4j.com/doc3/ 差异配置文档地址 支持单厂商多配置,可以配置多个同时使用
|
||||
sms:
|
||||
# 阿里云 dysmsapi.aliyuncs.com
|
||||
alibaba:
|
||||
#请求地址 默认为 dysmsapi.aliyuncs.com 如无特殊改变可以不用设置
|
||||
requestUrl: dysmsapi.aliyuncs.com
|
||||
#阿里云的accessKey
|
||||
accessKeyId: xxxxxxx
|
||||
#阿里云的accessKeySecret
|
||||
accessKeySecret: xxxxxxx
|
||||
#短信签名
|
||||
signature: 测试
|
||||
tencent:
|
||||
#请求地址默认为 sms.tencentcloudapi.com 如无特殊改变可不用设置
|
||||
requestUrl: sms.tencentcloudapi.com
|
||||
#腾讯云的accessKey
|
||||
accessKeyId: xxxxxxx
|
||||
#腾讯云的accessKeySecret
|
||||
accessKeySecret: xxxxxxx
|
||||
#短信签名
|
||||
signature: 测试
|
||||
#短信sdkAppId
|
||||
sdkAppId: appid
|
||||
#地域信息默认为 ap-guangzhou 如无特殊改变可不用设置
|
||||
territory: ap-guangzhou
|
||||
# 配置源类型用于标定配置来源(interface,yaml)
|
||||
config-type: yaml
|
||||
# 用于标定yml中的配置是否开启短信拦截,接口配置不受此限制
|
||||
restricted: true
|
||||
# 短信拦截限制单手机号每分钟最大发送,只对开启了拦截的配置有效
|
||||
minute-max: 1
|
||||
# 短信拦截限制单手机号每日最大发送量,只对开启了拦截的配置有效
|
||||
account-max: 30
|
||||
# 以下配置来自于 org.dromara.sms4j.provider.config.BaseConfig类中
|
||||
blends:
|
||||
# 唯一ID 用于发送短信寻找具体配置 随便定义别用中文即可
|
||||
# 可以同时存在两个相同厂商 例如: ali1 ali2 两个不同的阿里短信账号 也可用于区分租户
|
||||
config1:
|
||||
# 框架定义的厂商名称标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
|
||||
supplier: alibaba
|
||||
# 有些称为accessKey有些称之为apiKey,也有称为sdkKey或者appId。
|
||||
access-key-id: 您的accessKey
|
||||
# 称为accessSecret有些称之为apiSecret
|
||||
access-key-secret: 您的accessKeySecret
|
||||
signature: 您的短信签名
|
||||
sdk-app-id: 您的sdkAppId
|
||||
config2:
|
||||
# 厂商标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
|
||||
supplier: tencent
|
||||
access-key-id: 您的accessKey
|
||||
access-key-secret: 您的accessKeySecret
|
||||
signature: 您的短信签名
|
||||
sdk-app-id: 您的sdkAppId
|
||||
|
||||
--- # 三方授权
|
||||
justauth:
|
||||
enabled: true
|
||||
# 前端外网访问地址
|
||||
address: http://localhost:80
|
||||
type:
|
||||
@ -191,6 +198,13 @@ justauth:
|
||||
client-id: 876892492581044224
|
||||
client-secret: x1Y5MTMwNzIwMjMxNTM4NDc3Mzche8
|
||||
redirect-uri: ${justauth.address}/social-callback?source=maxkey
|
||||
topiam:
|
||||
# topiam 服务器地址
|
||||
server-url: http://127.0.0.1:1989/api/v1/authorize/y0q************spq***********8ol
|
||||
client-id: 449c4*********937************759
|
||||
client-secret: ac7***********1e0************28d
|
||||
redirect-uri: ${justauth.address}/social-callback?source=topiam
|
||||
scopes: [ openid, email, phone, profile ]
|
||||
qq:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
|
@ -5,7 +5,7 @@ ruoyi:
|
||||
# 版本
|
||||
version: ${revision}
|
||||
# 版权年份
|
||||
copyrightYear: 2023
|
||||
copyrightYear: 2024
|
||||
|
||||
captcha:
|
||||
enable: true
|
||||
@ -46,7 +46,7 @@ logging:
|
||||
level:
|
||||
org.dromara: @logging.level@
|
||||
org.springframework: warn
|
||||
tech.powerjob.worker.background: warn
|
||||
org.mybatis.spring.mapper: error
|
||||
config: classpath:logback-plus.xml
|
||||
|
||||
# 用户配置
|
||||
@ -61,6 +61,10 @@ user:
|
||||
spring:
|
||||
application:
|
||||
name: ${ruoyi.name}
|
||||
threads:
|
||||
# 开启虚拟线程 仅jdk21可用
|
||||
virtual:
|
||||
enabled: false
|
||||
# 资源信息
|
||||
messages:
|
||||
# 国际化资源文件路径
|
||||
@ -75,6 +79,8 @@ spring:
|
||||
# 设置总上传的文件大小
|
||||
max-request-size: 20MB
|
||||
mvc:
|
||||
# 设置静态资源路径 防止所有请求都去查静态资源
|
||||
static-path-pattern: /static/**
|
||||
format:
|
||||
date-time: yyyy-MM-dd HH:mm:ss
|
||||
jackson:
|
||||
@ -115,9 +121,6 @@ security:
|
||||
# swagger 文档配置
|
||||
- /*/api-docs
|
||||
- /*/api-docs/**
|
||||
# actuator 监控配置
|
||||
- /actuator
|
||||
- /actuator/**
|
||||
|
||||
# 多租户配置
|
||||
tenant:
|
||||
@ -138,8 +141,7 @@ tenant:
|
||||
# MyBatisPlus配置
|
||||
# https://baomidou.com/config/
|
||||
mybatis-plus:
|
||||
# 不支持多包, 如有需要可在注解配置 或 提升扫包等级
|
||||
# 例如 com.**.**.mapper
|
||||
# 多包名使用 例如 org.dromara.**.mapper,org.xxx.**.mapper
|
||||
mapperPackage: org.dromara.**.mapper
|
||||
# 对应的 XML 文件位置
|
||||
mapperLocations: classpath*:mapper/**/*Mapper.xml
|
||||
@ -226,6 +228,7 @@ xss:
|
||||
urlPatterns: /system/*,/monitor/*,/tool/*
|
||||
|
||||
# 全局线程池相关配置
|
||||
# 如使用JDK21请直接使用虚拟线程 不要开启此配置
|
||||
thread-pool:
|
||||
# 是否开启线程池
|
||||
enabled: false
|
||||
@ -253,11 +256,38 @@ management:
|
||||
logfile:
|
||||
external-file: ./logs/sys-console.log
|
||||
|
||||
--- # 默认/推荐使用sse推送
|
||||
sse:
|
||||
enabled: true
|
||||
path: /resource/sse
|
||||
|
||||
--- # websocket
|
||||
websocket:
|
||||
# 如果关闭 需要和前端开关一起关闭
|
||||
enabled: true
|
||||
enabled: false
|
||||
# 路径
|
||||
path: /resource/websocket
|
||||
# 设置访问源地址
|
||||
allowedOrigins: '*'
|
||||
|
||||
--- #flowable配置
|
||||
flowable:
|
||||
# 开关 用于启动/停用工作流
|
||||
enabled: true
|
||||
process.enabled: ${flowable.enabled}
|
||||
eventregistry.enabled: ${flowable.enabled}
|
||||
async-executor-activate: false #关闭定时任务JOB
|
||||
# 将databaseSchemaUpdate设置为true。当Flowable发现库与数据库表结构不一致时,会自动将数据库表结构升级至新版本。
|
||||
database-schema-update: true
|
||||
activity-font-name: 宋体
|
||||
label-font-name: 宋体
|
||||
annotation-font-name: 宋体
|
||||
# 关闭各个模块生成表,目前只使用工作流基础表
|
||||
idm:
|
||||
enabled: false
|
||||
cmmn:
|
||||
enabled: false
|
||||
dmn:
|
||||
enabled: false
|
||||
app:
|
||||
enabled: false
|
||||
|
Binary file not shown.
@ -33,6 +33,7 @@
|
||||
<module>ruoyi-common-encrypt</module>
|
||||
<module>ruoyi-common-tenant</module>
|
||||
<module>ruoyi-common-websocket</module>
|
||||
<module>ruoyi-common-sse</module>
|
||||
</modules>
|
||||
|
||||
<artifactId>ruoyi-common</artifactId>
|
||||
|
@ -14,7 +14,7 @@
|
||||
</description>
|
||||
|
||||
<properties>
|
||||
<revision>5.1.2</revision>
|
||||
<revision>5.2.2</revision>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
@ -172,6 +172,13 @@
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- SSE模块 -->
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-sse</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
|
@ -2,6 +2,7 @@ package org.dromara.common.core.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
|
||||
/**
|
||||
* 程序注解配置
|
||||
@ -9,8 +10,8 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||
* @author Lion Li
|
||||
*/
|
||||
@AutoConfiguration
|
||||
// 表示通过aop框架暴露该代理对象,AopContext能够访问
|
||||
@EnableAspectJAutoProxy(exposeProxy = true)
|
||||
@EnableAspectJAutoProxy
|
||||
@EnableAsync(proxyTargetClass = true)
|
||||
public class ApplicationConfig {
|
||||
|
||||
}
|
||||
|
@ -5,18 +5,19 @@ import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.core.task.VirtualThreadTaskExecutor;
|
||||
import org.springframework.scheduling.annotation.AsyncConfigurer;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
/**
|
||||
* 异步配置
|
||||
* <p>
|
||||
* 如果未使用虚拟线程则生效
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@EnableAsync(proxyTargetClass = true)
|
||||
@AutoConfiguration
|
||||
public class AsyncConfig implements AsyncConfigurer {
|
||||
|
||||
@ -25,6 +26,9 @@ public class AsyncConfig implements AsyncConfigurer {
|
||||
*/
|
||||
@Override
|
||||
public Executor getAsyncExecutor() {
|
||||
if(SpringUtils.isVirtual()) {
|
||||
return new VirtualThreadTaskExecutor("async-");
|
||||
}
|
||||
return SpringUtils.getBean("scheduledExecutorService");
|
||||
}
|
||||
|
||||
|
@ -22,4 +22,9 @@ public interface CacheConstants {
|
||||
*/
|
||||
String SYS_DICT_KEY = "sys_dict:";
|
||||
|
||||
/**
|
||||
* 登录账户密码错误次数 redis key
|
||||
*/
|
||||
String PWD_ERR_CNT_KEY = "pwd_err_cnt:";
|
||||
|
||||
}
|
||||
|
@ -35,6 +35,11 @@ public interface CacheNames {
|
||||
*/
|
||||
String SYS_TENANT = GlobalConstants.GLOBAL_REDIS_KEY + "sys_tenant#30d";
|
||||
|
||||
/**
|
||||
* 客户端
|
||||
*/
|
||||
String SYS_CLIENT = GlobalConstants.GLOBAL_REDIS_KEY + "sys_client#30d";
|
||||
|
||||
/**
|
||||
* 用户账户
|
||||
*/
|
||||
|
@ -27,11 +27,6 @@ public interface GlobalConstants {
|
||||
*/
|
||||
String RATE_LIMIT_KEY = GLOBAL_REDIS_KEY + "rate_limit:";
|
||||
|
||||
/**
|
||||
* 登录账户密码错误次数 redis key
|
||||
*/
|
||||
String PWD_ERR_CNT_KEY = GLOBAL_REDIS_KEY + "pwd_err_cnt:";
|
||||
|
||||
/**
|
||||
* 三方认证 redis key
|
||||
*/
|
||||
|
@ -0,0 +1,54 @@
|
||||
package org.dromara.common.core.constant;
|
||||
|
||||
import cn.hutool.core.lang.RegexPool;
|
||||
|
||||
/**
|
||||
* 常用正则表达式字符串
|
||||
* <p>
|
||||
* 常用正则表达式集合,更多正则见: https://any86.github.io/any-rule/
|
||||
*
|
||||
* @author Feng
|
||||
*/
|
||||
public interface RegexConstants extends RegexPool {
|
||||
|
||||
/**
|
||||
* 字典类型必须以字母开头,且只能为(小写字母,数字,下滑线)
|
||||
*/
|
||||
String DICTIONARY_TYPE = "^[a-z][a-z0-9_]*$";
|
||||
|
||||
/**
|
||||
* 权限标识必须符合 tool:build:list 格式,或者空字符串
|
||||
*/
|
||||
String PERMISSION_STRING = "^(|^[a-zA-Z0-9_]+:[a-zA-Z0-9_]+:[a-zA-Z0-9_]+)$";
|
||||
|
||||
/**
|
||||
* 身份证号码(后6位)
|
||||
*/
|
||||
String ID_CARD_LAST_6 = "^(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";
|
||||
|
||||
/**
|
||||
* QQ号码
|
||||
*/
|
||||
String QQ_NUMBER = "^[1-9][0-9]\\d{4,9}$";
|
||||
|
||||
/**
|
||||
* 邮政编码
|
||||
*/
|
||||
String POSTAL_CODE = "^[1-9]\\d{5}$";
|
||||
|
||||
/**
|
||||
* 注册账号
|
||||
*/
|
||||
String ACCOUNT = "^[a-zA-Z][a-zA-Z0-9_]{4,15}$";
|
||||
|
||||
/**
|
||||
* 密码:包含至少8个字符,包括大写字母、小写字母、数字和特殊字符
|
||||
*/
|
||||
String PASSWORD = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$";
|
||||
|
||||
/**
|
||||
* 通用状态(0表示正常,1表示停用)
|
||||
*/
|
||||
String STATUS = "^[01]$";
|
||||
|
||||
}
|
@ -67,6 +67,16 @@ public interface UserConstants {
|
||||
*/
|
||||
String DICT_NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 通用存在标志
|
||||
*/
|
||||
String DEL_FLAG_NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 通用删除标志
|
||||
*/
|
||||
String DEL_FLAG_REMOVED = "2";
|
||||
|
||||
/**
|
||||
* 是否为系统默认(是)
|
||||
*/
|
||||
|
@ -0,0 +1,46 @@
|
||||
package org.dromara.common.core.domain.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* OSS对象
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class OssDTO implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 对象存储主键
|
||||
*/
|
||||
private Long ossId;
|
||||
|
||||
/**
|
||||
* 文件名
|
||||
*/
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 原名
|
||||
*/
|
||||
private String originalName;
|
||||
|
||||
/**
|
||||
* 文件后缀名
|
||||
*/
|
||||
private String fileSuffix;
|
||||
|
||||
/**
|
||||
* URL地址
|
||||
*/
|
||||
private String url;
|
||||
|
||||
}
|
@ -3,6 +3,7 @@ package org.dromara.common.core.domain.dto;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
@ -15,6 +16,9 @@ import java.io.Serializable;
|
||||
@NoArgsConstructor
|
||||
public class RoleDTO implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 角色ID
|
||||
*/
|
||||
|
@ -0,0 +1,73 @@
|
||||
package org.dromara.common.core.domain.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
|
||||
/**
|
||||
* 用户
|
||||
*
|
||||
* @author Michelle.Chung
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class UserDTO implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 用户ID
|
||||
*/
|
||||
private Long userId;
|
||||
|
||||
/**
|
||||
* 部门ID
|
||||
*/
|
||||
private Long deptId;
|
||||
|
||||
/**
|
||||
* 用户账号
|
||||
*/
|
||||
private String userName;
|
||||
|
||||
/**
|
||||
* 用户昵称
|
||||
*/
|
||||
private String nickName;
|
||||
|
||||
/**
|
||||
* 用户类型(sys_user系统用户)
|
||||
*/
|
||||
private String userType;
|
||||
|
||||
/**
|
||||
* 用户邮箱
|
||||
*/
|
||||
private String email;
|
||||
|
||||
/**
|
||||
* 手机号码
|
||||
*/
|
||||
private String phonenumber;
|
||||
|
||||
/**
|
||||
* 用户性别(0男 1女 2未知)
|
||||
*/
|
||||
private String sex;
|
||||
|
||||
/**
|
||||
* 帐号状态(0正常 1停用)
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private Date createTime;
|
||||
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package org.dromara.common.core.domain.event;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 总体流程监听
|
||||
*
|
||||
* @author may
|
||||
*/
|
||||
|
||||
@Data
|
||||
public class ProcessEvent implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 流程定义key
|
||||
*/
|
||||
private String key;
|
||||
|
||||
/**
|
||||
* 业务id
|
||||
*/
|
||||
private String businessKey;
|
||||
|
||||
/**
|
||||
* 状态
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 当为true时为申请人节点办理
|
||||
*/
|
||||
private boolean submit;
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package org.dromara.common.core.domain.event;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 流程办理监听
|
||||
*
|
||||
* @author may
|
||||
*/
|
||||
|
||||
@Data
|
||||
public class ProcessTaskEvent implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 流程定义key
|
||||
*/
|
||||
private String key;
|
||||
|
||||
/**
|
||||
* 审批节点key
|
||||
*/
|
||||
private String taskDefinitionKey;
|
||||
|
||||
/**
|
||||
* 任务id
|
||||
*/
|
||||
private String taskId;
|
||||
|
||||
/**
|
||||
* 业务id
|
||||
*/
|
||||
private String businessKey;
|
||||
|
||||
}
|
@ -14,7 +14,6 @@ import java.util.Set;
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class LoginUser implements Serializable {
|
||||
@ -37,6 +36,11 @@ public class LoginUser implements Serializable {
|
||||
*/
|
||||
private Long deptId;
|
||||
|
||||
/**
|
||||
* 部门类别编码
|
||||
*/
|
||||
private String deptCategory;
|
||||
|
||||
/**
|
||||
* 部门名
|
||||
*/
|
||||
|
@ -0,0 +1,152 @@
|
||||
package org.dromara.common.core.enums;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 业务状态枚举
|
||||
*
|
||||
* @author may
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum BusinessStatusEnum {
|
||||
/**
|
||||
* 已撤销
|
||||
*/
|
||||
CANCEL("cancel", "已撤销"),
|
||||
/**
|
||||
* 草稿
|
||||
*/
|
||||
DRAFT("draft", "草稿"),
|
||||
/**
|
||||
* 待审核
|
||||
*/
|
||||
WAITING("waiting", "待审核"),
|
||||
/**
|
||||
* 已完成
|
||||
*/
|
||||
FINISH("finish", "已完成"),
|
||||
/**
|
||||
* 已作废
|
||||
*/
|
||||
INVALID("invalid", "已作废"),
|
||||
/**
|
||||
* 已退回
|
||||
*/
|
||||
BACK("back", "已退回"),
|
||||
/**
|
||||
* 已终止
|
||||
*/
|
||||
TERMINATION("termination", "已终止");
|
||||
|
||||
/**
|
||||
* 状态
|
||||
*/
|
||||
private final String status;
|
||||
|
||||
/**
|
||||
* 描述
|
||||
*/
|
||||
private final String desc;
|
||||
|
||||
/**
|
||||
* 获取业务状态
|
||||
*
|
||||
* @param status 状态
|
||||
*/
|
||||
public static String findByStatus(String status) {
|
||||
if (StringUtils.isBlank(status)) {
|
||||
return StrUtil.EMPTY;
|
||||
}
|
||||
return Arrays.stream(BusinessStatusEnum.values())
|
||||
.filter(statusEnum -> statusEnum.getStatus().equals(status))
|
||||
.findFirst()
|
||||
.map(BusinessStatusEnum::getDesc)
|
||||
.orElse(StrUtil.EMPTY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动流程校验
|
||||
*
|
||||
* @param status 状态
|
||||
*/
|
||||
public static void checkStartStatus(String status) {
|
||||
if (WAITING.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已提交过申请,正在审批中!");
|
||||
} else if (FINISH.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已完成申请!");
|
||||
} else if (INVALID.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已作废!");
|
||||
} else if (TERMINATION.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已终止!");
|
||||
} else if (StringUtils.isBlank(status)) {
|
||||
throw new ServiceException("流程状态为空!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 撤销流程校验
|
||||
*
|
||||
* @param status 状态
|
||||
*/
|
||||
public static void checkCancelStatus(String status) {
|
||||
if (CANCEL.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已撤销!");
|
||||
} else if (FINISH.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已完成申请!");
|
||||
} else if (INVALID.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已作废!");
|
||||
} else if (TERMINATION.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已终止!");
|
||||
} else if (BACK.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已退回!");
|
||||
} else if (StringUtils.isBlank(status)) {
|
||||
throw new ServiceException("流程状态为空!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 驳回流程校验
|
||||
*
|
||||
* @param status 状态
|
||||
*/
|
||||
public static void checkBackStatus(String status) {
|
||||
if (BACK.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已退回!");
|
||||
} else if (FINISH.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已完成申请!");
|
||||
} else if (INVALID.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已作废!");
|
||||
} else if (TERMINATION.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已终止!");
|
||||
} else if (CANCEL.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已撤销!");
|
||||
} else if (StringUtils.isBlank(status)) {
|
||||
throw new ServiceException("流程状态为空!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 作废,终止流程校验
|
||||
*
|
||||
* @param status 状态
|
||||
*/
|
||||
public static void checkInvalidStatus(String status) {
|
||||
if (FINISH.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已完成申请!");
|
||||
} else if (INVALID.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已作废!");
|
||||
} else if (TERMINATION.getStatus().equals(status)) {
|
||||
throw new ServiceException("该单据已终止!");
|
||||
} else if (StringUtils.isBlank(status)) {
|
||||
throw new ServiceException("流程状态为空!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,6 @@
|
||||
package org.dromara.common.core.exception;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.*;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
@ -45,19 +42,11 @@ public final class ServiceException extends RuntimeException {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getDetailMessage() {
|
||||
return detailMessage;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public ServiceException setMessage(String message) {
|
||||
this.message = message;
|
||||
return this;
|
||||
|
@ -0,0 +1,52 @@
|
||||
package org.dromara.common.core.factory;
|
||||
|
||||
import cn.hutool.core.lang.PatternPool;
|
||||
import org.dromara.common.core.constant.RegexConstants;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 正则表达式模式池工厂
|
||||
* <p>初始化的时候将正则表达式加入缓存池当中</p>
|
||||
* <p>提高正则表达式的性能,避免重复编译相同的正则表达式</p>
|
||||
*
|
||||
* @author 21001
|
||||
*/
|
||||
public class RegexPatternPoolFactory extends PatternPool {
|
||||
|
||||
/**
|
||||
* 字典类型必须以字母开头,且只能为(小写字母,数字,下滑线)
|
||||
*/
|
||||
public static final Pattern DICTIONARY_TYPE = get(RegexConstants.DICTIONARY_TYPE);
|
||||
|
||||
/**
|
||||
* 身份证号码(后6位)
|
||||
*/
|
||||
public static final Pattern ID_CARD_LAST_6 = get(RegexConstants.ID_CARD_LAST_6);
|
||||
|
||||
/**
|
||||
* QQ号码
|
||||
*/
|
||||
public static final Pattern QQ_NUMBER = get(RegexConstants.QQ_NUMBER);
|
||||
|
||||
/**
|
||||
* 邮政编码
|
||||
*/
|
||||
public static final Pattern POSTAL_CODE = get(RegexConstants.POSTAL_CODE);
|
||||
|
||||
/**
|
||||
* 注册账号
|
||||
*/
|
||||
public static final Pattern ACCOUNT = get(RegexConstants.ACCOUNT);
|
||||
|
||||
/**
|
||||
* 密码:包含至少8个字符,包括大写字母、小写字母、数字和特殊字符
|
||||
*/
|
||||
public static final Pattern PASSWORD = get(RegexConstants.PASSWORD);
|
||||
|
||||
/**
|
||||
* 通用状态(0表示正常,1表示停用)
|
||||
*/
|
||||
public static final Pattern STATUS = get(RegexConstants.STATUS);
|
||||
|
||||
}
|
@ -1,5 +1,9 @@
|
||||
package org.dromara.common.core.service;
|
||||
|
||||
import org.dromara.common.core.domain.dto.OssDTO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 通用 OSS服务
|
||||
*
|
||||
@ -15,4 +19,11 @@ public interface OssService {
|
||||
*/
|
||||
String selectUrlByIds(String ossIds);
|
||||
|
||||
/**
|
||||
* 通过ossId查询列表
|
||||
*
|
||||
* @param ossIds ossId串逗号分隔
|
||||
* @return 列表
|
||||
*/
|
||||
List<OssDTO> selectByIds(String ossIds);
|
||||
}
|
||||
|
@ -1,5 +1,9 @@
|
||||
package org.dromara.common.core.service;
|
||||
|
||||
import org.dromara.common.core.domain.dto.UserDTO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 通用 用户服务
|
||||
*
|
||||
@ -19,8 +23,63 @@ public interface UserService {
|
||||
* 通过用户ID查询用户账户
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 用户账户
|
||||
* @return 用户名称
|
||||
*/
|
||||
String selectNicknameById(Long userId);
|
||||
|
||||
/**
|
||||
* 通过用户ID查询用户账户
|
||||
*
|
||||
* @param userIds 用户ID 多个用逗号隔开
|
||||
* @return 用户名称
|
||||
*/
|
||||
String selectNicknameByIds(String userIds);
|
||||
|
||||
/**
|
||||
* 通过用户ID查询用户手机号
|
||||
*
|
||||
* @param userId 用户id
|
||||
* @return 用户手机号
|
||||
*/
|
||||
String selectPhonenumberById(Long userId);
|
||||
|
||||
/**
|
||||
* 通过用户ID查询用户邮箱
|
||||
*
|
||||
* @param userId 用户id
|
||||
* @return 用户邮箱
|
||||
*/
|
||||
String selectEmailById(Long userId);
|
||||
|
||||
/**
|
||||
* 通过用户ID查询用户列表
|
||||
*
|
||||
* @param userIds 用户ids
|
||||
* @return 用户列表
|
||||
*/
|
||||
List<UserDTO> selectListByIds(List<Long> userIds);
|
||||
|
||||
/**
|
||||
* 通过角色ID查询用户ID
|
||||
*
|
||||
* @param roleIds 角色ids
|
||||
* @return 用户ids
|
||||
*/
|
||||
List<Long> selectUserIdsByRoleIds(List<Long> roleIds);
|
||||
|
||||
/**
|
||||
* 通过角色ID查询用户
|
||||
*
|
||||
* @param roleIds 角色ids
|
||||
* @return 用户
|
||||
*/
|
||||
List<UserDTO> selectUsersByRoleIds(List<Long> roleIds);
|
||||
|
||||
/**
|
||||
* 通过部门ID查询用户
|
||||
*
|
||||
* @param deptIds 部门ids
|
||||
* @return 用户
|
||||
*/
|
||||
List<UserDTO> selectUsersByDeptIds(List<Long> deptIds);
|
||||
}
|
||||
|
@ -0,0 +1,76 @@
|
||||
package org.dromara.common.core.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 通用 工作流服务
|
||||
*
|
||||
* @author may
|
||||
*/
|
||||
public interface WorkflowService {
|
||||
|
||||
/**
|
||||
* 运行中的实例 删除程实例,删除历史记录,删除业务与流程关联信息
|
||||
*
|
||||
* @param businessKeys 业务id
|
||||
* @return 结果
|
||||
*/
|
||||
boolean deleteRunAndHisInstance(List<String> businessKeys);
|
||||
|
||||
/**
|
||||
* 获取当前流程状态
|
||||
*
|
||||
* @param taskId 任务id
|
||||
*/
|
||||
String getBusinessStatusByTaskId(String taskId);
|
||||
|
||||
/**
|
||||
* 获取当前流程状态
|
||||
*
|
||||
* @param businessKey 业务id
|
||||
*/
|
||||
String getBusinessStatus(String businessKey);
|
||||
|
||||
/**
|
||||
* 设置流程变量(全局变量)
|
||||
*
|
||||
* @param taskId 任务id
|
||||
* @param variableName 变量名称
|
||||
* @param value 变量值
|
||||
*/
|
||||
void setVariable(String taskId, String variableName, Object value);
|
||||
|
||||
/**
|
||||
* 设置流程变量(全局变量)
|
||||
*
|
||||
* @param taskId 任务id
|
||||
* @param variables 流程变量
|
||||
*/
|
||||
void setVariables(String taskId, Map<String, Object> variables);
|
||||
|
||||
/**
|
||||
* 设置流程变量(本地变量,非全局变量)
|
||||
*
|
||||
* @param taskId 任务id
|
||||
* @param variableName 变量名称
|
||||
* @param value 变量值
|
||||
*/
|
||||
void setVariableLocal(String taskId, String variableName, Object value);
|
||||
|
||||
/**
|
||||
* 设置流程变量(本地变量,非全局变量)
|
||||
*
|
||||
* @param taskId 任务id
|
||||
* @param variables 流程变量
|
||||
*/
|
||||
void setVariablesLocal(String taskId, Map<String, Object> variables);
|
||||
|
||||
/**
|
||||
* 按照业务id查询流程实例id
|
||||
*
|
||||
* @param businessKey 业务id
|
||||
* @return 结果
|
||||
*/
|
||||
String getInstanceIdByBusinessKey(String businessKey);
|
||||
}
|
@ -1,9 +1,10 @@
|
||||
package org.dromara.common.core.utils;
|
||||
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import org.springframework.aop.framework.AopContext;
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
import org.springframework.boot.autoconfigure.thread.Threading;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
@ -48,7 +49,7 @@ public final class SpringUtils extends SpringUtil {
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T getAopProxy(T invoker) {
|
||||
return (T) AopContext.currentProxy();
|
||||
return (T) getBean(invoker.getClass());
|
||||
}
|
||||
|
||||
|
||||
@ -59,4 +60,8 @@ public final class SpringUtils extends SpringUtil {
|
||||
return getApplicationContext();
|
||||
}
|
||||
|
||||
public static boolean isVirtual() {
|
||||
return Threading.VIRTUAL.isActive(getBean(Environment.class));
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -7,6 +7,7 @@ import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
@ -34,6 +35,34 @@ public class StreamUtils {
|
||||
return collection.stream().filter(function).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 找到流中满足条件的第一个元素
|
||||
*
|
||||
* @param collection 需要查询的集合
|
||||
* @param function 过滤方法
|
||||
* @return 找到符合条件的第一个元素,没有则返回null
|
||||
*/
|
||||
public static <E> E findFirst(Collection<E> collection, Predicate<E> function) {
|
||||
if (CollUtil.isEmpty(collection)) {
|
||||
return null;
|
||||
}
|
||||
return collection.stream().filter(function).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 找到流中任意一个满足条件的元素
|
||||
*
|
||||
* @param collection 需要查询的集合
|
||||
* @param function 过滤方法
|
||||
* @return 找到符合条件的任意一个元素,没有则返回null
|
||||
*/
|
||||
public static <E> Optional<E> findAny(Collection<E> collection, Predicate<E> function) {
|
||||
if (CollUtil.isEmpty(collection)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return collection.stream().filter(function).findAny();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将collection拼接
|
||||
*
|
||||
|
@ -22,6 +22,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
|
||||
|
||||
public static final String SEPARATOR = ",";
|
||||
|
||||
public static final String SLASH = "/";
|
||||
|
||||
/**
|
||||
* 获取参数不为空值
|
||||
*
|
||||
|
@ -1,11 +1,11 @@
|
||||
package org.dromara.common.core.utils;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import jakarta.validation.Validator;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
@ -18,6 +18,13 @@ public class ValidatorUtils {
|
||||
|
||||
private static final Validator VALID = SpringUtils.getBean(Validator.class);
|
||||
|
||||
/**
|
||||
* 对给定对象进行参数校验,并根据指定的校验组进行校验
|
||||
*
|
||||
* @param object 要进行校验的对象
|
||||
* @param groups 校验组
|
||||
* @throws ConstraintViolationException 如果校验不通过,则抛出参数校验异常
|
||||
*/
|
||||
public static <T> void validate(T object, Class<?>... groups) {
|
||||
Set<ConstraintViolation<T>> validate = VALID.validate(object, groups);
|
||||
if (!validate.isEmpty()) {
|
||||
|
@ -0,0 +1,30 @@
|
||||
package org.dromara.common.core.utils.regex;
|
||||
|
||||
|
||||
import cn.hutool.core.util.ReUtil;
|
||||
import org.dromara.common.core.constant.RegexConstants;
|
||||
|
||||
/**
|
||||
* 正则相关工具类
|
||||
*
|
||||
* @author Feng
|
||||
*/
|
||||
public final class RegexUtils extends ReUtil {
|
||||
|
||||
/**
|
||||
* 从输入字符串中提取匹配的部分,如果没有匹配则返回默认值
|
||||
*
|
||||
* @param input 要提取的输入字符串
|
||||
* @param regex 用于匹配的正则表达式,可以使用 {@link RegexConstants} 中定义的常量
|
||||
* @param defaultInput 如果没有匹配时返回的默认值
|
||||
* @return 如果找到匹配的部分,则返回匹配的部分,否则返回默认值
|
||||
*/
|
||||
public static String extractFromString(String input, String regex, String defaultInput) {
|
||||
try {
|
||||
return ReUtil.get(regex, input, 1);
|
||||
} catch (Exception e) {
|
||||
return defaultInput;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,105 @@
|
||||
package org.dromara.common.core.utils.regex;
|
||||
|
||||
import cn.hutool.core.exceptions.ValidateException;
|
||||
import cn.hutool.core.lang.Validator;
|
||||
import org.dromara.common.core.factory.RegexPatternPoolFactory;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 正则字段校验器
|
||||
* 主要验证字段非空、是否为满足指定格式等
|
||||
*
|
||||
* @author Feng
|
||||
*/
|
||||
public class RegexValidator extends Validator {
|
||||
|
||||
/**
|
||||
* 字典类型必须以字母开头,且只能为(小写字母,数字,下滑线)
|
||||
*/
|
||||
public static final Pattern DICTIONARY_TYPE = RegexPatternPoolFactory.DICTIONARY_TYPE;
|
||||
|
||||
/**
|
||||
* 身份证号码(后6位)
|
||||
*/
|
||||
public static final Pattern ID_CARD_LAST_6 = RegexPatternPoolFactory.ID_CARD_LAST_6;
|
||||
|
||||
/**
|
||||
* QQ号码
|
||||
*/
|
||||
public static final Pattern QQ_NUMBER = RegexPatternPoolFactory.QQ_NUMBER;
|
||||
|
||||
/**
|
||||
* 邮政编码
|
||||
*/
|
||||
public static final Pattern POSTAL_CODE = RegexPatternPoolFactory.POSTAL_CODE;
|
||||
|
||||
/**
|
||||
* 注册账号
|
||||
*/
|
||||
public static final Pattern ACCOUNT = RegexPatternPoolFactory.ACCOUNT;
|
||||
|
||||
/**
|
||||
* 密码:包含至少8个字符,包括大写字母、小写字母、数字和特殊字符
|
||||
*/
|
||||
public static final Pattern PASSWORD = RegexPatternPoolFactory.PASSWORD;
|
||||
|
||||
/**
|
||||
* 通用状态(0表示正常,1表示停用)
|
||||
*/
|
||||
public static final Pattern STATUS = RegexPatternPoolFactory.STATUS;
|
||||
|
||||
|
||||
/**
|
||||
* 检查输入的账号是否匹配预定义的规则
|
||||
*
|
||||
* @param value 要验证的账号
|
||||
* @return 如果账号符合规则,返回 true;否则,返回 false。
|
||||
*/
|
||||
public static boolean isAccount(CharSequence value) {
|
||||
return isMatchRegex(ACCOUNT, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证输入的账号是否符合规则,如果不符合,则抛出 ValidateException 异常
|
||||
*
|
||||
* @param value 要验证的账号
|
||||
* @param errorMsg 验证失败时抛出的异常消息
|
||||
* @param <T> CharSequence 的子类型
|
||||
* @return 如果验证通过,返回输入的账号
|
||||
* @throws ValidateException 如果验证失败
|
||||
*/
|
||||
public static <T extends CharSequence> T validateAccount(T value, String errorMsg) throws ValidateException {
|
||||
if (!isAccount(value)) {
|
||||
throw new ValidateException(errorMsg);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查输入的状态是否匹配预定义的规则
|
||||
*
|
||||
* @param value 要验证的状态
|
||||
* @return 如果状态符合规则,返回 true;否则,返回 false。
|
||||
*/
|
||||
public static boolean isStatus(CharSequence value) {
|
||||
return isMatchRegex(STATUS, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证输入的状态是否符合规则,如果不符合,则抛出 ValidateException 异常
|
||||
*
|
||||
* @param value 要验证的状态
|
||||
* @param errorMsg 验证失败时抛出的异常消息
|
||||
* @param <T> CharSequence 的子类型
|
||||
* @return 如果验证通过,返回输入的状态
|
||||
* @throws ValidateException 如果验证失败
|
||||
*/
|
||||
public static <T extends CharSequence> T validateStatus(T value, String errorMsg) throws ValidateException {
|
||||
if (!isStatus(value)) {
|
||||
throw new ValidateException(errorMsg);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
}
|
@ -11,6 +11,7 @@ import io.swagger.v3.oas.models.Paths;
|
||||
import io.swagger.v3.oas.models.tags.Tag;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.dromara.common.core.utils.StreamUtils;
|
||||
import org.springdoc.core.customizers.OpenApiBuilderCustomizer;
|
||||
import org.springdoc.core.customizers.ServerBaseUrlCustomizer;
|
||||
import org.springdoc.core.properties.SpringDocConfigProperties;
|
||||
@ -230,7 +231,7 @@ public class OpenApiHandler extends OpenAPIService {
|
||||
.flatMap(x -> Stream.of(x.value())).collect(Collectors.toSet());
|
||||
methodTags.addAll(AnnotatedElementUtils.findAllMergedAnnotations(method, io.swagger.v3.oas.annotations.tags.Tag.class));
|
||||
if (!CollectionUtils.isEmpty(methodTags)) {
|
||||
tagsStr.addAll(methodTags.stream().map(tag -> propertyResolverUtils.resolve(tag.name(), locale)).collect(Collectors.toSet()));
|
||||
tagsStr.addAll(StreamUtils.toSet(methodTags, tag -> propertyResolverUtils.resolve(tag.name(), locale)));
|
||||
List<io.swagger.v3.oas.annotations.tags.Tag> allTags = new ArrayList<>(methodTags);
|
||||
addTags(allTags, tags, locale);
|
||||
}
|
||||
|
@ -22,11 +22,6 @@
|
||||
<artifactId>ruoyi-common-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mybatis.spring.boot</groupId>
|
||||
<artifactId>mybatis-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15to18</artifactId>
|
||||
@ -42,6 +37,18 @@
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
<optional>true</optional>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.mybatis</groupId>
|
||||
<artifactId>mybatis-spring</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
@ -1,5 +1,8 @@
|
||||
package org.dromara.common.encrypt.config;
|
||||
|
||||
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
|
||||
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.common.encrypt.core.EncryptorManager;
|
||||
import org.dromara.common.encrypt.interceptor.MybatisDecryptInterceptor;
|
||||
import org.dromara.common.encrypt.interceptor.MybatisEncryptInterceptor;
|
||||
@ -16,17 +19,18 @@ import org.springframework.context.annotation.Bean;
|
||||
* @author 老马
|
||||
* @version 4.6.0
|
||||
*/
|
||||
@AutoConfiguration
|
||||
@AutoConfiguration(after = MybatisPlusAutoConfiguration.class)
|
||||
@EnableConfigurationProperties(EncryptorProperties.class)
|
||||
@ConditionalOnProperty(value = "mybatis-encryptor.enable", havingValue = "true")
|
||||
@Slf4j
|
||||
public class EncryptorAutoConfiguration {
|
||||
|
||||
@Autowired
|
||||
private EncryptorProperties properties;
|
||||
|
||||
@Bean
|
||||
public EncryptorManager encryptorManager() {
|
||||
return new EncryptorManager();
|
||||
public EncryptorManager encryptorManager(MybatisPlusProperties mybatisPlusProperties) {
|
||||
return new EncryptorManager(mybatisPlusProperties.getTypeAliasesPackage());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ -38,4 +42,8 @@ public class EncryptorAutoConfiguration {
|
||||
public MybatisDecryptInterceptor mybatisDecryptInterceptor(EncryptorManager encryptorManager) {
|
||||
return new MybatisDecryptInterceptor(encryptorManager, properties);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
@ -1,14 +1,23 @@
|
||||
package org.dromara.common.encrypt.core;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.ReflectUtil;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.io.Resources;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.encrypt.annotation.EncryptField;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
|
||||
import org.springframework.core.io.support.ResourcePatternResolver;
|
||||
import org.springframework.core.type.ClassMetadata;
|
||||
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ -19,6 +28,7 @@ import java.util.stream.Collectors;
|
||||
* @version 4.6.0
|
||||
*/
|
||||
@Slf4j
|
||||
@NoArgsConstructor
|
||||
public class EncryptorManager {
|
||||
|
||||
/**
|
||||
@ -31,25 +41,24 @@ public class EncryptorManager {
|
||||
*/
|
||||
Map<Class<?>, Set<Field>> fieldCache = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 构造方法传入类加密字段缓存
|
||||
*
|
||||
* @param typeAliasesPackage 实体类包
|
||||
*/
|
||||
public EncryptorManager(String typeAliasesPackage) {
|
||||
scanEncryptClasses(typeAliasesPackage);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取类加密字段缓存
|
||||
*/
|
||||
public Set<Field> getFieldCache(Class<?> sourceClazz) {
|
||||
return fieldCache.computeIfAbsent(sourceClazz, clazz -> {
|
||||
Set<Field> fieldSet = new HashSet<>();
|
||||
while (clazz != null) {
|
||||
Field[] fields = clazz.getDeclaredFields();
|
||||
fieldSet.addAll(Arrays.asList(fields));
|
||||
clazz = clazz.getSuperclass();
|
||||
}
|
||||
fieldSet = fieldSet.stream().filter(field ->
|
||||
field.isAnnotationPresent(EncryptField.class) && field.getType() == String.class)
|
||||
.collect(Collectors.toSet());
|
||||
for (Field field : fieldSet) {
|
||||
field.setAccessible(true);
|
||||
}
|
||||
return fieldSet;
|
||||
});
|
||||
if (ObjectUtil.isNotNull(fieldCache)) {
|
||||
return fieldCache.get(sourceClazz);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -97,4 +106,53 @@ public class EncryptorManager {
|
||||
return encryptor.decrypt(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 typeAliasesPackage 设置的扫描包 扫描缓存实体
|
||||
*/
|
||||
private void scanEncryptClasses(String typeAliasesPackage) {
|
||||
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
|
||||
CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
|
||||
String[] packagePatternArray = StringUtils.splitPreserveAllTokens(typeAliasesPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
|
||||
String classpath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX;
|
||||
try {
|
||||
for (String packagePattern : packagePatternArray) {
|
||||
String path = ClassUtils.convertClassNameToResourcePath(packagePattern);
|
||||
Resource[] resources = resolver.getResources(classpath + path + "/*.class");
|
||||
for (Resource resource : resources) {
|
||||
ClassMetadata classMetadata = factory.getMetadataReader(resource).getClassMetadata();
|
||||
Class<?> clazz = Resources.classForName(classMetadata.getClassName());
|
||||
Set<Field> encryptFieldSet = getEncryptFieldSetFromClazz(clazz);
|
||||
if (CollUtil.isNotEmpty(encryptFieldSet)) {
|
||||
fieldCache.put(clazz, encryptFieldSet);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("初始化数据安全缓存时出错:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个类的加密字段集合
|
||||
*/
|
||||
private Set<Field> getEncryptFieldSetFromClazz(Class<?> clazz) {
|
||||
Set<Field> fieldSet = new HashSet<>();
|
||||
// 判断clazz如果是接口,内部类,匿名类就直接返回
|
||||
if (clazz.isInterface() || clazz.isMemberClass() || clazz.isAnonymousClass()) {
|
||||
return fieldSet;
|
||||
}
|
||||
while (clazz != null) {
|
||||
Field[] fields = clazz.getDeclaredFields();
|
||||
fieldSet.addAll(Arrays.asList(fields));
|
||||
clazz = clazz.getSuperclass();
|
||||
}
|
||||
fieldSet = fieldSet.stream().filter(field ->
|
||||
field.isAnnotationPresent(EncryptField.class) && field.getType() == String.class)
|
||||
.collect(Collectors.toSet());
|
||||
for (Field field : fieldSet) {
|
||||
field.setAccessible(true);
|
||||
}
|
||||
return fieldSet;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -11,7 +11,6 @@ import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.encrypt.annotation.ApiEncrypt;
|
||||
import org.dromara.common.encrypt.properties.ApiDecryptProperties;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.HandlerExecutionChain;
|
||||
@ -36,47 +35,43 @@ public class CryptoFilter implements Filter {
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
HttpServletRequest servletRequest = (HttpServletRequest) request;
|
||||
HttpServletResponse servletResponse = (HttpServletResponse) response;
|
||||
|
||||
boolean encryptFlag = false;
|
||||
// 获取加密注解
|
||||
ApiEncrypt apiEncrypt = this.getApiEncryptAnnotation(servletRequest);
|
||||
boolean responseFlag = apiEncrypt != null && apiEncrypt.response();
|
||||
ServletRequest requestWrapper = null;
|
||||
ServletResponse responseWrapper = null;
|
||||
EncryptResponseBodyWrapper responseBodyWrapper = null;
|
||||
|
||||
// 是否为 json 请求
|
||||
if (StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
|
||||
// 是否为 put 或者 post 请求
|
||||
if (HttpMethod.PUT.matches(servletRequest.getMethod()) || HttpMethod.POST.matches(servletRequest.getMethod())) {
|
||||
// 是否存在加密标头
|
||||
String headerValue = servletRequest.getHeader(properties.getHeaderFlag());
|
||||
if (StringUtils.isNotBlank(headerValue)) {
|
||||
// 请求解密
|
||||
requestWrapper = new DecryptRequestBodyWrapper(servletRequest, properties.getPrivateKey(), properties.getHeaderFlag());
|
||||
// 获取加密注解
|
||||
ApiEncrypt apiEncrypt = this.getApiEncryptAnnotation(servletRequest);
|
||||
if (ObjectUtil.isNotNull(apiEncrypt)) {
|
||||
// 响应加密标志
|
||||
encryptFlag = apiEncrypt.response();
|
||||
} else {
|
||||
// 是否有注解,有就报错,没有放行
|
||||
HandlerExceptionResolver exceptionResolver = SpringUtils.getBean(HandlerExceptionResolver.class);
|
||||
exceptionResolver.resolveException(
|
||||
servletRequest, servletResponse, null,
|
||||
new ServiceException("没有访问权限,请联系管理员授权", HttpStatus.FORBIDDEN));
|
||||
}
|
||||
}
|
||||
// 判断是否响应加密
|
||||
if (encryptFlag) {
|
||||
responseBodyWrapper = new EncryptResponseBodyWrapper(servletResponse);
|
||||
responseWrapper = responseBodyWrapper;
|
||||
// 是否为 put 或者 post 请求
|
||||
if (HttpMethod.PUT.matches(servletRequest.getMethod()) || HttpMethod.POST.matches(servletRequest.getMethod())) {
|
||||
// 是否存在加密标头
|
||||
String headerValue = servletRequest.getHeader(properties.getHeaderFlag());
|
||||
if (StringUtils.isNotBlank(headerValue)) {
|
||||
// 请求解密
|
||||
requestWrapper = new DecryptRequestBodyWrapper(servletRequest, properties.getPrivateKey(), properties.getHeaderFlag());
|
||||
} else {
|
||||
// 是否有注解,有就报错,没有放行
|
||||
if (ObjectUtil.isNotNull(apiEncrypt)) {
|
||||
HandlerExceptionResolver exceptionResolver = SpringUtils.getBean("handlerExceptionResolver", HandlerExceptionResolver.class);
|
||||
exceptionResolver.resolveException(
|
||||
servletRequest, servletResponse, null,
|
||||
new ServiceException("没有访问权限,请联系管理员授权", HttpStatus.FORBIDDEN));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 判断是否响应加密
|
||||
if (responseFlag) {
|
||||
responseBodyWrapper = new EncryptResponseBodyWrapper(servletResponse);
|
||||
responseWrapper = responseBodyWrapper;
|
||||
}
|
||||
|
||||
chain.doFilter(
|
||||
ObjectUtil.defaultIfNull(requestWrapper, request),
|
||||
ObjectUtil.defaultIfNull(responseWrapper, response));
|
||||
|
||||
if (encryptFlag) {
|
||||
if (responseFlag) {
|
||||
servletResponse.reset();
|
||||
// 对原始内容加密
|
||||
String encryptContent = responseBodyWrapper.getEncryptContent(
|
||||
|
@ -76,6 +76,7 @@ public class EncryptResponseBodyWrapper extends HttpServletResponseWrapper {
|
||||
String encryptPassword = EncryptUtils.encryptByRsa(encryptAes, publicKey);
|
||||
|
||||
// 设置响应头
|
||||
servletResponse.addHeader("Access-Control-Expose-Headers", headerFlag);
|
||||
servletResponse.setHeader(headerFlag, encryptPassword);
|
||||
servletResponse.setHeader("Access-Control-Allow-Origin", "*");
|
||||
servletResponse.setHeader("Access-Control-Allow-Methods", "*");
|
||||
|
@ -73,7 +73,11 @@ public class MybatisDecryptInterceptor implements Interceptor {
|
||||
list.forEach(this::decryptHandler);
|
||||
return;
|
||||
}
|
||||
// 不在缓存中的类,就是没有加密注解的类(当然也有可能是typeAliasesPackage写错)
|
||||
Set<Field> fields = encryptorManager.getFieldCache(sourceObject.getClass());
|
||||
if(ObjectUtil.isNull(fields)){
|
||||
return;
|
||||
}
|
||||
try {
|
||||
for (Field field : fields) {
|
||||
field.set(sourceObject, this.decryptField(Convert.toStr(field.get(sourceObject)), field));
|
||||
|
@ -82,7 +82,11 @@ public class MybatisEncryptInterceptor implements Interceptor {
|
||||
list.forEach(this::encryptHandler);
|
||||
return;
|
||||
}
|
||||
// 不在缓存中的类,就是没有加密注解的类(当然也有可能是typeAliasesPackage写错)
|
||||
Set<Field> fields = encryptorManager.getFieldCache(sourceObject.getClass());
|
||||
if(ObjectUtil.isNull(fields)){
|
||||
return;
|
||||
}
|
||||
try {
|
||||
for (Field field : fields) {
|
||||
field.set(sourceObject, this.encryptField(Convert.toStr(field.get(sourceObject)), field));
|
||||
|
@ -25,6 +25,11 @@
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>easyexcel</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<artifactId>commons-compress</artifactId>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<version>1.26.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
@ -21,4 +21,9 @@ public @interface CellMerge {
|
||||
*/
|
||||
int index() default -1;
|
||||
|
||||
/**
|
||||
* 合并需要依赖的其他字段名称
|
||||
*/
|
||||
String[] mergeBy() default {};
|
||||
|
||||
}
|
||||
|
@ -1,8 +1,12 @@
|
||||
package org.dromara.common.excel.core;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ReflectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.excel.annotation.ExcelProperty;
|
||||
import com.alibaba.excel.metadata.Head;
|
||||
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
|
||||
import com.alibaba.excel.write.handler.context.WorkbookWriteHandlerContext;
|
||||
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
@ -15,10 +19,7 @@ import org.dromara.common.core.utils.reflect.ReflectUtils;
|
||||
import org.dromara.common.excel.annotation.CellMerge;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 列值重复合并策略
|
||||
@ -26,7 +27,7 @@ import java.util.Map;
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
public class CellMergeStrategy extends AbstractMergeStrategy {
|
||||
public class CellMergeStrategy extends AbstractMergeStrategy implements WorkbookWriteHandler {
|
||||
|
||||
private final List<CellRangeAddress> cellList;
|
||||
private final boolean hasTitle;
|
||||
@ -41,17 +42,28 @@ public class CellMergeStrategy extends AbstractMergeStrategy {
|
||||
|
||||
@Override
|
||||
protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
|
||||
// judge the list is not null
|
||||
if (CollUtil.isNotEmpty(cellList)) {
|
||||
// the judge is necessary
|
||||
if (cell.getRowIndex() == rowIndex && cell.getColumnIndex() == 0) {
|
||||
for (CellRangeAddress item : cellList) {
|
||||
sheet.addMergedRegion(item);
|
||||
//单元格写入了,遍历合并区域,如果该Cell在区域内,但非首行,则清空
|
||||
final int rowIndex = cell.getRowIndex();
|
||||
if (CollUtil.isNotEmpty(cellList)){
|
||||
for (CellRangeAddress cellAddresses : cellList) {
|
||||
final int firstRow = cellAddresses.getFirstRow();
|
||||
if (cellAddresses.isInRange(cell) && rowIndex != firstRow){
|
||||
cell.setBlank();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterWorkbookDispose(final WorkbookWriteHandlerContext context) {
|
||||
//当前表格写完后,统一写入
|
||||
if (CollUtil.isNotEmpty(cellList)){
|
||||
for (CellRangeAddress item : cellList) {
|
||||
context.getWriteContext().writeSheetHolder().getSheet().addMergedRegion(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private List<CellRangeAddress> handle(List<?> list, boolean hasTitle) {
|
||||
List<CellRangeAddress> cellList = new ArrayList<>();
|
||||
@ -93,36 +105,21 @@ public class CellMergeStrategy extends AbstractMergeStrategy {
|
||||
// 空值跳过不合并
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!cellValue.equals(val)) {
|
||||
if (i - repeatCell.getCurrent() > 1) {
|
||||
if ((i - repeatCell.getCurrent() > 1)) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex - 1, colNum, colNum));
|
||||
}
|
||||
map.put(field, new RepeatCell(val, i));
|
||||
} else if (j == 0) {
|
||||
if (i == list.size() - 1) {
|
||||
if (i > repeatCell.getCurrent()) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex, colNum, colNum));
|
||||
}
|
||||
} else if (i == list.size() - 1) {
|
||||
if (i > repeatCell.getCurrent() && isMerge(list, i, field)) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex, colNum, colNum));
|
||||
}
|
||||
} else {
|
||||
// 判断前面的是否合并了
|
||||
RepeatCell firstCell = map.get(mergeFields.get(0));
|
||||
if (repeatCell.getCurrent() != firstCell.getCurrent()) {
|
||||
if (i == list.size() - 1) {
|
||||
if (i > repeatCell.getCurrent()) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex, colNum, colNum));
|
||||
}
|
||||
} else if (repeatCell.getCurrent() < firstCell.getCurrent()) {
|
||||
if (i - repeatCell.getCurrent() > 1) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex - 1, colNum, colNum));
|
||||
}
|
||||
map.put(field, new RepeatCell(val, i));
|
||||
}
|
||||
} else if (i == list.size() - 1) {
|
||||
if (i > repeatCell.getCurrent()) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex, colNum, colNum));
|
||||
}
|
||||
} else if (!isMerge(list, i, field)) {
|
||||
if ((i - repeatCell.getCurrent() > 1)) {
|
||||
cellList.add(new CellRangeAddress(repeatCell.getCurrent() + rowIndex, i + rowIndex - 1, colNum, colNum));
|
||||
}
|
||||
map.put(field, new RepeatCell(val, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -130,6 +127,24 @@ public class CellMergeStrategy extends AbstractMergeStrategy {
|
||||
return cellList;
|
||||
}
|
||||
|
||||
private boolean isMerge(List<?> list, int i, Field field) {
|
||||
boolean isMerge = true;
|
||||
CellMerge cm = field.getAnnotation(CellMerge.class);
|
||||
final String[] mergeBy = cm.mergeBy();
|
||||
if (StrUtil.isAllNotBlank(mergeBy)) {
|
||||
//比对当前list(i)和list(i - 1)的各个属性值一一比对 如果全为真 则为真
|
||||
for (String fieldName : mergeBy) {
|
||||
final Object valCurrent = ReflectUtil.getFieldValue(list.get(i), fieldName);
|
||||
final Object valPre = ReflectUtil.getFieldValue(list.get(i - 1), fieldName);
|
||||
if (!Objects.equals(valPre, valCurrent)) {
|
||||
//依赖字段如有任一不等值,则标记为不可合并
|
||||
isMerge = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return isMerge;
|
||||
}
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
static class RepeatCell {
|
||||
|
@ -20,6 +20,7 @@ import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.service.DictService;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.dromara.common.core.utils.StreamUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.excel.annotation.ExcelDictFormat;
|
||||
import org.dromara.common.excel.annotation.ExcelEnumFormat;
|
||||
|
||||
@ -99,15 +100,16 @@ public class ExcelDownHandler implements SheetWriteHandler {
|
||||
ExcelDictFormat format = field.getDeclaredAnnotation(ExcelDictFormat.class);
|
||||
String dictType = format.dictType();
|
||||
String converterExp = format.readConverterExp();
|
||||
if (StrUtil.isNotBlank(dictType)) {
|
||||
if (StringUtils.isNotBlank(dictType)) {
|
||||
// 如果传递了字典名,则依据字典建立下拉
|
||||
Collection<String> values = Optional.ofNullable(dictService.getAllDictByDictType(dictType))
|
||||
.orElseThrow(() -> new ServiceException(String.format("字典 %s 不存在", dictType)))
|
||||
.values();
|
||||
options = new ArrayList<>(values);
|
||||
} else if (StrUtil.isNotBlank(converterExp)) {
|
||||
} else if (StringUtils.isNotBlank(converterExp)) {
|
||||
// 如果指定了确切的值,则直接解析确切的值
|
||||
options = StrUtil.split(converterExp, format.separator(), true, true);
|
||||
List<String> strList = StringUtils.splitList(converterExp, format.separator());
|
||||
options = StreamUtils.toList(strList, s -> StringUtils.split(s, "=")[1]);
|
||||
}
|
||||
} else if (field.isAnnotationPresent(ExcelEnumFormat.class)) {
|
||||
// 否则如果指定了@ExcelEnumFormat,则使用枚举的逻辑
|
||||
|
@ -4,6 +4,13 @@ import cn.dev33.satoken.SaManager;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.crypto.SecureUtil;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.AfterReturning;
|
||||
import org.aspectj.lang.annotation.AfterThrowing;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.dromara.common.core.constant.GlobalConstants;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
@ -13,13 +20,6 @@ import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.idempotent.annotation.RepeatSubmit;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.AfterReturning;
|
||||
import org.aspectj.lang.annotation.AfterThrowing;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@ -127,7 +127,7 @@ public class RepeatSubmitAspect {
|
||||
public boolean isFilterObject(final Object o) {
|
||||
Class<?> clazz = o.getClass();
|
||||
if (clazz.isArray()) {
|
||||
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
|
||||
return MultipartFile.class.isAssignableFrom(clazz.getComponentType());
|
||||
} else if (Collection.class.isAssignableFrom(clazz)) {
|
||||
Collection collection = (Collection) o;
|
||||
for (Object value : collection) {
|
||||
|
@ -22,20 +22,14 @@
|
||||
<artifactId>spring-boot-autoconfigure</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--PowerJob-->
|
||||
<!-- SnailJob client -->
|
||||
<dependency>
|
||||
<groupId>tech.powerjob</groupId>
|
||||
<artifactId>powerjob-worker-spring-boot-starter</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>powerjob-remote-impl-akka</artifactId>
|
||||
<groupId>tech.powerjob</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
<groupId>com.aizuda</groupId>
|
||||
<artifactId>snail-job-client-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>tech.powerjob</groupId>
|
||||
<artifactId>powerjob-official-processors</artifactId>
|
||||
<groupId>com.aizuda</groupId>
|
||||
<artifactId>snail-job-client-job-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
@ -1,21 +0,0 @@
|
||||
package org.dromara.common.job.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import tech.powerjob.worker.PowerJobWorker;
|
||||
|
||||
/**
|
||||
* 启动定时任务
|
||||
* @author yhan219
|
||||
* @since 2023/6/2
|
||||
*/
|
||||
@Configuration
|
||||
@ConditionalOnBean(PowerJobWorker.class)
|
||||
@ConditionalOnProperty(prefix = "powerjob.worker", name = "enabled", havingValue = "true")
|
||||
@EnableScheduling
|
||||
public class PowerJobConfig {
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package org.dromara.common.job.config;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import com.aizuda.snailjob.client.common.appender.SnailLogbackAppender;
|
||||
import com.aizuda.snailjob.client.common.event.SnailClientStartingEvent;
|
||||
import com.aizuda.snailjob.client.starter.EnableSnailJob;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/**
|
||||
* 启动定时任务
|
||||
*
|
||||
* @author opensnail
|
||||
* @date 2024-05-17
|
||||
*/
|
||||
@AutoConfiguration
|
||||
@ConditionalOnProperty(prefix = "snail-job", name = "enabled", havingValue = "true")
|
||||
@EnableScheduling
|
||||
@EnableSnailJob
|
||||
public class SnailJobConfig {
|
||||
|
||||
@EventListener(SnailClientStartingEvent.class)
|
||||
public void onStarting(SnailClientStartingEvent event) {
|
||||
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
|
||||
SnailLogbackAppender<ILoggingEvent> ca = new SnailLogbackAppender<>();
|
||||
ca.setName("snail_log_appender");
|
||||
ca.start();
|
||||
Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
rootLogger.addAppender(ca);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1 @@
|
||||
org.dromara.common.job.config.SnailJobConfig
|
@ -7,10 +7,10 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
@ -30,6 +30,13 @@ public class JsonUtils {
|
||||
return OBJECT_MAPPER;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象转换为JSON格式的字符串
|
||||
*
|
||||
* @param object 要转换的对象
|
||||
* @return JSON格式的字符串,如果对象为null,则返回null
|
||||
* @throws RuntimeException 如果转换过程中发生JSON处理异常,则抛出运行时异常
|
||||
*/
|
||||
public static String toJsonString(Object object) {
|
||||
if (ObjectUtil.isNull(object)) {
|
||||
return null;
|
||||
@ -41,6 +48,15 @@ public class JsonUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON格式的字符串转换为指定类型的对象
|
||||
*
|
||||
* @param text JSON格式的字符串
|
||||
* @param clazz 要转换的目标对象类型
|
||||
* @param <T> 目标对象的泛型类型
|
||||
* @return 转换后的对象,如果字符串为空则返回null
|
||||
* @throws RuntimeException 如果转换过程中发生IO异常,则抛出运行时异常
|
||||
*/
|
||||
public static <T> T parseObject(String text, Class<T> clazz) {
|
||||
if (StringUtils.isEmpty(text)) {
|
||||
return null;
|
||||
@ -52,6 +68,15 @@ public class JsonUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字节数组转换为指定类型的对象
|
||||
*
|
||||
* @param bytes 字节数组
|
||||
* @param clazz 要转换的目标对象类型
|
||||
* @param <T> 目标对象的泛型类型
|
||||
* @return 转换后的对象,如果字节数组为空则返回null
|
||||
* @throws RuntimeException 如果转换过程中发生IO异常,则抛出运行时异常
|
||||
*/
|
||||
public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
|
||||
if (ArrayUtil.isEmpty(bytes)) {
|
||||
return null;
|
||||
@ -63,6 +88,15 @@ public class JsonUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON格式的字符串转换为指定类型的对象,支持复杂类型
|
||||
*
|
||||
* @param text JSON格式的字符串
|
||||
* @param typeReference 指定类型的TypeReference对象
|
||||
* @param <T> 目标对象的泛型类型
|
||||
* @return 转换后的对象,如果字符串为空则返回null
|
||||
* @throws RuntimeException 如果转换过程中发生IO异常,则抛出运行时异常
|
||||
*/
|
||||
public static <T> T parseObject(String text, TypeReference<T> typeReference) {
|
||||
if (StringUtils.isBlank(text)) {
|
||||
return null;
|
||||
@ -74,6 +108,13 @@ public class JsonUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON格式的字符串转换为Dict对象
|
||||
*
|
||||
* @param text JSON格式的字符串
|
||||
* @return 转换后的Dict对象,如果字符串为空或者不是JSON格式则返回null
|
||||
* @throws RuntimeException 如果转换过程中发生IO异常,则抛出运行时异常
|
||||
*/
|
||||
public static Dict parseMap(String text) {
|
||||
if (StringUtils.isBlank(text)) {
|
||||
return null;
|
||||
@ -88,6 +129,13 @@ public class JsonUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON格式的字符串转换为Dict对象的列表
|
||||
*
|
||||
* @param text JSON格式的字符串
|
||||
* @return 转换后的Dict对象的列表,如果字符串为空则返回null
|
||||
* @throws RuntimeException 如果转换过程中发生IO异常,则抛出运行时异常
|
||||
*/
|
||||
public static List<Dict> parseArrayMap(String text) {
|
||||
if (StringUtils.isBlank(text)) {
|
||||
return null;
|
||||
@ -99,6 +147,15 @@ public class JsonUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON格式的字符串转换为指定类型对象的列表
|
||||
*
|
||||
* @param text JSON格式的字符串
|
||||
* @param clazz 要转换的目标对象类型
|
||||
* @param <T> 目标对象的泛型类型
|
||||
* @return 转换后的对象的列表,如果字符串为空则返回空列表
|
||||
* @throws RuntimeException 如果转换过程中发生IO异常,则抛出运行时异常
|
||||
*/
|
||||
public static <T> List<T> parseArray(String text, Class<T> clazz) {
|
||||
if (StringUtils.isEmpty(text)) {
|
||||
return new ArrayList<>();
|
||||
|
@ -27,11 +27,6 @@
|
||||
<artifactId>ruoyi-common-json</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>transmittable-thread-local</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
@ -4,16 +4,6 @@ import cn.hutool.core.lang.Dict;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.alibaba.ttl.TransmittableThreadLocal;
|
||||
import org.dromara.common.core.domain.model.LoginUser;
|
||||
import org.dromara.common.core.utils.ServletUtils;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessStatus;
|
||||
import org.dromara.common.log.event.OperLogEvent;
|
||||
import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@ -23,6 +13,15 @@ import org.aspectj.lang.annotation.AfterReturning;
|
||||
import org.aspectj.lang.annotation.AfterThrowing;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.dromara.common.core.domain.model.LoginUser;
|
||||
import org.dromara.common.core.utils.ServletUtils;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessStatus;
|
||||
import org.dromara.common.log.event.OperLogEvent;
|
||||
import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.validation.BindingResult;
|
||||
@ -49,17 +48,17 @@ public class LogAspect {
|
||||
|
||||
|
||||
/**
|
||||
* 计算操作消耗时间
|
||||
* 计时 key
|
||||
*/
|
||||
private static final ThreadLocal<StopWatch> TIME_THREADLOCAL = new TransmittableThreadLocal<>();
|
||||
private static final ThreadLocal<StopWatch> KEY_CACHE = new ThreadLocal<>();
|
||||
|
||||
/**
|
||||
* 处理请求前执行
|
||||
*/
|
||||
@Before(value = "@annotation(controllerLog)")
|
||||
public void boBefore(JoinPoint joinPoint, Log controllerLog) {
|
||||
public void doBefore(JoinPoint joinPoint, Log controllerLog) {
|
||||
StopWatch stopWatch = new StopWatch();
|
||||
TIME_THREADLOCAL.set(stopWatch);
|
||||
KEY_CACHE.set(stopWatch);
|
||||
stopWatch.start();
|
||||
}
|
||||
|
||||
@ -112,7 +111,7 @@ public class LogAspect {
|
||||
// 处理设置注解上的参数
|
||||
getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);
|
||||
// 设置消耗时间
|
||||
StopWatch stopWatch = TIME_THREADLOCAL.get();
|
||||
StopWatch stopWatch = KEY_CACHE.get();
|
||||
stopWatch.stop();
|
||||
operLog.setCostTime(stopWatch.getTime());
|
||||
// 发布事件保存数据库
|
||||
@ -122,7 +121,7 @@ public class LogAspect {
|
||||
log.error("异常信息:{}", exp.getMessage());
|
||||
exp.printStackTrace();
|
||||
} finally {
|
||||
TIME_THREADLOCAL.remove();
|
||||
KEY_CACHE.remove();
|
||||
}
|
||||
}
|
||||
|
||||
@ -204,7 +203,7 @@ public class LogAspect {
|
||||
public boolean isFilterObject(final Object o) {
|
||||
Class<?> clazz = o.getClass();
|
||||
if (clazz.isArray()) {
|
||||
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
|
||||
return MultipartFile.class.isAssignableFrom(clazz.getComponentType());
|
||||
} else if (Collection.class.isAssignableFrom(clazz)) {
|
||||
Collection collection = (Collection) o;
|
||||
for (Object value : collection) {
|
||||
|
@ -1,7 +1,7 @@
|
||||
package org.dromara.common.mail.config;
|
||||
|
||||
import cn.hutool.extra.mail.MailAccount;
|
||||
import org.dromara.common.mail.config.properties.MailProperties;
|
||||
import org.dromara.common.mail.utils.MailAccount;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
|
@ -1,46 +0,0 @@
|
||||
package org.dromara.common.mail.utils;
|
||||
|
||||
import cn.hutool.core.io.IORuntimeException;
|
||||
|
||||
/**
|
||||
* 全局邮件帐户,依赖于邮件配置文件{@link MailAccount#MAIL_SETTING_PATHS}
|
||||
*
|
||||
* @author looly
|
||||
*/
|
||||
public enum GlobalMailAccount {
|
||||
INSTANCE;
|
||||
|
||||
private final MailAccount mailAccount;
|
||||
|
||||
/**
|
||||
* 构造
|
||||
*/
|
||||
GlobalMailAccount() {
|
||||
mailAccount = createDefaultAccount();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得邮件帐户
|
||||
*
|
||||
* @return 邮件帐户
|
||||
*/
|
||||
public MailAccount getAccount() {
|
||||
return this.mailAccount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建默认帐户
|
||||
*
|
||||
* @return MailAccount
|
||||
*/
|
||||
private MailAccount createDefaultAccount() {
|
||||
for (String mailSettingPath : MailAccount.MAIL_SETTING_PATHS) {
|
||||
try {
|
||||
return new MailAccount(mailSettingPath);
|
||||
} catch (IORuntimeException ignore) {
|
||||
//ignore
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
@ -1,108 +0,0 @@
|
||||
package org.dromara.common.mail.utils;
|
||||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import jakarta.mail.internet.AddressException;
|
||||
import jakarta.mail.internet.InternetAddress;
|
||||
import jakarta.mail.internet.MimeUtility;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 邮件内部工具类
|
||||
*
|
||||
* @author looly
|
||||
* @since 3.2.3
|
||||
*/
|
||||
public class InternalMailUtil {
|
||||
|
||||
/**
|
||||
* 将多个字符串邮件地址转为{@link InternetAddress}列表<br>
|
||||
* 单个字符串地址可以是多个地址合并的字符串
|
||||
*
|
||||
* @param addrStrs 地址数组
|
||||
* @param charset 编码(主要用于中文用户名的编码)
|
||||
* @return 地址数组
|
||||
* @since 4.0.3
|
||||
*/
|
||||
public static InternetAddress[] parseAddressFromStrs(String[] addrStrs, Charset charset) {
|
||||
final List<InternetAddress> resultList = new ArrayList<>(addrStrs.length);
|
||||
InternetAddress[] addrs;
|
||||
for (String addrStr : addrStrs) {
|
||||
addrs = parseAddress(addrStr, charset);
|
||||
if (ArrayUtil.isNotEmpty(addrs)) {
|
||||
Collections.addAll(resultList, addrs);
|
||||
}
|
||||
}
|
||||
return resultList.toArray(new InternetAddress[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析第一个地址
|
||||
*
|
||||
* @param address 地址字符串
|
||||
* @param charset 编码,{@code null}表示使用系统属性定义的编码或系统编码
|
||||
* @return 地址列表
|
||||
*/
|
||||
public static InternetAddress parseFirstAddress(String address, Charset charset) {
|
||||
final InternetAddress[] internetAddresses = parseAddress(address, charset);
|
||||
if (ArrayUtil.isEmpty(internetAddresses)) {
|
||||
try {
|
||||
return new InternetAddress(address);
|
||||
} catch (AddressException e) {
|
||||
throw new MailException(e);
|
||||
}
|
||||
}
|
||||
return internetAddresses[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 将一个地址字符串解析为多个地址<br>
|
||||
* 地址间使用" "、","、";"分隔
|
||||
*
|
||||
* @param address 地址字符串
|
||||
* @param charset 编码,{@code null}表示使用系统属性定义的编码或系统编码
|
||||
* @return 地址列表
|
||||
*/
|
||||
public static InternetAddress[] parseAddress(String address, Charset charset) {
|
||||
InternetAddress[] addresses;
|
||||
try {
|
||||
addresses = InternetAddress.parse(address);
|
||||
} catch (AddressException e) {
|
||||
throw new MailException(e);
|
||||
}
|
||||
//编码用户名
|
||||
if (ArrayUtil.isNotEmpty(addresses)) {
|
||||
final String charsetStr = null == charset ? null : charset.name();
|
||||
for (InternetAddress internetAddress : addresses) {
|
||||
try {
|
||||
internetAddress.setPersonal(internetAddress.getPersonal(), charsetStr);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new MailException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return addresses;
|
||||
}
|
||||
|
||||
/**
|
||||
* 编码中文字符<br>
|
||||
* 编码失败返回原字符串
|
||||
*
|
||||
* @param text 被编码的文本
|
||||
* @param charset 编码
|
||||
* @return 编码后的结果
|
||||
*/
|
||||
public static String encodeText(String text, Charset charset) {
|
||||
try {
|
||||
return MimeUtility.encodeText(text, charset.name(), null);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
// ignore
|
||||
}
|
||||
return text;
|
||||
}
|
||||
}
|
@ -1,483 +0,0 @@
|
||||
package org.dromara.common.mail.utils;
|
||||
|
||||
import cn.hutool.core.builder.Builder;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.io.IORuntimeException;
|
||||
import cn.hutool.core.io.IoUtil;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import jakarta.activation.DataHandler;
|
||||
import jakarta.activation.DataSource;
|
||||
import jakarta.activation.FileDataSource;
|
||||
import jakarta.activation.FileTypeMap;
|
||||
import jakarta.mail.*;
|
||||
import jakarta.mail.internet.MimeBodyPart;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import jakarta.mail.internet.MimeMultipart;
|
||||
import jakarta.mail.internet.MimeUtility;
|
||||
import jakarta.mail.util.ByteArrayDataSource;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 邮件发送客户端
|
||||
*
|
||||
* @author looly
|
||||
* @since 3.2.0
|
||||
*/
|
||||
public class Mail implements Builder<MimeMessage> {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 邮箱帐户信息以及一些客户端配置信息
|
||||
*/
|
||||
private final MailAccount mailAccount;
|
||||
/**
|
||||
* 收件人列表
|
||||
*/
|
||||
private String[] tos;
|
||||
/**
|
||||
* 抄送人列表(carbon copy)
|
||||
*/
|
||||
private String[] ccs;
|
||||
/**
|
||||
* 密送人列表(blind carbon copy)
|
||||
*/
|
||||
private String[] bccs;
|
||||
/**
|
||||
* 回复地址(reply-to)
|
||||
*/
|
||||
private String[] reply;
|
||||
/**
|
||||
* 标题
|
||||
*/
|
||||
private String title;
|
||||
/**
|
||||
* 内容
|
||||
*/
|
||||
private String content;
|
||||
/**
|
||||
* 是否为HTML
|
||||
*/
|
||||
private boolean isHtml;
|
||||
/**
|
||||
* 正文、附件和图片的混合部分
|
||||
*/
|
||||
private final Multipart multipart = new MimeMultipart();
|
||||
/**
|
||||
* 是否使用全局会话,默认为false
|
||||
*/
|
||||
private boolean useGlobalSession = false;
|
||||
|
||||
/**
|
||||
* debug输出位置,可以自定义debug日志
|
||||
*/
|
||||
private PrintStream debugOutput;
|
||||
|
||||
/**
|
||||
* 创建邮件客户端
|
||||
*
|
||||
* @param mailAccount 邮件帐号
|
||||
* @return Mail
|
||||
*/
|
||||
public static Mail create(MailAccount mailAccount) {
|
||||
return new Mail(mailAccount);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建邮件客户端,使用全局邮件帐户
|
||||
*
|
||||
* @return Mail
|
||||
*/
|
||||
public static Mail create() {
|
||||
return new Mail();
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- Constructor start
|
||||
|
||||
/**
|
||||
* 构造,使用全局邮件帐户
|
||||
*/
|
||||
public Mail() {
|
||||
this(GlobalMailAccount.INSTANCE.getAccount());
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造
|
||||
*
|
||||
* @param mailAccount 邮件帐户,如果为null使用默认配置文件的全局邮件配置
|
||||
*/
|
||||
public Mail(MailAccount mailAccount) {
|
||||
mailAccount = (null != mailAccount) ? mailAccount : GlobalMailAccount.INSTANCE.getAccount();
|
||||
this.mailAccount = mailAccount.defaultIfEmpty();
|
||||
}
|
||||
// --------------------------------------------------------------- Constructor end
|
||||
|
||||
// --------------------------------------------------------------- Getters and Setters start
|
||||
|
||||
/**
|
||||
* 设置收件人
|
||||
*
|
||||
* @param tos 收件人列表
|
||||
* @return this
|
||||
* @see #setTos(String...)
|
||||
*/
|
||||
public Mail to(String... tos) {
|
||||
return setTos(tos);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置多个收件人
|
||||
*
|
||||
* @param tos 收件人列表
|
||||
* @return this
|
||||
*/
|
||||
public Mail setTos(String... tos) {
|
||||
this.tos = tos;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置多个抄送人(carbon copy)
|
||||
*
|
||||
* @param ccs 抄送人列表
|
||||
* @return this
|
||||
* @since 4.0.3
|
||||
*/
|
||||
public Mail setCcs(String... ccs) {
|
||||
this.ccs = ccs;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置多个密送人(blind carbon copy)
|
||||
*
|
||||
* @param bccs 密送人列表
|
||||
* @return this
|
||||
* @since 4.0.3
|
||||
*/
|
||||
public Mail setBccs(String... bccs) {
|
||||
this.bccs = bccs;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置多个回复地址(reply-to)
|
||||
*
|
||||
* @param reply 回复地址(reply-to)列表
|
||||
* @return this
|
||||
* @since 4.6.0
|
||||
*/
|
||||
public Mail setReply(String... reply) {
|
||||
this.reply = reply;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置标题
|
||||
*
|
||||
* @param title 标题
|
||||
* @return this
|
||||
*/
|
||||
public Mail setTitle(String title) {
|
||||
this.title = title;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置正文<br>
|
||||
* 正文可以是普通文本也可以是HTML(默认普通文本),可以通过调用{@link #setHtml(boolean)} 设置是否为HTML
|
||||
*
|
||||
* @param content 正文
|
||||
* @return this
|
||||
*/
|
||||
public Mail setContent(String content) {
|
||||
this.content = content;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置是否是HTML
|
||||
*
|
||||
* @param isHtml 是否为HTML
|
||||
* @return this
|
||||
*/
|
||||
public Mail setHtml(boolean isHtml) {
|
||||
this.isHtml = isHtml;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置正文
|
||||
*
|
||||
* @param content 正文内容
|
||||
* @param isHtml 是否为HTML
|
||||
* @return this
|
||||
*/
|
||||
public Mail setContent(String content, boolean isHtml) {
|
||||
setContent(content);
|
||||
return setHtml(isHtml);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置文件类型附件,文件可以是图片文件,此时自动设置cid(正文中引用图片),默认cid为文件名
|
||||
*
|
||||
* @param files 附件文件列表
|
||||
* @return this
|
||||
*/
|
||||
public Mail setFiles(File... files) {
|
||||
if (ArrayUtil.isEmpty(files)) {
|
||||
return this;
|
||||
}
|
||||
|
||||
final DataSource[] attachments = new DataSource[files.length];
|
||||
for (int i = 0; i < files.length; i++) {
|
||||
attachments[i] = new FileDataSource(files[i]);
|
||||
}
|
||||
return setAttachments(attachments);
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加附件或图片,附件使用{@link DataSource} 形式表示,可以使用{@link FileDataSource}包装文件表示文件附件
|
||||
*
|
||||
* @param attachments 附件列表
|
||||
* @return this
|
||||
* @since 4.0.9
|
||||
*/
|
||||
public Mail setAttachments(DataSource... attachments) {
|
||||
if (ArrayUtil.isNotEmpty(attachments)) {
|
||||
final Charset charset = this.mailAccount.getCharset();
|
||||
MimeBodyPart bodyPart;
|
||||
String nameEncoded;
|
||||
try {
|
||||
for (DataSource attachment : attachments) {
|
||||
bodyPart = new MimeBodyPart();
|
||||
bodyPart.setDataHandler(new DataHandler(attachment));
|
||||
nameEncoded = attachment.getName();
|
||||
if (this.mailAccount.isEncodefilename()) {
|
||||
nameEncoded = InternalMailUtil.encodeText(nameEncoded, charset);
|
||||
}
|
||||
// 普通附件文件名
|
||||
bodyPart.setFileName(nameEncoded);
|
||||
if (StrUtil.startWith(attachment.getContentType(), "image/")) {
|
||||
// 图片附件,用于正文中引用图片
|
||||
bodyPart.setContentID(nameEncoded);
|
||||
}
|
||||
this.multipart.addBodyPart(bodyPart);
|
||||
}
|
||||
} catch (MessagingException e) {
|
||||
throw new MailException(e);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加图片,图片的键对应到邮件模板中的占位字符串,图片类型默认为"image/jpeg"
|
||||
*
|
||||
* @param cid 图片与占位符,占位符格式为cid:${cid}
|
||||
* @param imageStream 图片文件
|
||||
* @return this
|
||||
* @since 4.6.3
|
||||
*/
|
||||
public Mail addImage(String cid, InputStream imageStream) {
|
||||
return addImage(cid, imageStream, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加图片,图片的键对应到邮件模板中的占位字符串
|
||||
*
|
||||
* @param cid 图片与占位符,占位符格式为cid:${cid}
|
||||
* @param imageStream 图片流,不关闭
|
||||
* @param contentType 图片类型,null赋值默认的"image/jpeg"
|
||||
* @return this
|
||||
* @since 4.6.3
|
||||
*/
|
||||
public Mail addImage(String cid, InputStream imageStream, String contentType) {
|
||||
ByteArrayDataSource imgSource;
|
||||
try {
|
||||
imgSource = new ByteArrayDataSource(imageStream, ObjectUtil.defaultIfNull(contentType, "image/jpeg"));
|
||||
} catch (IOException e) {
|
||||
throw new IORuntimeException(e);
|
||||
}
|
||||
imgSource.setName(cid);
|
||||
return setAttachments(imgSource);
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加图片,图片的键对应到邮件模板中的占位字符串
|
||||
*
|
||||
* @param cid 图片与占位符,占位符格式为cid:${cid}
|
||||
* @param imageFile 图片文件
|
||||
* @return this
|
||||
* @since 4.6.3
|
||||
*/
|
||||
public Mail addImage(String cid, File imageFile) {
|
||||
InputStream in = null;
|
||||
try {
|
||||
in = FileUtil.getInputStream(imageFile);
|
||||
return addImage(cid, in, FileTypeMap.getDefaultFileTypeMap().getContentType(imageFile));
|
||||
} finally {
|
||||
IoUtil.close(in);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置字符集编码
|
||||
*
|
||||
* @param charset 字符集编码
|
||||
* @return this
|
||||
* @see MailAccount#setCharset(Charset)
|
||||
*/
|
||||
public Mail setCharset(Charset charset) {
|
||||
this.mailAccount.setCharset(charset);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置是否使用全局会话,默认为true
|
||||
*
|
||||
* @param isUseGlobalSession 是否使用全局会话,默认为true
|
||||
* @return this
|
||||
* @since 4.0.2
|
||||
*/
|
||||
public Mail setUseGlobalSession(boolean isUseGlobalSession) {
|
||||
this.useGlobalSession = isUseGlobalSession;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置debug输出位置,可以自定义debug日志
|
||||
*
|
||||
* @param debugOutput debug输出位置
|
||||
* @return this
|
||||
* @since 5.5.6
|
||||
*/
|
||||
public Mail setDebugOutput(PrintStream debugOutput) {
|
||||
this.debugOutput = debugOutput;
|
||||
return this;
|
||||
}
|
||||
// --------------------------------------------------------------- Getters and Setters end
|
||||
|
||||
@Override
|
||||
public MimeMessage build() {
|
||||
try {
|
||||
return buildMsg();
|
||||
} catch (MessagingException e) {
|
||||
throw new MailException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送
|
||||
*
|
||||
* @return message-id
|
||||
* @throws MailException 邮件发送异常
|
||||
*/
|
||||
public String send() throws MailException {
|
||||
try {
|
||||
return doSend();
|
||||
} catch (MessagingException e) {
|
||||
if (e instanceof SendFailedException) {
|
||||
// 当地址无效时,显示更加详细的无效地址信息
|
||||
final Address[] invalidAddresses = ((SendFailedException) e).getInvalidAddresses();
|
||||
final String msg = StrUtil.format("Invalid Addresses: {}", ArrayUtil.toString(invalidAddresses));
|
||||
throw new MailException(msg, e);
|
||||
}
|
||||
throw new MailException(e);
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- Private method start
|
||||
|
||||
/**
|
||||
* 执行发送
|
||||
*
|
||||
* @return message-id
|
||||
* @throws MessagingException 发送异常
|
||||
*/
|
||||
private String doSend() throws MessagingException {
|
||||
final MimeMessage mimeMessage = buildMsg();
|
||||
Transport.send(mimeMessage);
|
||||
return mimeMessage.getMessageID();
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建消息
|
||||
*
|
||||
* @return {@link MimeMessage}消息
|
||||
* @throws MessagingException 消息异常
|
||||
*/
|
||||
private MimeMessage buildMsg() throws MessagingException {
|
||||
final Charset charset = this.mailAccount.getCharset();
|
||||
final MimeMessage msg = new MimeMessage(getSession());
|
||||
// 发件人
|
||||
final String from = this.mailAccount.getFrom();
|
||||
if (StrUtil.isEmpty(from)) {
|
||||
// 用户未提供发送方,则从Session中自动获取
|
||||
msg.setFrom();
|
||||
} else {
|
||||
msg.setFrom(InternalMailUtil.parseFirstAddress(from, charset));
|
||||
}
|
||||
// 标题
|
||||
msg.setSubject(this.title, (null == charset) ? null : charset.name());
|
||||
// 发送时间
|
||||
msg.setSentDate(new Date());
|
||||
// 内容和附件
|
||||
msg.setContent(buildContent(charset));
|
||||
// 收件人
|
||||
msg.setRecipients(MimeMessage.RecipientType.TO, InternalMailUtil.parseAddressFromStrs(this.tos, charset));
|
||||
// 抄送人
|
||||
if (ArrayUtil.isNotEmpty(this.ccs)) {
|
||||
msg.setRecipients(MimeMessage.RecipientType.CC, InternalMailUtil.parseAddressFromStrs(this.ccs, charset));
|
||||
}
|
||||
// 密送人
|
||||
if (ArrayUtil.isNotEmpty(this.bccs)) {
|
||||
msg.setRecipients(MimeMessage.RecipientType.BCC, InternalMailUtil.parseAddressFromStrs(this.bccs, charset));
|
||||
}
|
||||
// 回复地址(reply-to)
|
||||
if (ArrayUtil.isNotEmpty(this.reply)) {
|
||||
msg.setReplyTo(InternalMailUtil.parseAddressFromStrs(this.reply, charset));
|
||||
}
|
||||
|
||||
return msg;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建邮件信息主体
|
||||
*
|
||||
* @param charset 编码,{@code null}则使用{@link MimeUtility#getDefaultJavaCharset()}
|
||||
* @return 邮件信息主体
|
||||
* @throws MessagingException 消息异常
|
||||
*/
|
||||
private Multipart buildContent(Charset charset) throws MessagingException {
|
||||
final String charsetStr = null != charset ? charset.name() : MimeUtility.getDefaultJavaCharset();
|
||||
// 正文
|
||||
final MimeBodyPart body = new MimeBodyPart();
|
||||
body.setContent(content, StrUtil.format("text/{}; charset={}", isHtml ? "html" : "plain", charsetStr));
|
||||
this.multipart.addBodyPart(body);
|
||||
|
||||
return this.multipart;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取默认邮件会话<br>
|
||||
* 如果为全局单例的会话,则全局只允许一个邮件帐号,否则每次发送邮件会新建一个新的会话
|
||||
*
|
||||
* @return 邮件会话 {@link Session}
|
||||
*/
|
||||
private Session getSession() {
|
||||
final Session session = MailUtils.getSession(this.mailAccount, this.useGlobalSession);
|
||||
|
||||
if (null != this.debugOutput) {
|
||||
session.setDebugOut(debugOutput);
|
||||
}
|
||||
|
||||
return session;
|
||||
}
|
||||
// --------------------------------------------------------------- Private method end
|
||||
}
|
@ -1,659 +0,0 @@
|
||||
package org.dromara.common.mail.utils;
|
||||
|
||||
import cn.hutool.core.util.CharsetUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.setting.Setting;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* 邮件账户对象
|
||||
*
|
||||
* @author Luxiaolei
|
||||
*/
|
||||
public class MailAccount implements Serializable {
|
||||
@Serial
|
||||
private static final long serialVersionUID = -6937313421815719204L;
|
||||
|
||||
private static final String MAIL_PROTOCOL = "mail.transport.protocol";
|
||||
private static final String SMTP_HOST = "mail.smtp.host";
|
||||
private static final String SMTP_PORT = "mail.smtp.port";
|
||||
private static final String SMTP_AUTH = "mail.smtp.auth";
|
||||
private static final String SMTP_TIMEOUT = "mail.smtp.timeout";
|
||||
private static final String SMTP_CONNECTION_TIMEOUT = "mail.smtp.connectiontimeout";
|
||||
private static final String SMTP_WRITE_TIMEOUT = "mail.smtp.writetimeout";
|
||||
|
||||
// SSL
|
||||
private static final String STARTTLS_ENABLE = "mail.smtp.starttls.enable";
|
||||
private static final String SSL_ENABLE = "mail.smtp.ssl.enable";
|
||||
private static final String SSL_PROTOCOLS = "mail.smtp.ssl.protocols";
|
||||
private static final String SOCKET_FACTORY = "mail.smtp.socketFactory.class";
|
||||
private static final String SOCKET_FACTORY_FALLBACK = "mail.smtp.socketFactory.fallback";
|
||||
private static final String SOCKET_FACTORY_PORT = "smtp.socketFactory.port";
|
||||
|
||||
// System Properties
|
||||
private static final String SPLIT_LONG_PARAMS = "mail.mime.splitlongparameters";
|
||||
//private static final String ENCODE_FILE_NAME = "mail.mime.encodefilename";
|
||||
//private static final String CHARSET = "mail.mime.charset";
|
||||
|
||||
// 其他
|
||||
private static final String MAIL_DEBUG = "mail.debug";
|
||||
|
||||
public static final String[] MAIL_SETTING_PATHS = new String[]{"config/mail.setting", "config/mailAccount.setting", "mail.setting"};
|
||||
|
||||
/**
|
||||
* SMTP服务器域名
|
||||
*/
|
||||
private String host;
|
||||
/**
|
||||
* SMTP服务端口
|
||||
*/
|
||||
private Integer port;
|
||||
/**
|
||||
* 是否需要用户名密码验证
|
||||
*/
|
||||
private Boolean auth;
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
private String user;
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
private String pass;
|
||||
/**
|
||||
* 发送方,遵循RFC-822标准
|
||||
*/
|
||||
private String from;
|
||||
|
||||
/**
|
||||
* 是否打开调试模式,调试模式会显示与邮件服务器通信过程,默认不开启
|
||||
*/
|
||||
private boolean debug;
|
||||
/**
|
||||
* 编码用于编码邮件正文和发送人、收件人等中文
|
||||
*/
|
||||
private Charset charset = CharsetUtil.CHARSET_UTF_8;
|
||||
/**
|
||||
* 对于超长参数是否切分为多份,默认为false(国内邮箱附件不支持切分的附件名)
|
||||
*/
|
||||
private boolean splitlongparameters = false;
|
||||
/**
|
||||
* 对于文件名是否使用{@link #charset}编码,默认为 {@code true}
|
||||
*/
|
||||
private boolean encodefilename = true;
|
||||
|
||||
/**
|
||||
* 使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。它将纯文本连接升级为加密连接(TLS或SSL), 而不是使用一个单独的加密通信端口。
|
||||
*/
|
||||
private boolean starttlsEnable = false;
|
||||
/**
|
||||
* 使用 SSL安全连接
|
||||
*/
|
||||
private Boolean sslEnable;
|
||||
|
||||
/**
|
||||
* SSL协议,多个协议用空格分隔
|
||||
*/
|
||||
private String sslProtocols;
|
||||
|
||||
/**
|
||||
* 指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字
|
||||
*/
|
||||
private String socketFactoryClass = "javax.net.ssl.SSLSocketFactory";
|
||||
/**
|
||||
* 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true
|
||||
*/
|
||||
private boolean socketFactoryFallback;
|
||||
/**
|
||||
* 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口
|
||||
*/
|
||||
private int socketFactoryPort = 465;
|
||||
|
||||
/**
|
||||
* SMTP超时时长,单位毫秒,缺省值不超时
|
||||
*/
|
||||
private long timeout;
|
||||
/**
|
||||
* Socket连接超时值,单位毫秒,缺省值不超时
|
||||
*/
|
||||
private long connectionTimeout;
|
||||
/**
|
||||
* Socket写出超时值,单位毫秒,缺省值不超时
|
||||
*/
|
||||
private long writeTimeout;
|
||||
|
||||
/**
|
||||
* 自定义的其他属性,此自定义属性会覆盖默认属性
|
||||
*/
|
||||
private final Map<String, Object> customProperty = new HashMap<>();
|
||||
|
||||
// -------------------------------------------------------------- Constructor start
|
||||
|
||||
/**
|
||||
* 构造,所有参数需自行定义或保持默认值
|
||||
*/
|
||||
public MailAccount() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造
|
||||
*
|
||||
* @param settingPath 配置文件路径
|
||||
*/
|
||||
public MailAccount(String settingPath) {
|
||||
this(new Setting(settingPath));
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造
|
||||
*
|
||||
* @param setting 配置文件
|
||||
*/
|
||||
public MailAccount(Setting setting) {
|
||||
setting.toBean(this);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- Constructor end
|
||||
|
||||
/**
|
||||
* 获得SMTP服务器域名
|
||||
*
|
||||
* @return SMTP服务器域名
|
||||
*/
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置SMTP服务器域名
|
||||
*
|
||||
* @param host SMTP服务器域名
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setHost(String host) {
|
||||
this.host = host;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得SMTP服务端口
|
||||
*
|
||||
* @return SMTP服务端口
|
||||
*/
|
||||
public Integer getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置SMTP服务端口
|
||||
*
|
||||
* @param port SMTP服务端口
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setPort(Integer port) {
|
||||
this.port = port;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否需要用户名密码验证
|
||||
*
|
||||
* @return 是否需要用户名密码验证
|
||||
*/
|
||||
public Boolean isAuth() {
|
||||
return auth;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置是否需要用户名密码验证
|
||||
*
|
||||
* @param isAuth 是否需要用户名密码验证
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setAuth(boolean isAuth) {
|
||||
this.auth = isAuth;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户名
|
||||
*
|
||||
* @return 用户名
|
||||
*/
|
||||
public String getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置用户名
|
||||
*
|
||||
* @param user 用户名
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setUser(String user) {
|
||||
this.user = user;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取密码
|
||||
*
|
||||
* @return 密码
|
||||
*/
|
||||
public String getPass() {
|
||||
return pass;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置密码
|
||||
*
|
||||
* @param pass 密码
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setPass(String pass) {
|
||||
this.pass = pass;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取发送方,遵循RFC-822标准
|
||||
*
|
||||
* @return 发送方,遵循RFC-822标准
|
||||
*/
|
||||
public String getFrom() {
|
||||
return from;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置发送方,遵循RFC-822标准<br>
|
||||
* 发件人可以是以下形式:
|
||||
*
|
||||
* <pre>
|
||||
* 1. user@xxx.xx
|
||||
* 2. name <user@xxx.xx>
|
||||
* </pre>
|
||||
*
|
||||
* @param from 发送方,遵循RFC-822标准
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setFrom(String from) {
|
||||
this.from = from;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否打开调试模式,调试模式会显示与邮件服务器通信过程,默认不开启
|
||||
*
|
||||
* @return 是否打开调试模式,调试模式会显示与邮件服务器通信过程,默认不开启
|
||||
* @since 4.0.2
|
||||
*/
|
||||
public boolean isDebug() {
|
||||
return debug;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置是否打开调试模式,调试模式会显示与邮件服务器通信过程,默认不开启
|
||||
*
|
||||
* @param debug 是否打开调试模式,调试模式会显示与邮件服务器通信过程,默认不开启
|
||||
* @return this
|
||||
* @since 4.0.2
|
||||
*/
|
||||
public MailAccount setDebug(boolean debug) {
|
||||
this.debug = debug;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字符集编码
|
||||
*
|
||||
* @return 编码,可能为{@code null}
|
||||
*/
|
||||
public Charset getCharset() {
|
||||
return charset;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置字符集编码,此选项不会修改全局配置,若修改全局配置,请设置此项为{@code null}并设置:
|
||||
* <pre>
|
||||
* System.setProperty("mail.mime.charset", charset);
|
||||
* </pre>
|
||||
*
|
||||
* @param charset 字符集编码,{@code null} 则表示使用全局设置的默认编码,全局编码为mail.mime.charset系统属性
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setCharset(Charset charset) {
|
||||
this.charset = charset;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对于超长参数是否切分为多份,默认为false(国内邮箱附件不支持切分的附件名)
|
||||
*
|
||||
* @return 对于超长参数是否切分为多份
|
||||
*/
|
||||
public boolean isSplitlongparameters() {
|
||||
return splitlongparameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置对于超长参数是否切分为多份,默认为false(国内邮箱附件不支持切分的附件名)<br>
|
||||
* 注意此项为全局设置,此项会调用
|
||||
* <pre>
|
||||
* System.setProperty("mail.mime.splitlongparameters", true)
|
||||
* </pre>
|
||||
*
|
||||
* @param splitlongparameters 对于超长参数是否切分为多份
|
||||
*/
|
||||
public void setSplitlongparameters(boolean splitlongparameters) {
|
||||
this.splitlongparameters = splitlongparameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对于文件名是否使用{@link #charset}编码,默认为 {@code true}
|
||||
*
|
||||
* @return 对于文件名是否使用{@link #charset}编码,默认为 {@code true}
|
||||
* @since 5.7.16
|
||||
*/
|
||||
public boolean isEncodefilename() {
|
||||
|
||||
return encodefilename;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置对于文件名是否使用{@link #charset}编码,此选项不会修改全局配置<br>
|
||||
* 如果此选项设置为{@code false},则是否编码取决于两个系统属性:
|
||||
* <ul>
|
||||
* <li>mail.mime.encodefilename 是否编码附件文件名</li>
|
||||
* <li>mail.mime.charset 编码文件名的编码</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param encodefilename 对于文件名是否使用{@link #charset}编码
|
||||
* @since 5.7.16
|
||||
*/
|
||||
public void setEncodefilename(boolean encodefilename) {
|
||||
this.encodefilename = encodefilename;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。它将纯文本连接升级为加密连接(TLS或SSL), 而不是使用一个单独的加密通信端口。
|
||||
*
|
||||
* @return 是否使用 STARTTLS安全连接
|
||||
*/
|
||||
public boolean isStarttlsEnable() {
|
||||
return this.starttlsEnable;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置是否使用STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。它将纯文本连接升级为加密连接(TLS或SSL), 而不是使用一个单独的加密通信端口。
|
||||
*
|
||||
* @param startttlsEnable 是否使用STARTTLS安全连接
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setStarttlsEnable(boolean startttlsEnable) {
|
||||
this.starttlsEnable = startttlsEnable;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否使用 SSL安全连接
|
||||
*
|
||||
* @return 是否使用 SSL安全连接
|
||||
*/
|
||||
public Boolean isSslEnable() {
|
||||
return this.sslEnable;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置是否使用SSL安全连接
|
||||
*
|
||||
* @param sslEnable 是否使用SSL安全连接
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setSslEnable(Boolean sslEnable) {
|
||||
this.sslEnable = sslEnable;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取SSL协议,多个协议用空格分隔
|
||||
*
|
||||
* @return SSL协议,多个协议用空格分隔
|
||||
* @since 5.5.7
|
||||
*/
|
||||
public String getSslProtocols() {
|
||||
return sslProtocols;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置SSL协议,多个协议用空格分隔
|
||||
*
|
||||
* @param sslProtocols SSL协议,多个协议用空格分隔
|
||||
* @since 5.5.7
|
||||
*/
|
||||
public void setSslProtocols(String sslProtocols) {
|
||||
this.sslProtocols = sslProtocols;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字
|
||||
*
|
||||
* @return 指定实现javax.net.SocketFactory接口的类的名称, 这个类将被用于创建SMTP的套接字
|
||||
*/
|
||||
public String getSocketFactoryClass() {
|
||||
return socketFactoryClass;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字
|
||||
*
|
||||
* @param socketFactoryClass 指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setSocketFactoryClass(String socketFactoryClass) {
|
||||
this.socketFactoryClass = socketFactoryClass;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true
|
||||
*
|
||||
* @return 如果设置为true, 未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true
|
||||
*/
|
||||
public boolean isSocketFactoryFallback() {
|
||||
return socketFactoryFallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true
|
||||
*
|
||||
* @param socketFactoryFallback 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setSocketFactoryFallback(boolean socketFactoryFallback) {
|
||||
this.socketFactoryFallback = socketFactoryFallback;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口
|
||||
*
|
||||
* @return 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口
|
||||
*/
|
||||
public int getSocketFactoryPort() {
|
||||
return socketFactoryPort;
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口
|
||||
*
|
||||
* @param socketFactoryPort 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount setSocketFactoryPort(int socketFactoryPort) {
|
||||
this.socketFactoryPort = socketFactoryPort;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置SMTP超时时长,单位毫秒,缺省值不超时
|
||||
*
|
||||
* @param timeout SMTP超时时长,单位毫秒,缺省值不超时
|
||||
* @return this
|
||||
* @since 4.1.17
|
||||
*/
|
||||
public MailAccount setTimeout(long timeout) {
|
||||
this.timeout = timeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置Socket连接超时值,单位毫秒,缺省值不超时
|
||||
*
|
||||
* @param connectionTimeout Socket连接超时值,单位毫秒,缺省值不超时
|
||||
* @return this
|
||||
* @since 4.1.17
|
||||
*/
|
||||
public MailAccount setConnectionTimeout(long connectionTimeout) {
|
||||
this.connectionTimeout = connectionTimeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置Socket写出超时值,单位毫秒,缺省值不超时
|
||||
*
|
||||
* @param writeTimeout Socket写出超时值,单位毫秒,缺省值不超时
|
||||
* @return this
|
||||
* @since 5.8.3
|
||||
*/
|
||||
public MailAccount setWriteTimeout(long writeTimeout) {
|
||||
this.writeTimeout = writeTimeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取自定义属性列表
|
||||
*
|
||||
* @return 自定义参数列表
|
||||
* @since 5.6.4
|
||||
*/
|
||||
public Map<String, Object> getCustomProperty() {
|
||||
return customProperty;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置自定义属性,如mail.smtp.ssl.socketFactory
|
||||
*
|
||||
* @param key 属性名,空白被忽略
|
||||
* @param value 属性值, null被忽略
|
||||
* @return this
|
||||
* @since 5.6.4
|
||||
*/
|
||||
public MailAccount setCustomProperty(String key, Object value) {
|
||||
if (StrUtil.isNotBlank(key) && ObjectUtil.isNotNull(value)) {
|
||||
this.customProperty.put(key, value);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得SMTP相关信息
|
||||
*
|
||||
* @return {@link Properties}
|
||||
*/
|
||||
public Properties getSmtpProps() {
|
||||
//全局系统参数
|
||||
System.setProperty(SPLIT_LONG_PARAMS, String.valueOf(this.splitlongparameters));
|
||||
|
||||
final Properties p = new Properties();
|
||||
p.put(MAIL_PROTOCOL, "smtp");
|
||||
p.put(SMTP_HOST, this.host);
|
||||
p.put(SMTP_PORT, String.valueOf(this.port));
|
||||
p.put(SMTP_AUTH, String.valueOf(this.auth));
|
||||
if (this.timeout > 0) {
|
||||
p.put(SMTP_TIMEOUT, String.valueOf(this.timeout));
|
||||
}
|
||||
if (this.connectionTimeout > 0) {
|
||||
p.put(SMTP_CONNECTION_TIMEOUT, String.valueOf(this.connectionTimeout));
|
||||
}
|
||||
// issue#2355
|
||||
if (this.writeTimeout > 0) {
|
||||
p.put(SMTP_WRITE_TIMEOUT, String.valueOf(this.writeTimeout));
|
||||
}
|
||||
|
||||
p.put(MAIL_DEBUG, String.valueOf(this.debug));
|
||||
|
||||
if (this.starttlsEnable) {
|
||||
//STARTTLS是对纯文本通信协议的扩展。它将纯文本连接升级为加密连接(TLS或SSL), 而不是使用一个单独的加密通信端口。
|
||||
p.put(STARTTLS_ENABLE, "true");
|
||||
|
||||
if (null == this.sslEnable) {
|
||||
//为了兼容旧版本,当用户没有此项配置时,按照starttlsEnable开启状态时对待
|
||||
this.sslEnable = true;
|
||||
}
|
||||
}
|
||||
|
||||
// SSL
|
||||
if (null != this.sslEnable && this.sslEnable) {
|
||||
p.put(SSL_ENABLE, "true");
|
||||
p.put(SOCKET_FACTORY, socketFactoryClass);
|
||||
p.put(SOCKET_FACTORY_FALLBACK, String.valueOf(this.socketFactoryFallback));
|
||||
p.put(SOCKET_FACTORY_PORT, String.valueOf(this.socketFactoryPort));
|
||||
// issue#IZN95@Gitee,在Linux下需自定义SSL协议版本
|
||||
if (StrUtil.isNotBlank(this.sslProtocols)) {
|
||||
p.put(SSL_PROTOCOLS, this.sslProtocols);
|
||||
}
|
||||
}
|
||||
|
||||
// 补充自定义属性,允许自定属性覆盖已经设置的值
|
||||
p.putAll(this.customProperty);
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果某些值为null,使用默认值
|
||||
*
|
||||
* @return this
|
||||
*/
|
||||
public MailAccount defaultIfEmpty() {
|
||||
// 去掉发件人的姓名部分
|
||||
final String fromAddress = InternalMailUtil.parseFirstAddress(this.from, this.charset).getAddress();
|
||||
|
||||
if (StrUtil.isBlank(this.host)) {
|
||||
// 如果SMTP地址为空,默认使用smtp.<发件人邮箱后缀>
|
||||
this.host = StrUtil.format("smtp.{}", StrUtil.subSuf(fromAddress, fromAddress.indexOf('@') + 1));
|
||||
}
|
||||
if (StrUtil.isBlank(user)) {
|
||||
// 如果用户名为空,默认为发件人(issue#I4FYVY@Gitee)
|
||||
//this.user = StrUtil.subPre(fromAddress, fromAddress.indexOf('@'));
|
||||
this.user = fromAddress;
|
||||
}
|
||||
if (null == this.auth) {
|
||||
// 如果密码非空白,则使用认证模式
|
||||
this.auth = (false == StrUtil.isBlank(this.pass));
|
||||
}
|
||||
if (null == this.port) {
|
||||
// 端口在SSL状态下默认与socketFactoryPort一致,非SSL状态下默认为25
|
||||
this.port = (null != this.sslEnable && this.sslEnable) ? this.socketFactoryPort : 25;
|
||||
}
|
||||
if (null == this.charset) {
|
||||
// 默认UTF-8编码
|
||||
this.charset = CharsetUtil.CHARSET_UTF_8;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MailAccount [host=" + host + ", port=" + port + ", auth=" + auth + ", user=" + user + ", pass=" + (StrUtil.isEmpty(this.pass) ? "" : "******") + ", from=" + from + ", startttlsEnable="
|
||||
+ starttlsEnable + ", socketFactoryClass=" + socketFactoryClass + ", socketFactoryFallback=" + socketFactoryFallback + ", socketFactoryPort=" + socketFactoryPort + "]";
|
||||
}
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
package org.dromara.common.mail.utils;
|
||||
|
||||
import cn.hutool.core.exceptions.ExceptionUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* 邮件异常
|
||||
*
|
||||
* @author xiaoleilu
|
||||
*/
|
||||
public class MailException extends RuntimeException {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 8247610319171014183L;
|
||||
|
||||
public MailException(Throwable e) {
|
||||
super(ExceptionUtil.getMessage(e), e);
|
||||
}
|
||||
|
||||
public MailException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public MailException(String messageTemplate, Object... params) {
|
||||
super(StrUtil.format(messageTemplate, params));
|
||||
}
|
||||
|
||||
public MailException(String message, Throwable throwable) {
|
||||
super(message, throwable);
|
||||
}
|
||||
|
||||
public MailException(String message, Throwable throwable, boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, throwable, enableSuppression, writableStackTrace);
|
||||
}
|
||||
|
||||
public MailException(Throwable throwable, String messageTemplate, Object... params) {
|
||||
super(StrUtil.format(messageTemplate, params), throwable);
|
||||
}
|
||||
}
|
@ -5,6 +5,9 @@ import cn.hutool.core.io.IoUtil;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.core.util.CharUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.extra.mail.JakartaMail;
|
||||
import cn.hutool.extra.mail.JakartaUserPassAuthenticator;
|
||||
import cn.hutool.extra.mail.MailAccount;
|
||||
import jakarta.mail.Authenticator;
|
||||
import jakarta.mail.Session;
|
||||
import lombok.AccessLevel;
|
||||
@ -17,7 +20,7 @@ import java.io.InputStream;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import java.util.Map.Entry;
|
||||
|
||||
/**
|
||||
* 邮件工具类
|
||||
@ -385,7 +388,7 @@ public class MailUtils {
|
||||
public static Session getSession(MailAccount mailAccount, boolean isSingleton) {
|
||||
Authenticator authenticator = null;
|
||||
if (mailAccount.isAuth()) {
|
||||
authenticator = new UserPassAuthenticator(mailAccount.getUser(), mailAccount.getPass());
|
||||
authenticator = new JakartaUserPassAuthenticator(mailAccount.getUser(), mailAccount.getPass());
|
||||
}
|
||||
|
||||
return isSingleton ? Session.getDefaultInstance(mailAccount.getSmtpProps(), authenticator) //
|
||||
@ -412,7 +415,7 @@ public class MailUtils {
|
||||
*/
|
||||
private static String send(MailAccount mailAccount, boolean useGlobalSession, Collection<String> tos, Collection<String> ccs, Collection<String> bccs, String subject, String content,
|
||||
Map<String, InputStream> imageMap, boolean isHtml, File... files) {
|
||||
final Mail mail = Mail.create(mailAccount).setUseGlobalSession(useGlobalSession);
|
||||
final JakartaMail mail = JakartaMail.create(mailAccount).setUseGlobalSession(useGlobalSession);
|
||||
|
||||
// 可选抄送人
|
||||
if (CollUtil.isNotEmpty(ccs)) {
|
||||
@ -431,7 +434,7 @@ public class MailUtils {
|
||||
|
||||
// 图片
|
||||
if (MapUtil.isNotEmpty(imageMap)) {
|
||||
for (Map.Entry<String, InputStream> entry : imageMap.entrySet()) {
|
||||
for (Entry<String, InputStream> entry : imageMap.entrySet()) {
|
||||
mail.addImage(entry.getKey(), entry.getValue());
|
||||
// 关闭流
|
||||
IoUtil.close(entry.getValue());
|
||||
@ -463,5 +466,4 @@ public class MailUtils {
|
||||
return result;
|
||||
}
|
||||
// ------------------------------------------------------------------------------------------------------------------------ Private method end
|
||||
|
||||
}
|
||||
|
@ -1,33 +0,0 @@
|
||||
package org.dromara.common.mail.utils;
|
||||
|
||||
import jakarta.mail.Authenticator;
|
||||
import jakarta.mail.PasswordAuthentication;
|
||||
|
||||
/**
|
||||
* 用户名密码验证器
|
||||
*
|
||||
* @author looly
|
||||
* @since 3.1.2
|
||||
*/
|
||||
public class UserPassAuthenticator extends Authenticator {
|
||||
|
||||
private final String user;
|
||||
private final String pass;
|
||||
|
||||
/**
|
||||
* 构造
|
||||
*
|
||||
* @param user 用户名
|
||||
* @param pass 密码
|
||||
*/
|
||||
public UserPassAuthenticator(String user, String pass) {
|
||||
this.user = user;
|
||||
this.pass = pass;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication() {
|
||||
return new PasswordAuthentication(this.user, this.pass);
|
||||
}
|
||||
|
||||
}
|
@ -32,20 +32,9 @@
|
||||
<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mybatis.spring.boot</groupId>
|
||||
<artifactId>mybatis-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.mybatis</groupId>
|
||||
<artifactId>mybatis-spring</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- sql性能分析插件 -->
|
||||
|
@ -3,9 +3,10 @@ package org.dromara.common.mybatis.annotation;
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 数据权限
|
||||
*
|
||||
* 数据权限注解,用于标记数据权限的占位符关键字和替换值
|
||||
* <p>
|
||||
* 一个注解只能对应一个模板
|
||||
* </p>
|
||||
*
|
||||
* @author Lion Li
|
||||
* @version 3.5.0
|
||||
@ -16,13 +17,24 @@ import java.lang.annotation.*;
|
||||
public @interface DataColumn {
|
||||
|
||||
/**
|
||||
* 占位符关键字
|
||||
* 数据权限模板的占位符关键字,默认为 "deptName"
|
||||
*
|
||||
* @return 占位符关键字数组
|
||||
*/
|
||||
String[] key() default "deptName";
|
||||
|
||||
/**
|
||||
* 占位符替换值
|
||||
* 数据权限模板的占位符替换值,默认为 "dept_id"
|
||||
*
|
||||
* @return 占位符替换值数组
|
||||
*/
|
||||
String[] value() default "dept_id";
|
||||
|
||||
/**
|
||||
* 权限标识符 用于通过菜单权限标识符来获取数据权限
|
||||
* 拥有此标识符的角色 将不会拼接此角色的数据过滤sql
|
||||
*
|
||||
* @return 权限标识符
|
||||
*/
|
||||
String permission() default "";
|
||||
}
|
||||
|
@ -3,7 +3,7 @@ package org.dromara.common.mybatis.annotation;
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 数据权限组
|
||||
* 数据权限组注解,用于标记数据权限配置数组
|
||||
*
|
||||
* @author Lion Li
|
||||
* @version 3.5.0
|
||||
@ -13,6 +13,18 @@ import java.lang.annotation.*;
|
||||
@Documented
|
||||
public @interface DataPermission {
|
||||
|
||||
/**
|
||||
* 数据权限配置数组,用于指定数据权限的占位符关键字和替换值
|
||||
*
|
||||
* @return 数据权限配置数组
|
||||
*/
|
||||
DataColumn[] value();
|
||||
|
||||
/**
|
||||
* 权限拼接标识符(用于指定连接语句的sql符号)
|
||||
* 如不填 默认 select 用 OR 其他语句用 AND
|
||||
* 内容 OR 或者 AND
|
||||
*/
|
||||
String joinStr() default "";
|
||||
|
||||
}
|
||||
|
@ -7,11 +7,14 @@ import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
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 org.dromara.common.core.factory.YmlPropertySourceFactory;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.dromara.common.mybatis.handler.InjectionMetaObjectHandler;
|
||||
import org.dromara.common.mybatis.handler.MybatisExceptionHandler;
|
||||
import org.dromara.common.mybatis.interceptor.PlusDataPermissionInterceptor;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
@ -22,7 +25,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
* @author Lion Li
|
||||
*/
|
||||
@EnableTransactionManagement(proxyTargetClass = true)
|
||||
@AutoConfiguration
|
||||
@MapperScan("${mybatis-plus.mapperPackage}")
|
||||
@PropertySource(value = "classpath:common-mybatis.yml", factory = YmlPropertySourceFactory.class)
|
||||
public class MybatisPlusConfig {
|
||||
@ -30,6 +32,12 @@ public class MybatisPlusConfig {
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
// 多租户插件 必须放到第一位
|
||||
try {
|
||||
TenantLineInnerInterceptor tenant = SpringUtils.getBean(TenantLineInnerInterceptor.class);
|
||||
interceptor.addInnerInterceptor(tenant);
|
||||
} catch (BeansException ignore) {
|
||||
}
|
||||
// 数据权限处理
|
||||
interceptor.addInnerInterceptor(dataPermissionInterceptor());
|
||||
// 分页插件
|
||||
@ -43,7 +51,7 @@ public class MybatisPlusConfig {
|
||||
* 数据权限拦截器
|
||||
*/
|
||||
public PlusDataPermissionInterceptor dataPermissionInterceptor() {
|
||||
return new PlusDataPermissionInterceptor();
|
||||
return new PlusDataPermissionInterceptor(SpringUtils.getProperty("mybatis-plus.mapperPackage"));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -51,8 +59,6 @@ public class MybatisPlusConfig {
|
||||
*/
|
||||
public PaginationInnerInterceptor paginationInnerInterceptor() {
|
||||
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
|
||||
// 设置最大单页限制数量,默认 500 条,-1 不受限制
|
||||
paginationInnerInterceptor.setMaxLimit(-1L);
|
||||
// 分页合理化
|
||||
paginationInnerInterceptor.setOverflow(true);
|
||||
return paginationInnerInterceptor;
|
||||
@ -82,6 +88,14 @@ public class MybatisPlusConfig {
|
||||
return new DefaultIdentifierGenerator(NetUtil.getLocalhost());
|
||||
}
|
||||
|
||||
/**
|
||||
* 异常处理器
|
||||
*/
|
||||
@Bean
|
||||
public MybatisExceptionHandler mybatisExceptionHandler() {
|
||||
return new MybatisExceptionHandler();
|
||||
}
|
||||
|
||||
/**
|
||||
* PaginationInnerInterceptor 分页插件,自动识别数据库类型
|
||||
* https://baomidou.com/pages/97710a/
|
||||
|
@ -17,7 +17,6 @@ import java.util.Map;
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
|
||||
@Data
|
||||
public class BaseEntity implements Serializable {
|
||||
|
||||
|
@ -12,6 +12,7 @@ import com.baomidou.mybatisplus.extension.toolkit.Db;
|
||||
import org.apache.ibatis.logging.Log;
|
||||
import org.apache.ibatis.logging.LogFactory;
|
||||
import org.dromara.common.core.utils.MapstructUtils;
|
||||
import org.dromara.common.core.utils.StreamUtils;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
@ -34,74 +35,125 @@ public interface BaseMapperPlus<T, V> extends BaseMapper<T> {
|
||||
|
||||
Log log = LogFactory.getLog(BaseMapperPlus.class);
|
||||
|
||||
/**
|
||||
* 获取当前实例对象关联的泛型类型 V 的 Class 对象
|
||||
*
|
||||
* @return 返回当前实例对象关联的泛型类型 V 的 Class 对象
|
||||
*/
|
||||
default Class<V> currentVoClass() {
|
||||
GenericTypeUtils.resolveTypeArguments(this.getClass(), BaseMapperPlus.class);
|
||||
return (Class<V>) GenericTypeUtils.resolveTypeArguments(this.getClass(), BaseMapperPlus.class)[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前实例对象关联的泛型类型 T 的 Class 对象
|
||||
*
|
||||
* @return 返回当前实例对象关联的泛型类型 T 的 Class 对象
|
||||
*/
|
||||
default Class<T> currentModelClass() {
|
||||
return (Class<T>) GenericTypeUtils.resolveTypeArguments(this.getClass(), BaseMapperPlus.class)[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用默认的查询条件查询并返回结果列表
|
||||
*
|
||||
* @return 返回查询结果的列表
|
||||
*/
|
||||
default List<T> selectList() {
|
||||
return this.selectList(new QueryWrapper<>());
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入
|
||||
* 批量插入实体对象集合
|
||||
*
|
||||
* @param entityList 实体对象集合
|
||||
* @return 插入操作是否成功的布尔值
|
||||
*/
|
||||
default boolean insertBatch(Collection<T> entityList) {
|
||||
return Db.saveBatch(entityList);
|
||||
Db.saveBatch(entityList);
|
||||
// 临时解决 新版本 mp 插入状态判断错误问题
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新
|
||||
* 批量根据ID更新实体对象集合
|
||||
*
|
||||
* @param entityList 实体对象集合
|
||||
* @return 更新操作是否成功的布尔值
|
||||
*/
|
||||
default boolean updateBatchById(Collection<T> entityList) {
|
||||
return Db.updateBatchById(entityList);
|
||||
Db.updateBatchById(entityList);
|
||||
// 临时解决 新版本 mp 插入状态判断错误问题
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入或更新
|
||||
* 批量插入或更新实体对象集合
|
||||
*
|
||||
* @param entityList 实体对象集合
|
||||
* @return 插入或更新操作是否成功的布尔值
|
||||
*/
|
||||
default boolean insertOrUpdateBatch(Collection<T> entityList) {
|
||||
return Db.saveOrUpdateBatch(entityList);
|
||||
Db.saveOrUpdateBatch(entityList);
|
||||
// 临时解决 新版本 mp 插入状态判断错误问题
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入(包含限制条数)
|
||||
* 批量插入实体对象集合并指定批处理大小
|
||||
*
|
||||
* @param entityList 实体对象集合
|
||||
* @param batchSize 批处理大小
|
||||
* @return 插入操作是否成功的布尔值
|
||||
*/
|
||||
default boolean insertBatch(Collection<T> entityList, int batchSize) {
|
||||
return Db.saveBatch(entityList, batchSize);
|
||||
Db.saveBatch(entityList, batchSize);
|
||||
// 临时解决 新版本 mp 插入状态判断错误问题
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新(包含限制条数)
|
||||
* 批量根据ID更新实体对象集合并指定批处理大小
|
||||
*
|
||||
* @param entityList 实体对象集合
|
||||
* @param batchSize 批处理大小
|
||||
* @return 更新操作是否成功的布尔值
|
||||
*/
|
||||
default boolean updateBatchById(Collection<T> entityList, int batchSize) {
|
||||
return Db.updateBatchById(entityList, batchSize);
|
||||
Db.updateBatchById(entityList, batchSize);
|
||||
// 临时解决 新版本 mp 插入状态判断错误问题
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入或更新(包含限制条数)
|
||||
* 批量插入或更新实体对象集合并指定批处理大小
|
||||
*
|
||||
* @param entityList 实体对象集合
|
||||
* @param batchSize 批处理大小
|
||||
* @return 插入或更新操作是否成功的布尔值
|
||||
*/
|
||||
default boolean insertOrUpdateBatch(Collection<T> entityList, int batchSize) {
|
||||
return Db.saveOrUpdateBatch(entityList, batchSize);
|
||||
Db.saveOrUpdateBatch(entityList, batchSize);
|
||||
// 临时解决 新版本 mp 插入状态判断错误问题
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入或更新(包含限制条数)
|
||||
* 根据ID查询单个VO对象
|
||||
*
|
||||
* @param id 主键ID
|
||||
* @return 查询到的单个VO对象
|
||||
*/
|
||||
default boolean insertOrUpdate(T entity) {
|
||||
return Db.saveOrUpdate(entity);
|
||||
}
|
||||
|
||||
default V selectVoById(Serializable id) {
|
||||
return selectVoById(id, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 ID 查询
|
||||
* 根据ID查询单个VO对象并将其转换为指定的VO类
|
||||
*
|
||||
* @param id 主键ID
|
||||
* @param voClass 要转换的VO类的Class对象
|
||||
* @param <C> VO类的类型
|
||||
* @return 查询到的单个VO对象,经过转换为指定的VO类后返回
|
||||
*/
|
||||
default <C> C selectVoById(Serializable id, Class<C> voClass) {
|
||||
T obj = this.selectById(id);
|
||||
@ -111,12 +163,23 @@ public interface BaseMapperPlus<T, V> extends BaseMapper<T> {
|
||||
return MapstructUtils.convert(obj, voClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID集合批量查询VO对象列表
|
||||
*
|
||||
* @param idList 主键ID集合
|
||||
* @return 查询到的VO对象列表
|
||||
*/
|
||||
default List<V> selectVoBatchIds(Collection<? extends Serializable> idList) {
|
||||
return selectVoBatchIds(idList, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询(根据ID 批量查询)
|
||||
* 根据ID集合批量查询实体对象列表,并将其转换为指定的VO对象列表
|
||||
*
|
||||
* @param idList 主键ID集合
|
||||
* @param voClass 要转换的VO类的Class对象
|
||||
* @param <C> VO类的类型
|
||||
* @return 查询到的VO对象列表,经过转换为指定的VO类后返回
|
||||
*/
|
||||
default <C> List<C> selectVoBatchIds(Collection<? extends Serializable> idList, Class<C> voClass) {
|
||||
List<T> list = this.selectBatchIds(idList);
|
||||
@ -126,12 +189,23 @@ public interface BaseMapperPlus<T, V> extends BaseMapper<T> {
|
||||
return MapstructUtils.convert(list, voClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据查询条件Map查询VO对象列表
|
||||
*
|
||||
* @param map 查询条件Map
|
||||
* @return 查询到的VO对象列表
|
||||
*/
|
||||
default List<V> selectVoByMap(Map<String, Object> map) {
|
||||
return selectVoByMap(map, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询(根据 columnMap 条件)
|
||||
* 根据查询条件Map查询实体对象列表,并将其转换为指定的VO对象列表
|
||||
*
|
||||
* @param map 查询条件Map
|
||||
* @param voClass 要转换的VO类的Class对象
|
||||
* @param <C> VO类的类型
|
||||
* @return 查询到的VO对象列表,经过转换为指定的VO类后返回
|
||||
*/
|
||||
default <C> List<C> selectVoByMap(Map<String, Object> map, Class<C> voClass) {
|
||||
List<T> list = this.selectByMap(map);
|
||||
@ -141,31 +215,82 @@ public interface BaseMapperPlus<T, V> extends BaseMapper<T> {
|
||||
return MapstructUtils.convert(list, voClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件查询单个VO对象
|
||||
*
|
||||
* @param wrapper 查询条件Wrapper
|
||||
* @return 查询到的单个VO对象
|
||||
*/
|
||||
default V selectVoOne(Wrapper<T> wrapper) {
|
||||
return selectVoOne(wrapper, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 entity 条件,查询一条记录
|
||||
* 根据条件查询单个VO对象,并根据需要决定是否抛出异常
|
||||
*
|
||||
* @param wrapper 查询条件Wrapper
|
||||
* @param throwEx 是否抛出异常的标志
|
||||
* @return 查询到的单个VO对象
|
||||
*/
|
||||
default V selectVoOne(Wrapper<T> wrapper, boolean throwEx) {
|
||||
return selectVoOne(wrapper, this.currentVoClass(), throwEx);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件查询单个VO对象,并指定返回的VO对象的类型
|
||||
*
|
||||
* @param wrapper 查询条件Wrapper
|
||||
* @param voClass 返回的VO对象的Class对象
|
||||
* @param <C> 返回的VO对象的类型
|
||||
* @return 查询到的单个VO对象,经过类型转换为指定的VO类后返回
|
||||
*/
|
||||
default <C> C selectVoOne(Wrapper<T> wrapper, Class<C> voClass) {
|
||||
T obj = this.selectOne(wrapper);
|
||||
return selectVoOne(wrapper, voClass, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件查询单个实体对象,并将其转换为指定的VO对象
|
||||
*
|
||||
* @param wrapper 查询条件Wrapper
|
||||
* @param voClass 要转换的VO类的Class对象
|
||||
* @param throwEx 是否抛出异常的标志
|
||||
* @param <C> VO类的类型
|
||||
* @return 查询到的单个VO对象,经过转换为指定的VO类后返回
|
||||
*/
|
||||
default <C> C selectVoOne(Wrapper<T> wrapper, Class<C> voClass, boolean throwEx) {
|
||||
T obj = this.selectOne(wrapper, throwEx);
|
||||
if (ObjectUtil.isNull(obj)) {
|
||||
return null;
|
||||
}
|
||||
return MapstructUtils.convert(obj, voClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有VO对象列表
|
||||
*
|
||||
* @return 查询到的VO对象列表
|
||||
*/
|
||||
default List<V> selectVoList() {
|
||||
return selectVoList(new QueryWrapper<>(), this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件查询VO对象列表
|
||||
*
|
||||
* @param wrapper 查询条件Wrapper
|
||||
* @return 查询到的VO对象列表
|
||||
*/
|
||||
default List<V> selectVoList(Wrapper<T> wrapper) {
|
||||
return selectVoList(wrapper, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 entity 条件,查询全部记录
|
||||
* 根据条件查询实体对象列表,并将其转换为指定的VO对象列表
|
||||
*
|
||||
* @param wrapper 查询条件Wrapper
|
||||
* @param voClass 要转换的VO类的Class对象
|
||||
* @param <C> VO类的类型
|
||||
* @return 查询到的VO对象列表,经过转换为指定的VO类后返回
|
||||
*/
|
||||
default <C> List<C> selectVoList(Wrapper<T> wrapper, Class<C> voClass) {
|
||||
List<T> list = this.selectList(wrapper);
|
||||
@ -175,15 +300,31 @@ public interface BaseMapperPlus<T, V> extends BaseMapper<T> {
|
||||
return MapstructUtils.convert(list, voClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件分页查询VO对象列表
|
||||
*
|
||||
* @param page 分页信息
|
||||
* @param wrapper 查询条件Wrapper
|
||||
* @return 查询到的VO对象分页列表
|
||||
*/
|
||||
default <P extends IPage<V>> P selectVoPage(IPage<T> page, Wrapper<T> wrapper) {
|
||||
return selectVoPage(page, wrapper, this.currentVoClass());
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询VO
|
||||
* 根据条件分页查询实体对象列表,并将其转换为指定的VO对象分页列表
|
||||
*
|
||||
* @param page 分页信息
|
||||
* @param wrapper 查询条件Wrapper
|
||||
* @param voClass 要转换的VO类的Class对象
|
||||
* @param <C> VO类的类型
|
||||
* @param <P> VO对象分页列表的类型
|
||||
* @return 查询到的VO对象分页列表,经过转换为指定的VO类后返回
|
||||
*/
|
||||
default <C, P extends IPage<C>> P selectVoPage(IPage<T> page, Wrapper<T> wrapper, Class<C> voClass) {
|
||||
// 根据条件分页查询实体对象列表
|
||||
List<T> list = this.selectList(page, wrapper);
|
||||
// 创建一个新的VO对象分页列表,并设置分页信息
|
||||
IPage<C> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
|
||||
if (CollUtil.isEmpty(list)) {
|
||||
return (P) voPage;
|
||||
@ -192,8 +333,16 @@ public interface BaseMapperPlus<T, V> extends BaseMapper<T> {
|
||||
return (P) voPage;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件查询符合条件的对象,并将其转换为指定类型的对象列表
|
||||
*
|
||||
* @param wrapper 查询条件Wrapper
|
||||
* @param mapper 转换函数,用于将查询到的对象转换为指定类型的对象
|
||||
* @param <C> 要转换的对象的类型
|
||||
* @return 查询到的符合条件的对象列表,经过转换为指定类型的对象后返回
|
||||
*/
|
||||
default <C> List<C> selectObjs(Wrapper<T> wrapper, Function<? super Object, C> mapper) {
|
||||
return this.selectObjs(wrapper).stream().filter(Objects::nonNull).map(mapper).collect(Collectors.toList());
|
||||
return StreamUtils.toList(this.selectObjs(wrapper), mapper);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -4,10 +4,10 @@ import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.metadata.OrderItem;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import lombok.Data;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.core.utils.sql.SqlUtil;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
@ -19,7 +19,6 @@ import java.util.List;
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
|
||||
@Data
|
||||
public class PageQuery implements Serializable {
|
||||
|
||||
@ -56,6 +55,9 @@ public class PageQuery implements Serializable {
|
||||
*/
|
||||
public static final int DEFAULT_PAGE_SIZE = Integer.MAX_VALUE;
|
||||
|
||||
/**
|
||||
* 构建分页对象
|
||||
*/
|
||||
public <T> Page<T> build() {
|
||||
Integer pageNum = ObjectUtil.defaultIfNull(getPageNum(), DEFAULT_PAGE_NUM);
|
||||
Integer pageSize = ObjectUtil.defaultIfNull(getPageSize(), DEFAULT_PAGE_SIZE);
|
||||
@ -111,4 +113,8 @@ public class PageQuery implements Serializable {
|
||||
return list;
|
||||
}
|
||||
|
||||
public Integer getFirstNum() {
|
||||
return (pageNum - 1) * pageSize;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -14,7 +14,6 @@ import java.util.List;
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class TableDataInfo<T> implements Serializable {
|
||||
@ -53,6 +52,9 @@ public class TableDataInfo<T> implements Serializable {
|
||||
this.total = total;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据分页对象构建表格分页数据对象
|
||||
*/
|
||||
public static <T> TableDataInfo<T> build(IPage<T> page) {
|
||||
TableDataInfo<T> rspData = new TableDataInfo<>();
|
||||
rspData.setCode(HttpStatus.HTTP_OK);
|
||||
@ -62,6 +64,9 @@ public class TableDataInfo<T> implements Serializable {
|
||||
return rspData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据数据列表构建表格分页数据对象
|
||||
*/
|
||||
public static <T> TableDataInfo<T> build(List<T> list) {
|
||||
TableDataInfo<T> rspData = new TableDataInfo<>();
|
||||
rspData.setCode(HttpStatus.HTTP_OK);
|
||||
@ -71,6 +76,9 @@ public class TableDataInfo<T> implements Serializable {
|
||||
return rspData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建表格分页数据对象
|
||||
*/
|
||||
public static <T> TableDataInfo<T> build() {
|
||||
TableDataInfo<T> rspData = new TableDataInfo<>();
|
||||
rspData.setCode(HttpStatus.HTTP_OK);
|
||||
|
@ -1,8 +1,8 @@
|
||||
package org.dromara.common.mybatis.enums;
|
||||
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
|
||||
/**
|
||||
* 数据库类型
|
||||
@ -33,8 +33,17 @@ public enum DataBaseType {
|
||||
*/
|
||||
SQL_SERVER("Microsoft SQL Server");
|
||||
|
||||
/**
|
||||
* 数据库类型
|
||||
*/
|
||||
private final String type;
|
||||
|
||||
/**
|
||||
* 根据数据库产品名称查找对应的数据库类型
|
||||
*
|
||||
* @param databaseProductName 数据库产品名称
|
||||
* @return 对应的数据库类型枚举值,如果未找到则返回 null
|
||||
*/
|
||||
public static DataBaseType find(String databaseProductName) {
|
||||
if (StringUtils.isBlank(databaseProductName)) {
|
||||
return null;
|
||||
|
@ -1,19 +1,22 @@
|
||||
package org.dromara.common.mybatis.enums;
|
||||
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import org.dromara.common.core.domain.model.LoginUser;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.mybatis.helper.DataPermissionHelper;
|
||||
|
||||
/**
|
||||
* 数据权限类型
|
||||
* 数据权限类型枚举
|
||||
* <p>
|
||||
* 语法支持 spel 模板表达式
|
||||
* <p>
|
||||
* 内置数据 user 当前用户 内容参考 LoginUser
|
||||
* 如需扩展数据 可使用 {@link DataPermissionHelper} 操作
|
||||
* 内置服务 sdss 系统数据权限服务 内容参考 SysDataScopeService
|
||||
* 如需扩展更多自定义服务 可以参考 sdss 自行编写
|
||||
* 支持使用 SpEL 模板表达式定义 SQL 查询条件
|
||||
* 内置数据:
|
||||
* - {@code user}: 当前登录用户信息,参考 {@link LoginUser}
|
||||
* 内置服务:
|
||||
* - {@code sdss}: 系统数据权限服务,参考 ISysDataScopeService
|
||||
* 如需扩展数据,可以通过 {@link DataPermissionHelper} 进行操作
|
||||
* 如需扩展服务,可以通过 ISysDataScopeService 自行编写
|
||||
* </p>
|
||||
*
|
||||
* @author Lion Li
|
||||
* @version 3.5.0
|
||||
@ -50,15 +53,21 @@ public enum DataScopeType {
|
||||
private final String code;
|
||||
|
||||
/**
|
||||
* 语法 采用 spel 模板表达式
|
||||
* SpEL 模板表达式,用于构建 SQL 查询条件
|
||||
*/
|
||||
private final String sqlTemplate;
|
||||
|
||||
/**
|
||||
* 不满足 sqlTemplate 则填充
|
||||
* 如果不满足 {@code sqlTemplate} 的条件,则使用此默认 SQL 表达式
|
||||
*/
|
||||
private final String elseSql;
|
||||
|
||||
/**
|
||||
* 根据枚举代码查找对应的枚举值
|
||||
*
|
||||
* @param code 枚举代码
|
||||
* @return 对应的枚举值,如果未找到则返回 null
|
||||
*/
|
||||
public static DataScopeType findCode(String code) {
|
||||
if (StringUtils.isBlank(code)) {
|
||||
return null;
|
||||
|
@ -3,12 +3,12 @@ package org.dromara.common.mybatis.handler;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.http.HttpStatus;
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.dromara.common.core.domain.model.LoginUser;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.mybatis.core.domain.BaseEntity;
|
||||
import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
@ -21,43 +21,37 @@ import java.util.Date;
|
||||
@Slf4j
|
||||
public class InjectionMetaObjectHandler implements MetaObjectHandler {
|
||||
|
||||
/**
|
||||
* 插入填充方法,用于在插入数据时自动填充实体对象中的创建时间、更新时间、创建人、更新人等信息
|
||||
*
|
||||
* @param metaObject 元对象,用于获取原始对象并进行填充
|
||||
*/
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
try {
|
||||
if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity baseEntity) {
|
||||
// 获取当前时间作为创建时间和更新时间,如果创建时间不为空,则使用创建时间,否则使用当前时间
|
||||
Date current = ObjectUtil.isNotNull(baseEntity.getCreateTime())
|
||||
? baseEntity.getCreateTime() : new Date();
|
||||
baseEntity.setCreateTime(current);
|
||||
baseEntity.setUpdateTime(current);
|
||||
LoginUser loginUser = getLoginUser();
|
||||
if (ObjectUtil.isNotNull(loginUser)) {
|
||||
Long userId = ObjectUtil.isNotNull(baseEntity.getCreateBy())
|
||||
? baseEntity.getCreateBy() : loginUser.getUserId();
|
||||
// 当前已登录 且 创建人为空 则填充
|
||||
baseEntity.setCreateBy(userId);
|
||||
// 当前已登录 且 更新人为空 则填充
|
||||
baseEntity.setUpdateBy(userId);
|
||||
baseEntity.setCreateDept(ObjectUtil.isNotNull(baseEntity.getCreateDept())
|
||||
? baseEntity.getCreateDept() : loginUser.getDeptId());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
try {
|
||||
if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity baseEntity) {
|
||||
Date current = new Date();
|
||||
// 更新时间填充(不管为不为空)
|
||||
baseEntity.setUpdateTime(current);
|
||||
LoginUser loginUser = getLoginUser();
|
||||
// 当前已登录 更新人填充(不管为不为空)
|
||||
if (ObjectUtil.isNotNull(loginUser)) {
|
||||
baseEntity.setUpdateBy(loginUser.getUserId());
|
||||
// 如果创建人为空,则填充当前登录用户的信息
|
||||
if (ObjectUtil.isNull(baseEntity.getCreateBy())) {
|
||||
LoginUser loginUser = getLoginUser();
|
||||
if (ObjectUtil.isNotNull(loginUser)) {
|
||||
Long userId = loginUser.getUserId();
|
||||
// 填充创建人、更新人和创建部门信息
|
||||
baseEntity.setCreateBy(userId);
|
||||
baseEntity.setUpdateBy(userId);
|
||||
baseEntity.setCreateDept(ObjectUtil.isNotNull(baseEntity.getCreateDept())
|
||||
? baseEntity.getCreateDept() : loginUser.getDeptId());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Date date = new Date();
|
||||
this.strictInsertFill(metaObject, "createTime", Date.class, date);
|
||||
this.strictInsertFill(metaObject, "updateTime", Date.class, date);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
|
||||
@ -65,7 +59,35 @@ public class InjectionMetaObjectHandler implements MetaObjectHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取登录用户名
|
||||
* 更新填充方法,用于在更新数据时自动填充实体对象中的更新时间和更新人信息
|
||||
*
|
||||
* @param metaObject 元对象,用于获取原始对象并进行填充
|
||||
*/
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
try {
|
||||
if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity baseEntity) {
|
||||
// 获取当前时间作为更新时间,无论原始对象中的更新时间是否为空都填充
|
||||
Date current = new Date();
|
||||
baseEntity.setUpdateTime(current);
|
||||
|
||||
// 获取当前登录用户的ID,并填充更新人信息
|
||||
Long userId = LoginHelper.getUserId();
|
||||
if (ObjectUtil.isNotNull(userId)) {
|
||||
baseEntity.setUpdateBy(userId);
|
||||
}
|
||||
} else {
|
||||
this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录用户信息
|
||||
*
|
||||
* @return 当前登录用户的信息,如果用户未登录则返回 null
|
||||
*/
|
||||
private LoginUser getLoginUser() {
|
||||
LoginUser loginUser;
|
||||
|
@ -1,14 +1,14 @@
|
||||
package org.dromara.common.mybatis.handler;
|
||||
|
||||
import org.dromara.common.core.domain.R;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.mybatis.spring.MyBatisSystemException;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* Mybatis异常处理器
|
||||
*
|
||||
@ -35,7 +35,7 @@ public class MybatisExceptionHandler {
|
||||
public R<Void> handleCannotFindDataSourceException(MyBatisSystemException e, HttpServletRequest request) {
|
||||
String requestURI = request.getRequestURI();
|
||||
String message = e.getMessage();
|
||||
if ("CannotFindDataSourceException".contains(message)) {
|
||||
if (StringUtils.contains("CannotFindDataSourceException", message)) {
|
||||
log.error("请求地址'{}', 未找到数据源", requestURI);
|
||||
return R.fail("未找到数据源,请联系管理员确认");
|
||||
}
|
||||
|
@ -2,7 +2,6 @@ package org.dromara.common.mybatis.handler;
|
||||
|
||||
import cn.hutool.core.annotation.AnnotationUtil;
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ClassUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.sf.jsqlparser.JSQLParserException;
|
||||
@ -10,6 +9,7 @@ import net.sf.jsqlparser.expression.Expression;
|
||||
import net.sf.jsqlparser.expression.Parenthesis;
|
||||
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
|
||||
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
|
||||
import org.apache.ibatis.io.Resources;
|
||||
import org.dromara.common.core.domain.dto.RoleDTO;
|
||||
import org.dromara.common.core.domain.model.LoginUser;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
@ -21,16 +21,26 @@ import org.dromara.common.mybatis.annotation.DataPermission;
|
||||
import org.dromara.common.mybatis.enums.DataScopeType;
|
||||
import org.dromara.common.mybatis.helper.DataPermissionHelper;
|
||||
import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.expression.BeanFactoryResolver;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
|
||||
import org.springframework.core.io.support.ResourcePatternResolver;
|
||||
import org.springframework.core.type.ClassMetadata;
|
||||
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
|
||||
import org.springframework.expression.BeanResolver;
|
||||
import org.springframework.expression.ExpressionParser;
|
||||
import org.springframework.expression.ParserContext;
|
||||
import org.springframework.expression.common.TemplateParserContext;
|
||||
import org.springframework.expression.spel.standard.SpelExpressionParser;
|
||||
import org.springframework.expression.spel.support.StandardEvaluationContext;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
|
||||
@ -58,9 +68,27 @@ public class PlusDataPermissionHandler {
|
||||
*/
|
||||
private final BeanResolver beanResolver = new BeanFactoryResolver(SpringUtils.getBeanFactory());
|
||||
|
||||
/**
|
||||
* 构造方法,扫描指定包下的 Mapper 类并初始化缓存
|
||||
*
|
||||
* @param mapperPackage Mapper 类所在的包路径
|
||||
*/
|
||||
public PlusDataPermissionHandler(String mapperPackage) {
|
||||
scanMapperClasses(mapperPackage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据过滤条件的 SQL 片段
|
||||
*
|
||||
* @param where 原始的查询条件表达式
|
||||
* @param mappedStatementId Mapper 方法的 ID
|
||||
* @param isSelect 是否为查询语句
|
||||
* @return 数据过滤条件的 SQL 片段
|
||||
*/
|
||||
public Expression getSqlSegment(Expression where, String mappedStatementId, boolean isSelect) {
|
||||
DataColumn[] dataColumns = findAnnotation(mappedStatementId);
|
||||
// 获取数据权限配置
|
||||
DataPermission dataPermission = getDataPermission(mappedStatementId);
|
||||
// 获取当前登录用户信息
|
||||
LoginUser currentUser = DataPermissionHelper.getVariable("user");
|
||||
if (ObjectUtil.isNull(currentUser)) {
|
||||
currentUser = LoginHelper.getLoginUser();
|
||||
@ -70,7 +98,8 @@ public class PlusDataPermissionHandler {
|
||||
if (LoginHelper.isSuperAdmin() || LoginHelper.isTenantAdmin()) {
|
||||
return where;
|
||||
}
|
||||
String dataFilterSql = buildDataFilter(dataColumns, isSelect);
|
||||
// 构造数据过滤条件的 SQL 片段
|
||||
String dataFilterSql = buildDataFilter(dataPermission, isSelect);
|
||||
if (StringUtils.isBlank(dataFilterSql)) {
|
||||
return where;
|
||||
}
|
||||
@ -89,11 +118,19 @@ public class PlusDataPermissionHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造数据过滤sql
|
||||
* 构建数据过滤条件的 SQL 语句
|
||||
*
|
||||
* @param dataPermission 数据权限注解
|
||||
* @param isSelect 标志当前操作是否为查询操作,查询操作和更新或删除操作在处理过滤条件时会有不同的处理方式
|
||||
* @return 构建的数据过滤条件的 SQL 语句
|
||||
* @throws ServiceException 如果角色的数据范围异常或者 key 与 value 的长度不匹配,则抛出 ServiceException 异常
|
||||
*/
|
||||
private String buildDataFilter(DataColumn[] dataColumns, boolean isSelect) {
|
||||
private String buildDataFilter(DataPermission dataPermission, boolean isSelect) {
|
||||
// 更新或删除需满足所有条件
|
||||
String joinStr = isSelect ? " OR " : " AND ";
|
||||
if (StringUtils.isNotBlank(dataPermission.joinStr())) {
|
||||
joinStr = " " + dataPermission.joinStr() + " ";
|
||||
}
|
||||
LoginUser user = DataPermissionHelper.getVariable("user");
|
||||
StandardEvaluationContext context = new StandardEvaluationContext();
|
||||
context.setBeanResolver(beanResolver);
|
||||
@ -111,7 +148,7 @@ public class PlusDataPermissionHandler {
|
||||
return "";
|
||||
}
|
||||
boolean isSuccess = false;
|
||||
for (DataColumn dataColumn : dataColumns) {
|
||||
for (DataColumn dataColumn : dataPermission.value()) {
|
||||
if (dataColumn.key().length != dataColumn.value().length) {
|
||||
throw new ServiceException("角色数据范围异常 => key与value长度不匹配");
|
||||
}
|
||||
@ -121,6 +158,13 @@ public class PlusDataPermissionHandler {
|
||||
)) {
|
||||
continue;
|
||||
}
|
||||
// 包含权限标识符 这直接跳过
|
||||
if (StringUtils.isNotBlank(dataColumn.permission()) &&
|
||||
CollUtil.contains(user.getMenuPermission(), dataColumn.permission())
|
||||
) {
|
||||
isSuccess = true;
|
||||
continue;
|
||||
}
|
||||
// 设置注解变量 key 为表达式变量 value 为变量值
|
||||
for (int i = 0; i < dataColumn.key().length; i++) {
|
||||
context.setVariable(dataColumn.key()[i], dataColumn.value()[i]);
|
||||
@ -144,43 +188,87 @@ public class PlusDataPermissionHandler {
|
||||
return "";
|
||||
}
|
||||
|
||||
public DataColumn[] findAnnotation(String mappedStatementId) {
|
||||
StringBuilder sb = new StringBuilder(mappedStatementId);
|
||||
int index = sb.lastIndexOf(".");
|
||||
String clazzName = sb.substring(0, index);
|
||||
String methodName = sb.substring(index + 1, sb.length());
|
||||
Class<?> clazz;
|
||||
/**
|
||||
* 扫描指定包下的 Mapper 类,并查找其中带有特定注解的方法或类
|
||||
*
|
||||
* @param mapperPackage Mapper 类所在的包路径
|
||||
*/
|
||||
private void scanMapperClasses(String mapperPackage) {
|
||||
// 创建资源解析器和元数据读取工厂
|
||||
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
|
||||
CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
|
||||
// 将 Mapper 包路径按分隔符拆分为数组
|
||||
String[] packagePatternArray = StringUtils.splitPreserveAllTokens(mapperPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
|
||||
String classpath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX;
|
||||
try {
|
||||
clazz = ClassUtil.loadClass(clazzName);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
List<Method> methods = Arrays.stream(ClassUtil.getDeclaredMethods(clazz))
|
||||
.filter(method -> method.getName().equals(methodName)).toList();
|
||||
DataPermission dataPermission;
|
||||
// 获取方法注解
|
||||
for (Method method : methods) {
|
||||
dataPermission = dataPermissionCacheMap.get(mappedStatementId);
|
||||
if (ObjectUtil.isNotNull(dataPermission)) {
|
||||
return dataPermission.value();
|
||||
for (String packagePattern : packagePatternArray) {
|
||||
// 将包路径转换为资源路径
|
||||
String path = ClassUtils.convertClassNameToResourcePath(packagePattern);
|
||||
// 获取指定路径下的所有 .class 文件资源
|
||||
Resource[] resources = resolver.getResources(classpath + path + "/*.class");
|
||||
for (Resource resource : resources) {
|
||||
// 获取资源的类元数据
|
||||
ClassMetadata classMetadata = factory.getMetadataReader(resource).getClassMetadata();
|
||||
// 获取资源对应的类对象
|
||||
Class<?> clazz = Resources.classForName(classMetadata.getClassName());
|
||||
// 查找类中的特定注解
|
||||
findAnnotation(clazz);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("初始化数据安全缓存时出错:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在指定的类中查找特定的注解 DataPermission,并将带有这个注解的方法或类存储到 dataPermissionCacheMap 中
|
||||
*
|
||||
* @param clazz 要查找的类
|
||||
*/
|
||||
private void findAnnotation(Class<?> clazz) {
|
||||
DataPermission dataPermission;
|
||||
for (Method method : clazz.getMethods()) {
|
||||
if (method.isDefault() || method.isVarArgs()) {
|
||||
continue;
|
||||
}
|
||||
String mappedStatementId = clazz.getName() + "." + method.getName();
|
||||
if (AnnotationUtil.hasAnnotation(method, DataPermission.class)) {
|
||||
dataPermission = AnnotationUtil.getAnnotation(method, DataPermission.class);
|
||||
dataPermissionCacheMap.put(mappedStatementId, dataPermission);
|
||||
return dataPermission.value();
|
||||
}
|
||||
}
|
||||
dataPermission = dataPermissionCacheMap.get(clazz.getName());
|
||||
if (ObjectUtil.isNotNull(dataPermission)) {
|
||||
return dataPermission.value();
|
||||
}
|
||||
// 获取类注解
|
||||
if (AnnotationUtil.hasAnnotation(clazz, DataPermission.class)) {
|
||||
dataPermission = AnnotationUtil.getAnnotation(clazz, DataPermission.class);
|
||||
dataPermissionCacheMap.put(clazz.getName(), dataPermission);
|
||||
return dataPermission.value();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据映射语句 ID 或类名获取对应的 DataPermission 注解对象
|
||||
*
|
||||
* @param mapperId 映射语句 ID
|
||||
* @return DataPermission 注解对象,如果不存在则返回 null
|
||||
*/
|
||||
public DataPermission getDataPermission(String mapperId) {
|
||||
// 检查缓存中是否包含映射语句 ID 对应的 DataPermission 注解对象
|
||||
if (dataPermissionCacheMap.containsKey(mapperId)) {
|
||||
return dataPermissionCacheMap.get(mapperId);
|
||||
}
|
||||
// 如果缓存中不包含映射语句 ID 对应的 DataPermission 注解对象,则尝试使用类名作为键查找
|
||||
String clazzName = mapperId.substring(0, mapperId.lastIndexOf("."));
|
||||
if (dataPermissionCacheMap.containsKey(clazzName)) {
|
||||
return dataPermissionCacheMap.get(clazzName);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查给定的映射语句 ID 是否有效,即是否能够找到对应的 DataPermission 注解对象
|
||||
*
|
||||
* @param mapperId 映射语句 ID
|
||||
* @return 如果找到对应的 DataPermission 注解对象,则返回 false;否则返回 true
|
||||
*/
|
||||
public boolean invalid(String mapperId) {
|
||||
return getDataPermission(mapperId) == null;
|
||||
}
|
||||
}
|
||||
|
@ -2,11 +2,11 @@ package org.dromara.common.mybatis.helper;
|
||||
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.dromara.common.mybatis.enums.DataBaseType;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
@ -14,7 +14,6 @@ import java.sql.DatabaseMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 数据库助手
|
||||
|
@ -2,14 +2,17 @@ package org.dromara.common.mybatis.helper;
|
||||
|
||||
import cn.dev33.satoken.context.SaHolder;
|
||||
import cn.dev33.satoken.context.model.SaStorage;
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.plugins.IgnoreStrategy;
|
||||
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.dromara.common.core.utils.reflect.ReflectUtils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Stack;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
@ -24,17 +27,37 @@ public class DataPermissionHelper {
|
||||
|
||||
private static final String DATA_PERMISSION_KEY = "data:permission";
|
||||
|
||||
private static final ThreadLocal<Stack<Integer>> REENTRANT_IGNORE = ThreadLocal.withInitial(Stack::new);
|
||||
|
||||
/**
|
||||
* 从上下文中获取指定键的变量值,并将其转换为指定的类型
|
||||
*
|
||||
* @param key 变量的键
|
||||
* @param <T> 变量值的类型
|
||||
* @return 指定键的变量值,如果不存在则返回 null
|
||||
*/
|
||||
public static <T> T getVariable(String key) {
|
||||
Map<String, Object> context = getContext();
|
||||
return (T) context.get(key);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 向上下文中设置指定键的变量值
|
||||
*
|
||||
* @param key 要设置的变量的键
|
||||
* @param value 要设置的变量值
|
||||
*/
|
||||
public static void setVariable(String key, Object value) {
|
||||
Map<String, Object> context = getContext();
|
||||
context.put(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据权限上下文
|
||||
*
|
||||
* @return 存储在SaStorage中的Map对象,用于存储数据权限相关的上下文信息
|
||||
* @throws NullPointerException 如果数据权限上下文类型异常,则抛出NullPointerException
|
||||
*/
|
||||
public static Map<String, Object> getContext() {
|
||||
SaStorage saStorage = SaHolder.getStorage();
|
||||
Object attribute = saStorage.get(DATA_PERMISSION_KEY);
|
||||
@ -48,18 +71,50 @@ public class DataPermissionHelper {
|
||||
throw new NullPointerException("data permission context type exception");
|
||||
}
|
||||
|
||||
private static IgnoreStrategy getIgnoreStrategy() {
|
||||
Object ignoreStrategyLocal = ReflectUtils.getStaticFieldValue(ReflectUtils.getField(InterceptorIgnoreHelper.class, "IGNORE_STRATEGY_LOCAL"));
|
||||
if (ignoreStrategyLocal instanceof ThreadLocal<?> IGNORE_STRATEGY_LOCAL) {
|
||||
if (IGNORE_STRATEGY_LOCAL.get() instanceof IgnoreStrategy ignoreStrategy) {
|
||||
return ignoreStrategy;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 开启忽略数据权限(开启后需手动调用 {@link #disableIgnore()} 关闭)
|
||||
*/
|
||||
public static void enableIgnore() {
|
||||
InterceptorIgnoreHelper.handle(IgnoreStrategy.builder().dataPermission(true).build());
|
||||
IgnoreStrategy ignoreStrategy = getIgnoreStrategy();
|
||||
if (ObjectUtil.isNull(ignoreStrategy)) {
|
||||
InterceptorIgnoreHelper.handle(IgnoreStrategy.builder().dataPermission(true).build());
|
||||
} else {
|
||||
ignoreStrategy.setDataPermission(true);
|
||||
}
|
||||
Stack<Integer> reentrantStack = REENTRANT_IGNORE.get();
|
||||
reentrantStack.push(reentrantStack.size() + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭忽略数据权限
|
||||
*/
|
||||
public static void disableIgnore() {
|
||||
InterceptorIgnoreHelper.clearIgnoreStrategy();
|
||||
IgnoreStrategy ignoreStrategy = getIgnoreStrategy();
|
||||
if (ObjectUtil.isNotNull(ignoreStrategy)) {
|
||||
boolean noOtherIgnoreStrategy = !Boolean.TRUE.equals(ignoreStrategy.getDynamicTableName())
|
||||
&& !Boolean.TRUE.equals(ignoreStrategy.getBlockAttack())
|
||||
&& !Boolean.TRUE.equals(ignoreStrategy.getIllegalSql())
|
||||
&& !Boolean.TRUE.equals(ignoreStrategy.getTenantLine())
|
||||
&& CollectionUtil.isEmpty(ignoreStrategy.getOthers());
|
||||
Stack<Integer> reentrantStack = REENTRANT_IGNORE.get();
|
||||
boolean empty = reentrantStack.isEmpty() || reentrantStack.pop() == 1;
|
||||
if (noOtherIgnoreStrategy && empty) {
|
||||
InterceptorIgnoreHelper.clearIgnoreStrategy();
|
||||
} else if (empty) {
|
||||
ignoreStrategy.setDataPermission(false);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -1,18 +1,16 @@
|
||||
package org.dromara.common.mybatis.interceptor;
|
||||
|
||||
import cn.hutool.core.collection.ConcurrentHashSet;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
|
||||
import com.baomidou.mybatisplus.extension.parser.JsqlParserSupport;
|
||||
import com.baomidou.mybatisplus.extension.plugins.handler.MultiDataPermissionHandler;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.BaseMultiTableInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
|
||||
import org.dromara.common.mybatis.annotation.DataColumn;
|
||||
import org.dromara.common.mybatis.handler.PlusDataPermissionHandler;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.sf.jsqlparser.expression.Expression;
|
||||
import net.sf.jsqlparser.schema.Table;
|
||||
import net.sf.jsqlparser.statement.delete.Delete;
|
||||
import net.sf.jsqlparser.statement.select.PlainSelect;
|
||||
import net.sf.jsqlparser.statement.select.Select;
|
||||
import net.sf.jsqlparser.statement.select.SelectBody;
|
||||
import net.sf.jsqlparser.statement.select.SetOperationList;
|
||||
import net.sf.jsqlparser.statement.update.Update;
|
||||
import org.apache.ibatis.executor.Executor;
|
||||
@ -22,11 +20,11 @@ import org.apache.ibatis.mapping.MappedStatement;
|
||||
import org.apache.ibatis.mapping.SqlCommandType;
|
||||
import org.apache.ibatis.session.ResultHandler;
|
||||
import org.apache.ibatis.session.RowBounds;
|
||||
import org.dromara.common.mybatis.handler.PlusDataPermissionHandler;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 数据权限拦截器
|
||||
@ -34,27 +32,39 @@ import java.util.Set;
|
||||
* @author Lion Li
|
||||
* @version 3.5.0
|
||||
*/
|
||||
public class PlusDataPermissionInterceptor extends JsqlParserSupport implements InnerInterceptor {
|
||||
@Slf4j
|
||||
public class PlusDataPermissionInterceptor extends BaseMultiTableInnerInterceptor implements InnerInterceptor {
|
||||
|
||||
private final PlusDataPermissionHandler dataPermissionHandler;
|
||||
|
||||
private final PlusDataPermissionHandler dataPermissionHandler = new PlusDataPermissionHandler();
|
||||
/**
|
||||
* 无效注解方法缓存用于快速返回
|
||||
* 构造函数,初始化 PlusDataPermissionHandler 实例
|
||||
*
|
||||
* @param mapperPackage 扫描的映射器包
|
||||
*/
|
||||
private final Set<String> invalidCacheSet = new ConcurrentHashSet<>();
|
||||
public PlusDataPermissionInterceptor(String mapperPackage) {
|
||||
this.dataPermissionHandler = new PlusDataPermissionHandler(mapperPackage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在执行查询之前,检查并处理数据权限相关逻辑
|
||||
*
|
||||
* @param executor MyBatis 执行器对象
|
||||
* @param ms 映射语句对象
|
||||
* @param parameter 方法参数
|
||||
* @param rowBounds 分页对象
|
||||
* @param resultHandler 结果处理器
|
||||
* @param boundSql 绑定的 SQL 对象
|
||||
* @throws SQLException 如果发生 SQL 异常
|
||||
*/
|
||||
@Override
|
||||
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
|
||||
// 检查忽略注解
|
||||
// 检查是否需要忽略数据权限处理
|
||||
if (InterceptorIgnoreHelper.willIgnoreDataPermission(ms.getId())) {
|
||||
return;
|
||||
}
|
||||
// 检查是否无效 无数据权限注解
|
||||
if (invalidCacheSet.contains(ms.getId())) {
|
||||
return;
|
||||
}
|
||||
DataColumn[] dataColumns = dataPermissionHandler.findAnnotation(ms.getId());
|
||||
if (ArrayUtil.isEmpty(dataColumns)) {
|
||||
invalidCacheSet.add(ms.getId());
|
||||
// 检查是否缺少有效的数据权限注解
|
||||
if (dataPermissionHandler.invalid(ms.getId())) {
|
||||
return;
|
||||
}
|
||||
// 解析 sql 分配对应方法
|
||||
@ -62,22 +72,27 @@ public class PlusDataPermissionInterceptor extends JsqlParserSupport implements
|
||||
mpBs.sql(parserSingle(mpBs.sql(), ms.getId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 在准备 SQL 语句之前,检查并处理更新和删除操作的数据权限相关逻辑
|
||||
*
|
||||
* @param sh MyBatis StatementHandler 对象
|
||||
* @param connection 数据库连接对象
|
||||
* @param transactionTimeout 事务超时时间
|
||||
*/
|
||||
@Override
|
||||
public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
|
||||
PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
|
||||
MappedStatement ms = mpSh.mappedStatement();
|
||||
// 获取 SQL 命令类型(增、删、改、查)
|
||||
SqlCommandType sct = ms.getSqlCommandType();
|
||||
|
||||
// 只处理更新和删除操作的 SQL 语句
|
||||
if (sct == SqlCommandType.UPDATE || sct == SqlCommandType.DELETE) {
|
||||
if (InterceptorIgnoreHelper.willIgnoreDataPermission(ms.getId())) {
|
||||
return;
|
||||
}
|
||||
// 检查是否无效 无数据权限注解
|
||||
if (invalidCacheSet.contains(ms.getId())) {
|
||||
return;
|
||||
}
|
||||
DataColumn[] dataColumns = dataPermissionHandler.findAnnotation(ms.getId());
|
||||
if (ArrayUtil.isEmpty(dataColumns)) {
|
||||
invalidCacheSet.add(ms.getId());
|
||||
// 检查是否缺少有效的数据权限注解
|
||||
if (dataPermissionHandler.invalid(ms.getId())) {
|
||||
return;
|
||||
}
|
||||
PluginUtils.MPBoundSql mpBs = mpSh.mPBoundSql();
|
||||
@ -85,17 +100,32 @@ public class PlusDataPermissionInterceptor extends JsqlParserSupport implements
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 SELECT 查询语句中的 WHERE 条件
|
||||
*
|
||||
* @param select SELECT 查询对象
|
||||
* @param index 查询语句的索引
|
||||
* @param sql 查询语句
|
||||
* @param obj WHERE 条件参数
|
||||
*/
|
||||
@Override
|
||||
protected void processSelect(Select select, int index, String sql, Object obj) {
|
||||
SelectBody selectBody = select.getSelectBody();
|
||||
if (selectBody instanceof PlainSelect plainSelect) {
|
||||
this.setWhere(plainSelect, (String) obj);
|
||||
} else if (selectBody instanceof SetOperationList setOperationList) {
|
||||
List<SelectBody> selectBodyList = setOperationList.getSelects();
|
||||
if (select instanceof PlainSelect) {
|
||||
this.setWhere((PlainSelect) select, (String) obj);
|
||||
} else if (select instanceof SetOperationList setOperationList) {
|
||||
List<Select> selectBodyList = setOperationList.getSelects();
|
||||
selectBodyList.forEach(s -> this.setWhere((PlainSelect) s, (String) obj));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 UPDATE 语句中的 WHERE 条件
|
||||
*
|
||||
* @param update UPDATE 查询对象
|
||||
* @param index 查询语句的索引
|
||||
* @param sql 查询语句
|
||||
* @param obj WHERE 条件参数
|
||||
*/
|
||||
@Override
|
||||
protected void processUpdate(Update update, int index, String sql, Object obj) {
|
||||
Expression sqlSegment = dataPermissionHandler.getSqlSegment(update.getWhere(), (String) obj, false);
|
||||
@ -104,6 +134,14 @@ public class PlusDataPermissionInterceptor extends JsqlParserSupport implements
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 DELETE 语句中的 WHERE 条件
|
||||
*
|
||||
* @param delete DELETE 查询对象
|
||||
* @param index 查询语句的索引
|
||||
* @param sql 查询语句
|
||||
* @param obj WHERE 条件参数
|
||||
*/
|
||||
@Override
|
||||
protected void processDelete(Delete delete, int index, String sql, Object obj) {
|
||||
Expression sqlSegment = dataPermissionHandler.getSqlSegment(delete.getWhere(), (String) obj, false);
|
||||
@ -113,10 +151,10 @@ public class PlusDataPermissionInterceptor extends JsqlParserSupport implements
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 where 条件
|
||||
* 设置 SELECT 语句的 WHERE 条件
|
||||
*
|
||||
* @param plainSelect 查询对象
|
||||
* @param mappedStatementId 执行方法id
|
||||
* @param plainSelect SELECT 查询对象
|
||||
* @param mappedStatementId 映射语句的 ID
|
||||
*/
|
||||
protected void setWhere(PlainSelect plainSelect, String mappedStatementId) {
|
||||
Expression sqlSegment = dataPermissionHandler.getSqlSegment(plainSelect.getWhere(), mappedStatementId, true);
|
||||
@ -125,5 +163,19 @@ public class PlusDataPermissionInterceptor extends JsqlParserSupport implements
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建表达式,用于处理表的数据权限
|
||||
*
|
||||
* @param table 表对象
|
||||
* @param where WHERE 条件表达式
|
||||
* @param whereSegment WHERE 条件片段
|
||||
* @return 构建的表达式
|
||||
*/
|
||||
@Override
|
||||
public Expression buildTableExpression(Table table, Expression where, String whereSegment) {
|
||||
// 只有新版数据权限处理器才会执行到这里
|
||||
final MultiDataPermissionHandler handler = (MultiDataPermissionHandler) dataPermissionHandler;
|
||||
return handler.getSqlSegment(table, where, whereSegment);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -6,8 +6,6 @@ logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
|
||||
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
|
||||
# 使用日志系统记录 sql
|
||||
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
|
||||
# 设置 p6spy driver 代理
|
||||
#deregisterdrivers=true
|
||||
# 取消JDBC URL前缀
|
||||
useprefix=true
|
||||
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
|
||||
@ -16,13 +14,7 @@ excludecategories=info,debug,result,commit,resultset
|
||||
dateformat=yyyy-MM-dd HH:mm:ss
|
||||
# SQL语句打印时间格式
|
||||
databaseDialectTimestampFormat=yyyy-MM-dd HH:mm:ss
|
||||
# 实际驱动可多个
|
||||
#driverlist=org.h2.Driver
|
||||
# 是否开启慢SQL记录
|
||||
outagedetection=true
|
||||
# 慢SQL记录标准 2 秒
|
||||
outagedetectioninterval=2
|
||||
# 是否过滤 Log
|
||||
filter=true
|
||||
# 过滤 Log 时所排除的 sql 关键字,以逗号分隔
|
||||
exclude=SELECT 1
|
||||
exclude=
|
@ -26,10 +26,46 @@
|
||||
<artifactId>ruoyi-common-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- AWS SDK for Java 2.x -->
|
||||
<dependency>
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-java-sdk-s3</artifactId>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>s3</artifactId>
|
||||
<exclusions>
|
||||
<!-- 将基于 Netty 的 HTTP 客户端从类路径中移除 -->
|
||||
<exclusion>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>netty-nio-client</artifactId>
|
||||
</exclusion>
|
||||
<!-- 将基于 CRT 的 HTTP 客户端从类路径中移除 -->
|
||||
<exclusion>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>aws-crt-client</artifactId>
|
||||
</exclusion>
|
||||
<!-- 将基于 Apache 的 HTTP 客户端从类路径中移除 -->
|
||||
<exclusion>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>apache-client</artifactId>
|
||||
</exclusion>
|
||||
<!-- 将配置基于 URL 连接的 HTTP 客户端从类路径中移除 -->
|
||||
<exclusion>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>url-connection-client</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!-- 使用AWS基于 CRT 的 S3 客户端 -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk.crt</groupId>
|
||||
<artifactId>aws-crt</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 基于 AWS CRT 的 S3 客户端的性能增强的 S3 传输管理器 -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>s3-transfer-manager</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
@ -2,73 +2,117 @@ package org.dromara.common.oss.core;
|
||||
|
||||
import cn.hutool.core.io.IoUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.amazonaws.ClientConfiguration;
|
||||
import com.amazonaws.HttpMethod;
|
||||
import com.amazonaws.Protocol;
|
||||
import com.amazonaws.auth.AWSCredentials;
|
||||
import com.amazonaws.auth.AWSCredentialsProvider;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.client.builder.AwsClientBuilder;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3Client;
|
||||
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
|
||||
import com.amazonaws.services.s3.model.*;
|
||||
import org.dromara.common.core.constant.Constants;
|
||||
import org.dromara.common.core.utils.DateUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.core.utils.file.FileUtils;
|
||||
import org.dromara.common.oss.constant.OssConstant;
|
||||
import org.dromara.common.oss.entity.UploadResult;
|
||||
import org.dromara.common.oss.enumd.AccessPolicyType;
|
||||
import org.dromara.common.oss.enumd.PolicyType;
|
||||
import org.dromara.common.oss.exception.OssException;
|
||||
import org.dromara.common.oss.properties.OssProperties;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.core.ResponseInputStream;
|
||||
import software.amazon.awssdk.core.async.AsyncRequestBody;
|
||||
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
|
||||
import software.amazon.awssdk.core.async.BlockingInputStreamAsyncRequestBody;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.s3.S3AsyncClient;
|
||||
import software.amazon.awssdk.services.s3.S3Configuration;
|
||||
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
|
||||
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
|
||||
import software.amazon.awssdk.services.s3.model.S3Exception;
|
||||
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
|
||||
import software.amazon.awssdk.transfer.s3.S3TransferManager;
|
||||
import software.amazon.awssdk.transfer.s3.model.*;
|
||||
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.*;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.util.Date;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* S3 存储协议 所有兼容S3协议的云厂商均支持
|
||||
* 阿里云 腾讯云 七牛云 minio
|
||||
*
|
||||
* @author Lion Li
|
||||
* @author AprilWind
|
||||
*/
|
||||
public class OssClient {
|
||||
|
||||
/**
|
||||
* 服务商
|
||||
*/
|
||||
private final String configKey;
|
||||
|
||||
/**
|
||||
* 配置属性
|
||||
*/
|
||||
private final OssProperties properties;
|
||||
|
||||
private final AmazonS3 client;
|
||||
/**
|
||||
* Amazon S3 异步客户端
|
||||
*/
|
||||
private final S3AsyncClient client;
|
||||
|
||||
/**
|
||||
* 用于管理 S3 数据传输的高级工具
|
||||
*/
|
||||
private final S3TransferManager transferManager;
|
||||
|
||||
/**
|
||||
* AWS S3 预签名 URL 的生成器
|
||||
*/
|
||||
private final S3Presigner presigner;
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
*
|
||||
* @param configKey 配置键
|
||||
* @param ossProperties Oss配置属性
|
||||
*/
|
||||
public OssClient(String configKey, OssProperties ossProperties) {
|
||||
this.configKey = configKey;
|
||||
this.properties = ossProperties;
|
||||
try {
|
||||
AwsClientBuilder.EndpointConfiguration endpointConfig =
|
||||
new AwsClientBuilder.EndpointConfiguration(properties.getEndpoint(), properties.getRegion());
|
||||
// 创建 AWS 认证信息
|
||||
StaticCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create(properties.getAccessKey(), properties.getSecretKey()));
|
||||
|
||||
AWSCredentials credentials = new BasicAWSCredentials(properties.getAccessKey(), properties.getSecretKey());
|
||||
AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
|
||||
ClientConfiguration clientConfig = new ClientConfiguration();
|
||||
if (OssConstant.IS_HTTPS.equals(properties.getIsHttps())) {
|
||||
clientConfig.setProtocol(Protocol.HTTPS);
|
||||
} else {
|
||||
clientConfig.setProtocol(Protocol.HTTP);
|
||||
}
|
||||
AmazonS3ClientBuilder build = AmazonS3Client.builder()
|
||||
.withEndpointConfiguration(endpointConfig)
|
||||
.withClientConfiguration(clientConfig)
|
||||
.withCredentials(credentialsProvider)
|
||||
.disableChunkedEncoding();
|
||||
if (!StringUtils.containsAny(properties.getEndpoint(), OssConstant.CLOUD_SERVICE)) {
|
||||
// minio 使用https限制使用域名访问 需要此配置 站点填域名
|
||||
build.enablePathStyleAccess();
|
||||
}
|
||||
this.client = build.build();
|
||||
//MinIO 使用 HTTPS 限制使用域名访问,站点填域名。需要启用路径样式访问
|
||||
boolean isStyle = !StringUtils.containsAny(properties.getEndpoint(), OssConstant.CLOUD_SERVICE);
|
||||
|
||||
//创建AWS基于 CRT 的 S3 客户端
|
||||
this.client = S3AsyncClient.crtBuilder()
|
||||
.credentialsProvider(credentialsProvider)
|
||||
.endpointOverride(URI.create(getEndpoint()))
|
||||
.region(of())
|
||||
.targetThroughputInGbps(20.0)
|
||||
.minimumPartSizeInBytes(10 * 1025 * 1024L)
|
||||
.checksumValidationEnabled(false)
|
||||
.forcePathStyle(isStyle)
|
||||
.build();
|
||||
|
||||
//AWS基于 CRT 的 S3 AsyncClient 实例用作 S3 传输管理器的底层客户端
|
||||
this.transferManager = S3TransferManager.builder().s3Client(this.client).build();
|
||||
|
||||
// 创建 S3 配置对象
|
||||
S3Configuration config = S3Configuration.builder().chunkedEncodingEnabled(false)
|
||||
.pathStyleAccessEnabled(isStyle).build();
|
||||
|
||||
// 创建 预签名 URL 的生成器 实例,用于生成 S3 预签名 URL
|
||||
this.presigner = S3Presigner.builder()
|
||||
.region(of())
|
||||
.credentialsProvider(credentialsProvider)
|
||||
.endpointOverride(URI.create(getDomain()))
|
||||
.serviceConfiguration(config)
|
||||
.build();
|
||||
|
||||
// 创建存储桶
|
||||
createBucket();
|
||||
} catch (Exception e) {
|
||||
if (e instanceof OssException) {
|
||||
@ -78,126 +122,195 @@ public class OssClient {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步创建存储桶
|
||||
* 如果存储桶不存在,会进行创建;如果存储桶存在,不执行任何操作
|
||||
*
|
||||
* @throws OssException 当创建存储桶时发生异常时抛出
|
||||
*/
|
||||
public void createBucket() {
|
||||
String bucketName = properties.getBucketName();
|
||||
try {
|
||||
String bucketName = properties.getBucketName();
|
||||
if (client.doesBucketExistV2(bucketName)) {
|
||||
return;
|
||||
// 尝试获取存储桶的信息
|
||||
client.headBucket(
|
||||
x -> x.bucket(bucketName)
|
||||
.build())
|
||||
.join();
|
||||
} catch (Exception ex) {
|
||||
if (ex.getCause() instanceof NoSuchBucketException) {
|
||||
try {
|
||||
// 存储桶不存在,尝试创建存储桶
|
||||
client.createBucket(
|
||||
x -> x.bucket(bucketName))
|
||||
.join();
|
||||
|
||||
// 设置存储桶的访问策略(Bucket Policy)
|
||||
client.putBucketPolicy(
|
||||
x -> x.bucket(bucketName)
|
||||
.policy(getPolicy(bucketName, getAccessPolicy().getPolicyType())))
|
||||
.join();
|
||||
} catch (S3Exception e) {
|
||||
// 存储桶创建或策略设置失败
|
||||
throw new OssException("创建Bucket失败, 请核对配置信息:[" + e.getMessage() + "]");
|
||||
}
|
||||
} else {
|
||||
throw new OssException("判断Bucket是否存在失败,请核对配置信息:[" + ex.getMessage() + "]");
|
||||
}
|
||||
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
|
||||
AccessPolicyType accessPolicy = getAccessPolicy();
|
||||
createBucketRequest.setCannedAcl(accessPolicy.getAcl());
|
||||
client.createBucket(createBucketRequest);
|
||||
client.setBucketPolicy(bucketName, getPolicy(bucketName, accessPolicy.getPolicyType()));
|
||||
} catch (Exception e) {
|
||||
throw new OssException("创建Bucket失败, 请核对配置信息:[" + e.getMessage() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
public UploadResult upload(byte[] data, String path, String contentType) {
|
||||
return upload(new ByteArrayInputStream(data), path, contentType);
|
||||
/**
|
||||
* 上传文件到 Amazon S3,并返回上传结果
|
||||
*
|
||||
* @param filePath 本地文件路径
|
||||
* @param key 在 Amazon S3 中的对象键
|
||||
* @param md5Digest 本地文件的 MD5 哈希值(可选)
|
||||
* @param contentType 文件内容类型
|
||||
* @return UploadResult 包含上传后的文件信息
|
||||
* @throws OssException 如果上传失败,抛出自定义异常
|
||||
*/
|
||||
public UploadResult upload(Path filePath, String key, String md5Digest, String contentType) {
|
||||
try {
|
||||
// 构建上传请求对象
|
||||
FileUpload fileUpload = transferManager.uploadFile(
|
||||
x -> x.putObjectRequest(
|
||||
y -> y.bucket(properties.getBucketName())
|
||||
.key(key)
|
||||
.contentMD5(StringUtils.isNotEmpty(md5Digest) ? md5Digest : null)
|
||||
.contentType(contentType)
|
||||
.acl(getAccessPolicy().getObjectCannedACL())
|
||||
.build())
|
||||
.addTransferListener(LoggingTransferListener.create())
|
||||
.source(filePath).build());
|
||||
|
||||
// 等待上传完成并获取上传结果
|
||||
CompletedFileUpload uploadResult = fileUpload.completionFuture().join();
|
||||
String eTag = uploadResult.response().eTag();
|
||||
|
||||
// 提取上传结果中的 ETag,并构建一个自定义的 UploadResult 对象
|
||||
return UploadResult.builder().url(getUrl() + StringUtils.SLASH + key).filename(key).eTag(eTag).build();
|
||||
} catch (Exception e) {
|
||||
// 捕获异常并抛出自定义异常
|
||||
throw new OssException("上传文件失败,请检查配置信息:[" + e.getMessage() + "]");
|
||||
} finally {
|
||||
// 无论上传是否成功,最终都会删除临时文件
|
||||
FileUtils.del(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
public UploadResult upload(InputStream inputStream, String path, String contentType) {
|
||||
/**
|
||||
* 上传 InputStream 到 Amazon S3
|
||||
*
|
||||
* @param inputStream 要上传的输入流
|
||||
* @param key 在 Amazon S3 中的对象键
|
||||
* @param length 输入流的长度
|
||||
* @param contentType 文件内容类型
|
||||
* @return UploadResult 包含上传后的文件信息
|
||||
* @throws OssException 如果上传失败,抛出自定义异常
|
||||
*/
|
||||
public UploadResult upload(InputStream inputStream, String key, Long length, String contentType) {
|
||||
// 如果输入流不是 ByteArrayInputStream,则将其读取为字节数组再创建 ByteArrayInputStream
|
||||
if (!(inputStream instanceof ByteArrayInputStream)) {
|
||||
inputStream = new ByteArrayInputStream(IoUtil.readBytes(inputStream));
|
||||
}
|
||||
try {
|
||||
ObjectMetadata metadata = new ObjectMetadata();
|
||||
metadata.setContentType(contentType);
|
||||
metadata.setContentLength(inputStream.available());
|
||||
PutObjectRequest putObjectRequest = new PutObjectRequest(properties.getBucketName(), path, inputStream, metadata);
|
||||
// 设置上传对象的 Acl 为公共读
|
||||
putObjectRequest.setCannedAcl(getAccessPolicy().getAcl());
|
||||
client.putObject(putObjectRequest);
|
||||
// 创建异步请求体(length如果为空会报错)
|
||||
BlockingInputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingInputStream(length);
|
||||
|
||||
// 使用 transferManager 进行上传
|
||||
Upload upload = transferManager.upload(
|
||||
x -> x.requestBody(body)
|
||||
.putObjectRequest(
|
||||
y -> y.bucket(properties.getBucketName())
|
||||
.key(key)
|
||||
.contentType(contentType)
|
||||
.acl(getAccessPolicy().getObjectCannedACL())
|
||||
.build())
|
||||
.build());
|
||||
|
||||
// 将输入流写入请求体
|
||||
body.writeInputStream(inputStream);
|
||||
|
||||
// 等待文件上传操作完成
|
||||
CompletedUpload uploadResult = upload.completionFuture().join();
|
||||
String eTag = uploadResult.response().eTag();
|
||||
|
||||
// 提取上传结果中的 ETag,并构建一个自定义的 UploadResult 对象
|
||||
return UploadResult.builder().url(getUrl() + StringUtils.SLASH + key).filename(key).eTag(eTag).build();
|
||||
} catch (Exception e) {
|
||||
throw new OssException("上传文件失败,请检查配置信息:[" + e.getMessage() + "]");
|
||||
}
|
||||
return UploadResult.builder().url(getUrl() + "/" + path).filename(path).build();
|
||||
}
|
||||
|
||||
public UploadResult upload(File file, String path) {
|
||||
try {
|
||||
PutObjectRequest putObjectRequest = new PutObjectRequest(properties.getBucketName(), path, file);
|
||||
// 设置上传对象的 Acl 为公共读
|
||||
putObjectRequest.setCannedAcl(getAccessPolicy().getAcl());
|
||||
client.putObject(putObjectRequest);
|
||||
} catch (Exception e) {
|
||||
throw new OssException("上传文件失败,请检查配置信息:[" + e.getMessage() + "]");
|
||||
}
|
||||
return UploadResult.builder().url(getUrl() + "/" + path).filename(path).build();
|
||||
}
|
||||
|
||||
public void delete(String path) {
|
||||
path = path.replace(getUrl() + "/", "");
|
||||
try {
|
||||
client.deleteObject(properties.getBucketName(), path);
|
||||
} catch (Exception e) {
|
||||
throw new OssException("删除文件失败,请检查配置信息:[" + e.getMessage() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
public UploadResult uploadSuffix(byte[] data, String suffix, String contentType) {
|
||||
return upload(data, getPath(properties.getPrefix(), suffix), contentType);
|
||||
}
|
||||
|
||||
public UploadResult uploadSuffix(InputStream inputStream, String suffix, String contentType) {
|
||||
return upload(inputStream, getPath(properties.getPrefix(), suffix), contentType);
|
||||
}
|
||||
|
||||
public UploadResult uploadSuffix(File file, String suffix) {
|
||||
return upload(file, getPath(properties.getPrefix(), suffix));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件元数据
|
||||
* 下载文件从 Amazon S3 到临时目录
|
||||
*
|
||||
* @param path 完整文件路径
|
||||
* @param path 文件在 Amazon S3 中的对象键
|
||||
* @return 下载后的文件在本地的临时路径
|
||||
* @throws OssException 如果下载失败,抛出自定义异常
|
||||
*/
|
||||
public ObjectMetadata getObjectMetadata(String path) {
|
||||
path = path.replace(getUrl() + "/", "");
|
||||
S3Object object = client.getObject(properties.getBucketName(), path);
|
||||
return object.getObjectMetadata();
|
||||
public Path fileDownload(String path) {
|
||||
// 构建临时文件
|
||||
Path tempFilePath = FileUtils.createTempFile().toPath();
|
||||
// 使用 S3TransferManager 下载文件
|
||||
FileDownload downloadFile = transferManager.downloadFile(
|
||||
x -> x.getObjectRequest(
|
||||
y -> y.bucket(properties.getBucketName())
|
||||
.key(removeBaseUrl(path))
|
||||
.build())
|
||||
.addTransferListener(LoggingTransferListener.create())
|
||||
.destination(tempFilePath)
|
||||
.build());
|
||||
// 等待文件下载操作完成
|
||||
downloadFile.completionFuture().join();
|
||||
return tempFilePath;
|
||||
}
|
||||
|
||||
public InputStream getObjectContent(String path) {
|
||||
path = path.replace(getUrl() + "/", "");
|
||||
S3Object object = client.getObject(properties.getBucketName(), path);
|
||||
return object.getObjectContent();
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
String domain = properties.getDomain();
|
||||
String endpoint = properties.getEndpoint();
|
||||
String header = OssConstant.IS_HTTPS.equals(properties.getIsHttps()) ? "https://" : "http://";
|
||||
// 云服务商直接返回
|
||||
if (StringUtils.containsAny(endpoint, OssConstant.CLOUD_SERVICE)) {
|
||||
if (StringUtils.isNotBlank(domain)) {
|
||||
return header + domain;
|
||||
/**
|
||||
* 下载文件从 Amazon S3 到 输出流
|
||||
*
|
||||
* @param key 文件在 Amazon S3 中的对象键
|
||||
* @param out 输出流
|
||||
* @return 输出流中写入的字节数(长度)
|
||||
* @throws OssException 如果下载失败,抛出自定义异常
|
||||
*/
|
||||
public long download(String key, OutputStream out) {
|
||||
try {
|
||||
// 构建下载请求
|
||||
DownloadRequest<ResponseInputStream<GetObjectResponse>> downloadRequest = DownloadRequest.builder()
|
||||
// 文件对象
|
||||
.getObjectRequest(y -> y.bucket(properties.getBucketName())
|
||||
.key(key)
|
||||
.build())
|
||||
.addTransferListener(LoggingTransferListener.create())
|
||||
// 使用订阅转换器
|
||||
.responseTransformer(AsyncResponseTransformer.toBlockingInputStream())
|
||||
.build();
|
||||
// 使用 S3TransferManager 下载文件
|
||||
Download<ResponseInputStream<GetObjectResponse>> responseFuture = transferManager.download(downloadRequest);
|
||||
// 输出到流中
|
||||
try (ResponseInputStream<GetObjectResponse> responseStream = responseFuture.completionFuture().join().result()) { // auto-closeable stream
|
||||
return responseStream.transferTo(out); // 阻塞调用线程 blocks the calling thread
|
||||
}
|
||||
return header + properties.getBucketName() + "." + endpoint;
|
||||
} catch (Exception e) {
|
||||
throw new OssException("文件下载失败,错误信息:[" + e.getMessage() + "]");
|
||||
}
|
||||
// minio 单独处理
|
||||
if (StringUtils.isNotBlank(domain)) {
|
||||
return header + domain + "/" + properties.getBucketName();
|
||||
}
|
||||
return header + endpoint + "/" + properties.getBucketName();
|
||||
}
|
||||
|
||||
public String getPath(String prefix, String suffix) {
|
||||
// 生成uuid
|
||||
String uuid = IdUtil.fastSimpleUUID();
|
||||
// 文件路径
|
||||
String path = DateUtils.datePath() + "/" + uuid;
|
||||
if (StringUtils.isNotBlank(prefix)) {
|
||||
path = prefix + "/" + path;
|
||||
/**
|
||||
* 删除云存储服务中指定路径下文件
|
||||
*
|
||||
* @param path 指定路径
|
||||
*/
|
||||
public void delete(String path) {
|
||||
try {
|
||||
client.deleteObject(
|
||||
x -> x.bucket(properties.getBucketName())
|
||||
.key(removeBaseUrl(path))
|
||||
.build());
|
||||
} catch (Exception e) {
|
||||
throw new OssException("删除文件失败,请检查配置信息:[" + e.getMessage() + "]");
|
||||
}
|
||||
return path + suffix;
|
||||
}
|
||||
|
||||
|
||||
public String getConfigKey() {
|
||||
return configKey;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -207,14 +320,189 @@ public class OssClient {
|
||||
* @param second 授权时间
|
||||
*/
|
||||
public String getPrivateUrl(String objectKey, Integer second) {
|
||||
GeneratePresignedUrlRequest generatePresignedUrlRequest =
|
||||
new GeneratePresignedUrlRequest(properties.getBucketName(), objectKey)
|
||||
.withMethod(HttpMethod.GET)
|
||||
.withExpiration(new Date(System.currentTimeMillis() + 1000L * second));
|
||||
URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
|
||||
// 使用 AWS S3 预签名 URL 的生成器 获取对象的预签名 URL
|
||||
URL url = presigner.presignGetObject(
|
||||
x -> x.signatureDuration(Duration.ofSeconds(second))
|
||||
.getObjectRequest(
|
||||
y -> y.bucket(properties.getBucketName())
|
||||
.key(objectKey)
|
||||
.build())
|
||||
.build())
|
||||
.url();
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传 byte[] 数据到 Amazon S3,使用指定的后缀构造对象键。
|
||||
*
|
||||
* @param data 要上传的 byte[] 数据
|
||||
* @param suffix 对象键的后缀
|
||||
* @return UploadResult 包含上传后的文件信息
|
||||
* @throws OssException 如果上传失败,抛出自定义异常
|
||||
*/
|
||||
public UploadResult uploadSuffix(byte[] data, String suffix) {
|
||||
return upload(new ByteArrayInputStream(data), getPath(properties.getPrefix(), suffix), Long.valueOf(data.length), FileUtils.getMimeType(suffix));
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传 InputStream 到 Amazon S3,使用指定的后缀构造对象键。
|
||||
*
|
||||
* @param inputStream 要上传的输入流
|
||||
* @param suffix 对象键的后缀
|
||||
* @param length 输入流的长度
|
||||
* @return UploadResult 包含上传后的文件信息
|
||||
* @throws OssException 如果上传失败,抛出自定义异常
|
||||
*/
|
||||
public UploadResult uploadSuffix(InputStream inputStream, String suffix, Long length) {
|
||||
return upload(inputStream, getPath(properties.getPrefix(), suffix), length, FileUtils.getMimeType(suffix));
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到 Amazon S3,使用指定的后缀构造对象键
|
||||
*
|
||||
* @param file 要上传的文件
|
||||
* @param suffix 对象键的后缀
|
||||
* @return UploadResult 包含上传后的文件信息
|
||||
* @throws OssException 如果上传失败,抛出自定义异常
|
||||
*/
|
||||
public UploadResult uploadSuffix(File file, String suffix) {
|
||||
return upload(file.toPath(), getPath(properties.getPrefix(), suffix), null, FileUtils.getMimeType(suffix));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件输入流
|
||||
*
|
||||
* @param path 完整文件路径
|
||||
* @return 输入流
|
||||
*/
|
||||
public InputStream getObjectContent(String path) throws IOException {
|
||||
// 下载文件到临时目录
|
||||
Path tempFilePath = fileDownload(path);
|
||||
// 创建输入流
|
||||
InputStream inputStream = Files.newInputStream(tempFilePath);
|
||||
// 删除临时文件
|
||||
FileUtils.del(tempFilePath);
|
||||
// 返回对象内容的输入流
|
||||
return inputStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 S3 客户端的终端点 URL
|
||||
*
|
||||
* @return 终端点 URL
|
||||
*/
|
||||
public String getEndpoint() {
|
||||
// 根据配置文件中的是否使用 HTTPS,设置协议头部
|
||||
String header = getIsHttps();
|
||||
// 拼接协议头部和终端点,得到完整的终端点 URL
|
||||
return header + properties.getEndpoint();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 S3 客户端的终端点 URL(自定义域名)
|
||||
*
|
||||
* @return 终端点 URL
|
||||
*/
|
||||
public String getDomain() {
|
||||
// 从配置中获取域名、终端点、是否使用 HTTPS 等信息
|
||||
String domain = properties.getDomain();
|
||||
String endpoint = properties.getEndpoint();
|
||||
String header = getIsHttps();
|
||||
|
||||
// 如果是云服务商,直接返回域名或终端点
|
||||
if (StringUtils.containsAny(endpoint, OssConstant.CLOUD_SERVICE)) {
|
||||
return StringUtils.isNotEmpty(domain) ? header + domain : header + endpoint;
|
||||
}
|
||||
|
||||
// 如果是 MinIO,处理域名并返回
|
||||
if (StringUtils.isNotEmpty(domain)) {
|
||||
return domain.startsWith(Constants.HTTPS) || domain.startsWith(Constants.HTTP) ? domain : header + domain;
|
||||
}
|
||||
|
||||
// 返回终端点
|
||||
return header + endpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据传入的 region 参数返回相应的 AWS 区域
|
||||
* 如果 region 参数非空,使用 Region.of 方法创建并返回对应的 AWS 区域对象
|
||||
* 如果 region 参数为空,返回一个默认的 AWS 区域(例如,us-east-1),作为广泛支持的区域
|
||||
*
|
||||
* @return 对应的 AWS 区域对象,或者默认的广泛支持的区域(us-east-1)
|
||||
*/
|
||||
public Region of() {
|
||||
//AWS 区域字符串
|
||||
String region = properties.getRegion();
|
||||
// 如果 region 参数非空,使用 Region.of 方法创建对应的 AWS 区域对象,否则返回默认区域
|
||||
return StringUtils.isNotEmpty(region) ? Region.of(region) : Region.US_EAST_1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取云存储服务的URL
|
||||
*
|
||||
* @return 文件路径
|
||||
*/
|
||||
public String getUrl() {
|
||||
String domain = properties.getDomain();
|
||||
String endpoint = properties.getEndpoint();
|
||||
String header = getIsHttps();
|
||||
// 云服务商直接返回
|
||||
if (StringUtils.containsAny(endpoint, OssConstant.CLOUD_SERVICE)) {
|
||||
return header + (StringUtils.isNotEmpty(domain) ? domain : properties.getBucketName() + "." + endpoint);
|
||||
}
|
||||
// MinIO 单独处理
|
||||
if (StringUtils.isNotEmpty(domain)) {
|
||||
// 如果 domain 以 "https://" 或 "http://" 开头
|
||||
return (domain.startsWith(Constants.HTTPS) || domain.startsWith(Constants.HTTP)) ?
|
||||
domain + StringUtils.SLASH + properties.getBucketName() : header + domain + StringUtils.SLASH + properties.getBucketName();
|
||||
}
|
||||
return header + endpoint + StringUtils.SLASH + properties.getBucketName();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成一个符合特定规则的、唯一的文件路径。通过使用日期、UUID、前缀和后缀等元素的组合,确保了文件路径的独一无二性
|
||||
*
|
||||
* @param prefix 前缀
|
||||
* @param suffix 后缀
|
||||
* @return 文件路径
|
||||
*/
|
||||
public String getPath(String prefix, String suffix) {
|
||||
// 生成uuid
|
||||
String uuid = IdUtil.fastSimpleUUID();
|
||||
// 生成日期路径
|
||||
String datePath = DateUtils.datePath();
|
||||
// 拼接路径
|
||||
String path = StringUtils.isNotEmpty(prefix) ?
|
||||
prefix + StringUtils.SLASH + datePath + StringUtils.SLASH + uuid : datePath + StringUtils.SLASH + uuid;
|
||||
return path + suffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除路径中的基础URL部分,得到相对路径
|
||||
*
|
||||
* @param path 完整的路径,包括基础URL和相对路径
|
||||
* @return 去除基础URL后的相对路径
|
||||
*/
|
||||
public String removeBaseUrl(String path) {
|
||||
return path.replace(getUrl() + StringUtils.SLASH, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务商
|
||||
*/
|
||||
public String getConfigKey() {
|
||||
return configKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取是否使用 HTTPS 的配置,并返回相应的协议头部。
|
||||
*
|
||||
* @return 协议头部,根据是否使用 HTTPS 返回 "https://" 或 "http://"
|
||||
*/
|
||||
public String getIsHttps() {
|
||||
return OssConstant.IS_HTTPS.equals(properties.getIsHttps()) ? Constants.HTTPS : Constants.HTTP;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查配置是否相同
|
||||
*/
|
||||
@ -231,32 +519,77 @@ public class OssClient {
|
||||
return AccessPolicyType.getByType(properties.getAccessPolicy());
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 AWS S3 存储桶访问策略
|
||||
*
|
||||
* @param bucketName 存储桶
|
||||
* @param policyType 桶策略类型
|
||||
* @return 符合 AWS S3 存储桶访问策略格式的字符串
|
||||
*/
|
||||
private static String getPolicy(String bucketName, PolicyType policyType) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("{\n\"Statement\": [\n{\n\"Action\": [\n");
|
||||
builder.append(switch (policyType) {
|
||||
case WRITE -> "\"s3:GetBucketLocation\",\n\"s3:ListBucketMultipartUploads\"\n";
|
||||
case READ_WRITE -> "\"s3:GetBucketLocation\",\n\"s3:ListBucket\",\n\"s3:ListBucketMultipartUploads\"\n";
|
||||
default -> "\"s3:GetBucketLocation\"\n";
|
||||
});
|
||||
builder.append("],\n\"Effect\": \"Allow\",\n\"Principal\": \"*\",\n\"Resource\": \"arn:aws:s3:::");
|
||||
builder.append(bucketName);
|
||||
builder.append("\"\n},\n");
|
||||
if (policyType == PolicyType.READ) {
|
||||
builder.append("{\n\"Action\": [\n\"s3:ListBucket\"\n],\n\"Effect\": \"Deny\",\n\"Principal\": \"*\",\n\"Resource\": \"arn:aws:s3:::");
|
||||
builder.append(bucketName);
|
||||
builder.append("\"\n},\n");
|
||||
}
|
||||
builder.append("{\n\"Action\": ");
|
||||
builder.append(switch (policyType) {
|
||||
case WRITE -> "[\n\"s3:AbortMultipartUpload\",\n\"s3:DeleteObject\",\n\"s3:ListMultipartUploadParts\",\n\"s3:PutObject\"\n],\n";
|
||||
case READ_WRITE -> "[\n\"s3:AbortMultipartUpload\",\n\"s3:DeleteObject\",\n\"s3:GetObject\",\n\"s3:ListMultipartUploadParts\",\n\"s3:PutObject\"\n],\n";
|
||||
default -> "\"s3:GetObject\",\n";
|
||||
});
|
||||
builder.append("\"Effect\": \"Allow\",\n\"Principal\": \"*\",\n\"Resource\": \"arn:aws:s3:::");
|
||||
builder.append(bucketName);
|
||||
builder.append("/*\"\n}\n],\n\"Version\": \"2012-10-17\"\n}\n");
|
||||
return builder.toString();
|
||||
String policy = switch (policyType) {
|
||||
case WRITE -> """
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []
|
||||
}
|
||||
""";
|
||||
case READ_WRITE -> """
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": [
|
||||
"s3:GetBucketLocation",
|
||||
"s3:ListBucket",
|
||||
"s3:ListBucketMultipartUploads"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::bucketName"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": [
|
||||
"s3:AbortMultipartUpload",
|
||||
"s3:DeleteObject",
|
||||
"s3:GetObject",
|
||||
"s3:ListMultipartUploadParts",
|
||||
"s3:PutObject"
|
||||
],
|
||||
"Resource": "arn:aws:s3:::bucketName/*"
|
||||
}
|
||||
]
|
||||
}
|
||||
""";
|
||||
case READ -> """
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": ["s3:GetBucketLocation"],
|
||||
"Resource": "arn:aws:s3:::bucketName"
|
||||
},
|
||||
{
|
||||
"Effect": "Deny",
|
||||
"Principal": "*",
|
||||
"Action": ["s3:ListBucket"],
|
||||
"Resource": "arn:aws:s3:::bucketName"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:GetObject",
|
||||
"Resource": "arn:aws:s3:::bucketName/*"
|
||||
}
|
||||
]
|
||||
}
|
||||
""";
|
||||
};
|
||||
return policy.replaceAll("bucketName", bucketName);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -21,4 +21,10 @@ public class UploadResult {
|
||||
* 文件名
|
||||
*/
|
||||
private String filename;
|
||||
|
||||
/**
|
||||
* 已上传对象的实体标记(用来校验文件)
|
||||
*/
|
||||
private String eTag;
|
||||
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user