mirror of
https://gitee.com/y_project/RuoYi-Cloud.git
synced 2026-01-27 04:01:56 +08:00
Compare commits
83 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1abf802a09 | ||
|
|
2bb0eb1edb | ||
|
|
1a12d56cc3 | ||
|
|
45e5395550 | ||
|
|
692cc84693 | ||
|
|
b812e01100 | ||
|
|
594329127f | ||
|
|
cdc813c453 | ||
|
|
3d7fe2a288 | ||
|
|
93920707b5 | ||
|
|
84ffdaefe2 | ||
|
|
0422f858f7 | ||
|
|
01c3019cea | ||
|
|
24fb0b712a | ||
|
|
8fdcd576c9 | ||
|
|
07df90f99b | ||
|
|
7bd762267b | ||
|
|
512c6acebc | ||
|
|
ad928ee719 | ||
|
|
04d8c97c62 | ||
|
|
9fc5d74f6e | ||
|
|
f245105b58 | ||
|
|
c0cc0bdf84 | ||
|
|
c04ea0221a | ||
|
|
d52f6673bc | ||
|
|
dce8ee4236 | ||
|
|
f64f806a42 | ||
|
|
fbbc91ea0a | ||
|
|
c2bd0ace6e | ||
|
|
6b74ea676c | ||
|
|
86c7a763bc | ||
|
|
3eac04311f | ||
|
|
679756c633 | ||
|
|
2115edcfb4 | ||
|
|
8acb322d49 | ||
|
|
f4f89f9de6 | ||
|
|
5d1701fd69 | ||
|
|
fec24d6785 | ||
|
|
00e2c7f04d | ||
|
|
0e21fab978 | ||
|
|
4ec6d51aca | ||
|
|
15a4a5350d | ||
|
|
9277d7173d | ||
|
|
35f8665dac | ||
|
|
8601b26cff | ||
|
|
eda2ec10f4 | ||
|
|
fc48704057 | ||
|
|
00345099cf | ||
|
|
155b585ae5 | ||
|
|
0ffefeb420 | ||
|
|
dbadce31c6 | ||
|
|
857a5b26e7 | ||
|
|
ca97fc0b5d | ||
|
|
293b855866 | ||
|
|
f9d537b567 | ||
|
|
d42a6751e3 | ||
|
|
f124236a64 | ||
|
|
6704db8108 | ||
|
|
179062e6e5 | ||
|
|
397e821824 | ||
|
|
6b25828113 | ||
|
|
bd7ae4e96b | ||
|
|
5f5c4e8415 | ||
|
|
66e8b59e26 | ||
|
|
a7d93d38ce | ||
|
|
ba3549e824 | ||
|
|
e2c4ca4922 | ||
|
|
1305507bf4 | ||
|
|
c789ef147d | ||
|
|
1ffee7ac0b | ||
|
|
7401297236 | ||
|
|
6f1dd1125b | ||
|
|
82eeb86d60 | ||
|
|
f5cee45345 | ||
|
|
1524005060 | ||
|
|
b70e8ad81e | ||
|
|
a2c265848d | ||
|
|
19e5f11fd3 | ||
|
|
8d99adceb2 | ||
|
|
f1bc33e80d | ||
|
|
6bd7e183f6 | ||
|
|
7d94113d24 | ||
|
|
97ebab0c67 |
16
README.md
16
README.md
@@ -2,12 +2,13 @@
|
|||||||
|
|
||||||
* 采用前后端分离的模式,微服务版本前端(基于 [RuoYi-Vue](https://gitee.com/y_project/RuoYi-Vue))。
|
* 采用前后端分离的模式,微服务版本前端(基于 [RuoYi-Vue](https://gitee.com/y_project/RuoYi-Vue))。
|
||||||
* 后端采用Spring Boot、Spring Cloud & Alibaba。
|
* 后端采用Spring Boot、Spring Cloud & Alibaba。
|
||||||
* 注册中心、配置中心选型Nacos,权限认证使用OAuth2。
|
* 注册中心、配置中心选型Nacos,权限认证使用Redis。
|
||||||
* 流量控制框架选型Sentinel。
|
* 流量控制框架选型Sentinel。
|
||||||
* 如需不分离应用,请移步 [RuoYi](https://gitee.com/y_project/RuoYi),如需分离应用,请移步 [RuoYi-Vue](https://gitee.com/y_project/RuoYi-Vue)
|
* 如需不分离应用,请移步 [RuoYi](https://gitee.com/y_project/RuoYi),如需分离应用,请移步 [RuoYi-Vue](https://gitee.com/y_project/RuoYi-Vue)
|
||||||
* 感谢[ruoyi-cloud-design](https://gitee.com/zhangmrit/ruoyi-cloud),[pig](https://gitee.com/log4j/pig)。
|
* 阿里云折扣场:[点我进入](http://aly.ruoyi.vip),腾讯云秒杀场:[点我进入](http://txy.ruoyi.vip)
|
||||||
* 阿里云优惠券:[点我进入](https://www.aliyun.com/minisite/goods?userCode=brki8iof&share_source=copy_link),腾讯云优惠券:[点我领取](https://cloud.tencent.com/redirect.php?redirect=1025&cps_key=198c8df2ed259157187173bc7f4f32fd&from=console)
|
* 阿里云优惠券:[点我领取](https://www.aliyun.com/minisite/goods?userCode=brki8iof&share_source=copy_link),腾讯云优惠券:[点我领取](https://cloud.tencent.com/redirect.php?redirect=1025&cps_key=198c8df2ed259157187173bc7f4f32fd&from=console)
|
||||||
|
|
||||||
|
#### 友情链接 [若依/RuoYi-Cloud](https://gitee.com/zhangmrit/ruoyi-cloud) Ant Design版本。
|
||||||
|
|
||||||
## 系统模块
|
## 系统模块
|
||||||
|
|
||||||
@@ -29,6 +30,7 @@ com.ruoyi
|
|||||||
│ └── ruoyi-system // 系统模块 [9201]
|
│ └── ruoyi-system // 系统模块 [9201]
|
||||||
│ └── ruoyi-gen // 代码生成 [9202]
|
│ └── ruoyi-gen // 代码生成 [9202]
|
||||||
│ └── ruoyi-job // 定时任务 [9203]
|
│ └── ruoyi-job // 定时任务 [9203]
|
||||||
|
│ └── ruoyi-file // 文件服务 [9300]
|
||||||
├── ruoyi-visual // 图形化管理模块
|
├── ruoyi-visual // 图形化管理模块
|
||||||
│ └── ruoyi-visual-monitor // 监控中心 [9100]
|
│ └── ruoyi-visual-monitor // 监控中心 [9100]
|
||||||
├──pom.xml // 公共依赖
|
├──pom.xml // 公共依赖
|
||||||
@@ -36,7 +38,7 @@ com.ruoyi
|
|||||||
|
|
||||||
## 架构图
|
## 架构图
|
||||||
|
|
||||||
<img src="https://oscimg.oschina.net/oscnet/up-aaa2d885b0fba37e52b56f0948edde1c4fe.png"/>
|
<img src="https://oscimg.oschina.net/oscnet/up-8b9f92ed62f8aa17bd95999272f12a5927c.png"/>
|
||||||
|
|
||||||
## 内置功能
|
## 内置功能
|
||||||
|
|
||||||
@@ -79,7 +81,7 @@ com.ruoyi
|
|||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td><img src="https://oscimg.oschina.net/oscnet/up-39bf2584ec3a529b0d5a3b70d15c9b37646.png"/></td>
|
<td><img src="https://oscimg.oschina.net/oscnet/up-39bf2584ec3a529b0d5a3b70d15c9b37646.png"/></td>
|
||||||
<td><img src="https://oscimg.oschina.net/oscnet/up-936ec82d1f4872e1bc980927654b6007307.png"/></td>
|
<td><img src="https://oscimg.oschina.net/oscnet/up-4148b24f58660a9dc347761e4cf6162f28f.png"/></td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td><img src="https://oscimg.oschina.net/oscnet/up-b2d62ceb95d2dd9b3fbe157bb70d26001e9.png"/></td>
|
<td><img src="https://oscimg.oschina.net/oscnet/up-b2d62ceb95d2dd9b3fbe157bb70d26001e9.png"/></td>
|
||||||
@@ -102,7 +104,7 @@ com.ruoyi
|
|||||||
<td><img src="https://oscimg.oschina.net/oscnet/up-92ffb7f3835855cff100fa0f754a6be0d99.png"/></td>
|
<td><img src="https://oscimg.oschina.net/oscnet/up-92ffb7f3835855cff100fa0f754a6be0d99.png"/></td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<td><img src="https://oscimg.oschina.net/oscnet/up-d69a19493e5aff7ecdd5d02410862bcea40.png"/></td>
|
<td><img src="https://oscimg.oschina.net/oscnet/up-ff9e3066561574aca73005c5730c6a41f15.png"/></td>
|
||||||
<td><img src="https://oscimg.oschina.net/oscnet/up-6d73c2140ce694e3de4c05035fdc1868d4c.png"/></td>
|
<td><img src="https://oscimg.oschina.net/oscnet/up-6d73c2140ce694e3de4c05035fdc1868d4c.png"/></td>
|
||||||
</tr>
|
</tr>
|
||||||
</table>
|
</table>
|
||||||
@@ -110,4 +112,4 @@ com.ruoyi
|
|||||||
|
|
||||||
## 若依微服务交流群
|
## 若依微服务交流群
|
||||||
|
|
||||||
QQ群: [](https://jq.qq.com/?_wv=1027&k=yqInfq0S) [](https://jq.qq.com/?_wv=1027&k=Oy1mb3p8) 点击按钮入群。
|
QQ群: [](https://jq.qq.com/?_wv=1027&k=yqInfq0S) [](https://jq.qq.com/?_wv=1027&k=Oy1mb3p8) [](https://jq.qq.com/?_wv=1027&k=rvxkJtXK) 点击按钮入群。
|
||||||
27
pom.xml
27
pom.xml
@@ -6,30 +6,30 @@
|
|||||||
|
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi</artifactId>
|
<artifactId>ruoyi</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
|
|
||||||
<name>ruoyi</name>
|
<name>ruoyi</name>
|
||||||
<url>http://www.ruoyi.vip</url>
|
<url>http://www.ruoyi.vip</url>
|
||||||
<description>若依微服务系统</description>
|
<description>若依微服务系统</description>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<ruoyi.version>2.1.0</ruoyi.version>
|
<ruoyi.version>2.3.0</ruoyi.version>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||||
<java.version>1.8</java.version>
|
<java.version>1.8</java.version>
|
||||||
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
|
<spring-boot.version>2.3.4.RELEASE</spring-boot.version>
|
||||||
<spring-cloud.version>Hoxton.SR4</spring-cloud.version>
|
<spring-cloud.version>Hoxton.SR8</spring-cloud.version>
|
||||||
<spring-boot-admin.version>2.2.3</spring-boot-admin.version>
|
<spring-cloud-alibaba.version>2.2.3.RELEASE</spring-cloud-alibaba.version>
|
||||||
<spring-boot.mybatis>2.1.2</spring-boot.mybatis>
|
<spring-boot-admin.version>2.3.0</spring-boot-admin.version>
|
||||||
<nacos.version>1.3.0</nacos.version>
|
<spring-boot.mybatis>2.1.3</spring-boot.mybatis>
|
||||||
<swagger.fox.version>2.9.2</swagger.fox.version>
|
<swagger.fox.version>2.9.2</swagger.fox.version>
|
||||||
<swagger.core.version>1.5.24</swagger.core.version>
|
<swagger.core.version>1.5.24</swagger.core.version>
|
||||||
<kaptcha.version>2.3.2</kaptcha.version>
|
<kaptcha.version>2.3.2</kaptcha.version>
|
||||||
<pagehelper.boot.version>1.2.12</pagehelper.boot.version>
|
<pagehelper.boot.version>1.3.0</pagehelper.boot.version>
|
||||||
<commons.io.version>2.5</commons.io.version>
|
<commons.io.version>2.5</commons.io.version>
|
||||||
<commons.fileupload.version>1.3.3</commons.fileupload.version>
|
<commons.fileupload.version>1.3.3</commons.fileupload.version>
|
||||||
<velocity.version>1.7</velocity.version>
|
<velocity.version>1.7</velocity.version>
|
||||||
<fastjson.version>1.2.70</fastjson.version>
|
<fastjson.version>1.2.74</fastjson.version>
|
||||||
<poi.version>3.17</poi.version>
|
<poi.version>3.17</poi.version>
|
||||||
<common-pool.version>2.6.2</common-pool.version>
|
<common-pool.version>2.6.2</common-pool.version>
|
||||||
</properties>
|
</properties>
|
||||||
@@ -51,18 +51,11 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.alibaba.cloud</groupId>
|
<groupId>com.alibaba.cloud</groupId>
|
||||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||||
<version>2.2.1.RELEASE</version>
|
<version>${spring-cloud-alibaba.version}</version>
|
||||||
<type>pom</type>
|
<type>pom</type>
|
||||||
<scope>import</scope>
|
<scope>import</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Alibaba Nacos 配置 -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.alibaba.nacos</groupId>
|
|
||||||
<artifactId>nacos-client</artifactId>
|
|
||||||
<version>${nacos.version}</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<!-- SpringBoot 依赖配置 -->
|
<!-- SpringBoot 依赖配置 -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi</artifactId>
|
<artifactId>ruoyi</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi-api</artifactId>
|
<artifactId>ruoyi-api</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.ruoyi.system.api;
|
||||||
|
|
||||||
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestPart;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import com.ruoyi.common.core.constant.ServiceNameConstants;
|
||||||
|
import com.ruoyi.common.core.domain.R;
|
||||||
|
import com.ruoyi.system.api.domain.SysFile;
|
||||||
|
import com.ruoyi.system.api.factory.RemoteFileFallbackFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件服务
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@FeignClient(contextId = "remoteFileService", value = ServiceNameConstants.FILE_SERVICE, fallbackFactory = RemoteFileFallbackFactory.class)
|
||||||
|
public interface RemoteFileService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 上传文件
|
||||||
|
*
|
||||||
|
* @param file 文件信息
|
||||||
|
* @return 结果
|
||||||
|
*/
|
||||||
|
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||||
|
public R<SysFile> upload(@RequestPart(value = "file") MultipartFile file);
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ import org.springframework.web.bind.annotation.PathVariable;
|
|||||||
import com.ruoyi.common.core.constant.ServiceNameConstants;
|
import com.ruoyi.common.core.constant.ServiceNameConstants;
|
||||||
import com.ruoyi.common.core.domain.R;
|
import com.ruoyi.common.core.domain.R;
|
||||||
import com.ruoyi.system.api.factory.RemoteUserFallbackFactory;
|
import com.ruoyi.system.api.factory.RemoteUserFallbackFactory;
|
||||||
import com.ruoyi.system.api.model.UserInfo;
|
import com.ruoyi.system.api.model.LoginUser;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 用户服务
|
* 用户服务
|
||||||
@@ -23,5 +23,5 @@ public interface RemoteUserService
|
|||||||
* @return 结果
|
* @return 结果
|
||||||
*/
|
*/
|
||||||
@GetMapping(value = "/user/info/{username}")
|
@GetMapping(value = "/user/info/{username}")
|
||||||
public R<UserInfo> getUserInfo(@PathVariable("username") String username);
|
public R<LoginUser> getUserInfo(@PathVariable("username") String username);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package com.ruoyi.system.api.domain;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.builder.ToStringBuilder;
|
||||||
|
import org.apache.commons.lang3.builder.ToStringStyle;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件信息
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public class SysFile
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 文件名称
|
||||||
|
*/
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件地址
|
||||||
|
*/
|
||||||
|
private String url;
|
||||||
|
|
||||||
|
public String getName()
|
||||||
|
{
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name)
|
||||||
|
{
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUrl()
|
||||||
|
{
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUrl(String url)
|
||||||
|
{
|
||||||
|
this.url = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
|
||||||
|
.append("name", getName())
|
||||||
|
.append("url", getUrl())
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -37,6 +37,12 @@ public class SysRole extends BaseEntity
|
|||||||
@Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限")
|
@Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限")
|
||||||
private String dataScope;
|
private String dataScope;
|
||||||
|
|
||||||
|
/** 菜单树选择项是否关联显示( 0:父子不互相关联显示 1:父子互相关联显示) */
|
||||||
|
private boolean menuCheckStrictly;
|
||||||
|
|
||||||
|
/** 部门树选择项是否关联显示(0:父子不互相关联显示 1:父子互相关联显示 ) */
|
||||||
|
private boolean deptCheckStrictly;
|
||||||
|
|
||||||
/** 角色状态(0正常 1停用) */
|
/** 角色状态(0正常 1停用) */
|
||||||
@Excel(name = "角色状态", readConverterExp = "0=正常,1=停用")
|
@Excel(name = "角色状态", readConverterExp = "0=正常,1=停用")
|
||||||
private String status;
|
private String status;
|
||||||
@@ -128,6 +134,26 @@ public class SysRole extends BaseEntity
|
|||||||
this.dataScope = dataScope;
|
this.dataScope = dataScope;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean isMenuCheckStrictly()
|
||||||
|
{
|
||||||
|
return menuCheckStrictly;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMenuCheckStrictly(boolean menuCheckStrictly)
|
||||||
|
{
|
||||||
|
this.menuCheckStrictly = menuCheckStrictly;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isDeptCheckStrictly()
|
||||||
|
{
|
||||||
|
return deptCheckStrictly;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDeptCheckStrictly(boolean deptCheckStrictly)
|
||||||
|
{
|
||||||
|
this.deptCheckStrictly = deptCheckStrictly;
|
||||||
|
}
|
||||||
|
|
||||||
public String getStatus()
|
public String getStatus()
|
||||||
{
|
{
|
||||||
return status;
|
return status;
|
||||||
@@ -185,6 +211,8 @@ public class SysRole extends BaseEntity
|
|||||||
.append("roleKey", getRoleKey())
|
.append("roleKey", getRoleKey())
|
||||||
.append("roleSort", getRoleSort())
|
.append("roleSort", getRoleSort())
|
||||||
.append("dataScope", getDataScope())
|
.append("dataScope", getDataScope())
|
||||||
|
.append("menuCheckStrictly", isMenuCheckStrictly())
|
||||||
|
.append("deptCheckStrictly", isDeptCheckStrictly())
|
||||||
.append("status", getStatus())
|
.append("status", getStatus())
|
||||||
.append("delFlag", getDelFlag())
|
.append("delFlag", getDelFlag())
|
||||||
.append("createBy", getCreateBy())
|
.append("createBy", getCreateBy())
|
||||||
|
|||||||
@@ -67,12 +67,12 @@ public class SysUser extends BaseEntity
|
|||||||
/** 删除标志(0代表存在 2代表删除) */
|
/** 删除标志(0代表存在 2代表删除) */
|
||||||
private String delFlag;
|
private String delFlag;
|
||||||
|
|
||||||
/** 最后登陆IP */
|
/** 最后登录IP */
|
||||||
@Excel(name = "最后登陆IP", type = Type.EXPORT)
|
@Excel(name = "最后登录IP", type = Type.EXPORT)
|
||||||
private String loginIp;
|
private String loginIp;
|
||||||
|
|
||||||
/** 最后登陆时间 */
|
/** 最后登录时间 */
|
||||||
@Excel(name = "最后登陆时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Type.EXPORT)
|
@Excel(name = "最后登录时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Type.EXPORT)
|
||||||
private Date loginDate;
|
private Date loginDate;
|
||||||
|
|
||||||
/** 部门对象 */
|
/** 部门对象 */
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.ruoyi.system.api.factory;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import com.ruoyi.common.core.domain.R;
|
||||||
|
import com.ruoyi.system.api.RemoteFileService;
|
||||||
|
import com.ruoyi.system.api.domain.SysFile;
|
||||||
|
import feign.hystrix.FallbackFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件服务降级处理
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class RemoteFileFallbackFactory implements FallbackFactory<RemoteFileService>
|
||||||
|
{
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(RemoteFileFallbackFactory.class);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public RemoteFileService create(Throwable throwable)
|
||||||
|
{
|
||||||
|
log.error("文件服务调用失败:{}", throwable.getMessage());
|
||||||
|
return new RemoteFileService()
|
||||||
|
{
|
||||||
|
@Override
|
||||||
|
public R<SysFile> upload(MultipartFile file)
|
||||||
|
{
|
||||||
|
return R.fail("上传文件失败:" + throwable.getMessage());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
|
|||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import com.ruoyi.common.core.domain.R;
|
import com.ruoyi.common.core.domain.R;
|
||||||
import com.ruoyi.system.api.RemoteUserService;
|
import com.ruoyi.system.api.RemoteUserService;
|
||||||
import com.ruoyi.system.api.model.UserInfo;
|
import com.ruoyi.system.api.model.LoginUser;
|
||||||
import feign.hystrix.FallbackFactory;
|
import feign.hystrix.FallbackFactory;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -25,9 +25,9 @@ public class RemoteUserFallbackFactory implements FallbackFactory<RemoteUserServ
|
|||||||
return new RemoteUserService()
|
return new RemoteUserService()
|
||||||
{
|
{
|
||||||
@Override
|
@Override
|
||||||
public R<UserInfo> getUserInfo(String username)
|
public R<LoginUser> getUserInfo(String username)
|
||||||
{
|
{
|
||||||
return null;
|
return R.fail("获取用户失败:" + throwable.getMessage());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
package com.ruoyi.system.api.model;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.Set;
|
||||||
|
import com.ruoyi.system.api.domain.SysUser;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户信息
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public class LoginUser implements Serializable
|
||||||
|
{
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户唯一标识
|
||||||
|
*/
|
||||||
|
private String token;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户名id
|
||||||
|
*/
|
||||||
|
private Long userid;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户名
|
||||||
|
*/
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录时间
|
||||||
|
*/
|
||||||
|
private Long loginTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 过期时间
|
||||||
|
*/
|
||||||
|
private Long expireTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录IP地址
|
||||||
|
*/
|
||||||
|
private String ipaddr;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 权限列表
|
||||||
|
*/
|
||||||
|
private Set<String> permissions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 角色列表
|
||||||
|
*/
|
||||||
|
private Set<String> roles;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户信息
|
||||||
|
*/
|
||||||
|
private SysUser sysUser;
|
||||||
|
|
||||||
|
public String getToken()
|
||||||
|
{
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setToken(String token)
|
||||||
|
{
|
||||||
|
this.token = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getUserid()
|
||||||
|
{
|
||||||
|
return userid;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUserid(Long userid)
|
||||||
|
{
|
||||||
|
this.userid = userid;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUsername()
|
||||||
|
{
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUsername(String username)
|
||||||
|
{
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getLoginTime()
|
||||||
|
{
|
||||||
|
return loginTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLoginTime(Long loginTime)
|
||||||
|
{
|
||||||
|
this.loginTime = loginTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getExpireTime()
|
||||||
|
{
|
||||||
|
return expireTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setExpireTime(Long expireTime)
|
||||||
|
{
|
||||||
|
this.expireTime = expireTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getIpaddr()
|
||||||
|
{
|
||||||
|
return ipaddr;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIpaddr(String ipaddr)
|
||||||
|
{
|
||||||
|
this.ipaddr = ipaddr;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<String> getPermissions()
|
||||||
|
{
|
||||||
|
return permissions;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPermissions(Set<String> permissions)
|
||||||
|
{
|
||||||
|
this.permissions = permissions;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<String> getRoles()
|
||||||
|
{
|
||||||
|
return roles;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRoles(Set<String> roles)
|
||||||
|
{
|
||||||
|
this.roles = roles;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SysUser getSysUser()
|
||||||
|
{
|
||||||
|
return sysUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSysUser(SysUser sysUser)
|
||||||
|
{
|
||||||
|
this.sysUser = sysUser;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
package com.ruoyi.system.api.model;
|
|
||||||
|
|
||||||
import java.io.Serializable;
|
|
||||||
import java.util.Set;
|
|
||||||
import com.ruoyi.system.api.domain.SysUser;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 用户信息
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
public class UserInfo implements Serializable
|
|
||||||
{
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 用户基本信息
|
|
||||||
*/
|
|
||||||
private SysUser sysUser;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 权限标识集合
|
|
||||||
*/
|
|
||||||
private Set<String> permissions;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 角色集合
|
|
||||||
*/
|
|
||||||
private Set<String> roles;
|
|
||||||
|
|
||||||
public SysUser getSysUser()
|
|
||||||
{
|
|
||||||
return sysUser;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSysUser(SysUser sysUser)
|
|
||||||
{
|
|
||||||
this.sysUser = sysUser;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Set<String> getPermissions()
|
|
||||||
{
|
|
||||||
return permissions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPermissions(Set<String> permissions)
|
|
||||||
{
|
|
||||||
this.permissions = permissions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Set<String> getRoles()
|
|
||||||
{
|
|
||||||
return roles;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setRoles(Set<String> roles)
|
|
||||||
{
|
|
||||||
this.roles = roles;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi</artifactId>
|
<artifactId>ruoyi</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
@@ -28,10 +28,10 @@
|
|||||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- SpringCloud Netflix Hystrix -->
|
<!-- SpringCloud Ailibaba Sentinel -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>com.alibaba.cloud</groupId>
|
||||||
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
|
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- SpringBoot Web -->
|
<!-- SpringBoot Web -->
|
||||||
@@ -40,6 +40,12 @@
|
|||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- SpringBoot Actuator -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- Mysql Connector -->
|
<!-- Mysql Connector -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>mysql</groupId>
|
<groupId>mysql</groupId>
|
||||||
@@ -52,12 +58,6 @@
|
|||||||
<artifactId>ruoyi-common-security</artifactId>
|
<artifactId>ruoyi-common-security</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- RuoYi Common Redis-->
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.ruoyi</groupId>
|
|
||||||
<artifactId>ruoyi-common-redis</artifactId>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
@@ -1,131 +0,0 @@
|
|||||||
package com.ruoyi.auth.config;
|
|
||||||
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import javax.sql.DataSource;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
|
||||||
import org.springframework.http.HttpMethod;
|
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
|
||||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
|
||||||
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
|
|
||||||
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
|
|
||||||
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
|
|
||||||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
|
|
||||||
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
|
|
||||||
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
|
|
||||||
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
|
|
||||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
|
||||||
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
|
|
||||||
import com.ruoyi.auth.exception.CustomWebResponseExceptionTranslator;
|
|
||||||
import com.ruoyi.common.core.constant.CacheConstants;
|
|
||||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
|
||||||
import com.ruoyi.common.security.domain.LoginUser;
|
|
||||||
import com.ruoyi.common.security.service.RedisClientDetailsService;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* OAuth2 认证服务配置
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
@Configuration
|
|
||||||
@EnableAuthorizationServer
|
|
||||||
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter
|
|
||||||
{
|
|
||||||
@Autowired
|
|
||||||
private AuthenticationManager authenticationManager;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private DataSource dataSource;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private RedisConnectionFactory redisConnectionFactory;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private UserDetailsService userDetailsService;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private TokenEnhancer tokenEnhancer;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 定义授权和令牌端点以及令牌服务
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
|
|
||||||
{
|
|
||||||
endpoints
|
|
||||||
// 请求方式
|
|
||||||
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
|
|
||||||
// 指定token存储位置
|
|
||||||
.tokenStore(tokenStore())
|
|
||||||
// 自定义生成令牌
|
|
||||||
.tokenEnhancer(tokenEnhancer)
|
|
||||||
// 用户账号密码认证
|
|
||||||
.userDetailsService(userDetailsService)
|
|
||||||
// 指定认证管理器
|
|
||||||
.authenticationManager(authenticationManager)
|
|
||||||
// 是否重复使用 refresh_token
|
|
||||||
.reuseRefreshTokens(false)
|
|
||||||
// 自定义异常处理
|
|
||||||
.exceptionTranslator(new CustomWebResponseExceptionTranslator());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 配置令牌端点(Token Endpoint)的安全约束
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void configure(AuthorizationServerSecurityConfigurer oauthServer)
|
|
||||||
{
|
|
||||||
oauthServer.allowFormAuthenticationForClients().checkTokenAccess("permitAll()");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 声明 ClientDetails实现
|
|
||||||
*/
|
|
||||||
public RedisClientDetailsService clientDetailsService()
|
|
||||||
{
|
|
||||||
RedisClientDetailsService clientDetailsService = new RedisClientDetailsService(dataSource);
|
|
||||||
return clientDetailsService;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 配置客户端详情
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void configure(ClientDetailsServiceConfigurer clients) throws Exception
|
|
||||||
{
|
|
||||||
clients.withClientDetails(clientDetailsService());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 基于 Redis 实现,令牌保存到缓存
|
|
||||||
*/
|
|
||||||
@Bean
|
|
||||||
public TokenStore tokenStore()
|
|
||||||
{
|
|
||||||
RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
|
|
||||||
tokenStore.setPrefix(CacheConstants.OAUTH_ACCESS);
|
|
||||||
return tokenStore;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自定义生成令牌
|
|
||||||
*/
|
|
||||||
@Bean
|
|
||||||
public TokenEnhancer tokenEnhancer()
|
|
||||||
{
|
|
||||||
return (accessToken, authentication) -> {
|
|
||||||
if (authentication.getUserAuthentication() != null)
|
|
||||||
{
|
|
||||||
Map<String, Object> additionalInformation = new LinkedHashMap<String, Object>();
|
|
||||||
LoginUser user = (LoginUser) authentication.getUserAuthentication().getPrincipal();
|
|
||||||
additionalInformation.put(SecurityConstants.DETAILS_USER_ID, user.getUserId());
|
|
||||||
additionalInformation.put(SecurityConstants.DETAILS_USERNAME, user.getUsername());
|
|
||||||
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
|
|
||||||
}
|
|
||||||
return accessToken;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
package com.ruoyi.auth.config;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.core.annotation.Order;
|
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
|
||||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
|
||||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
|
||||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
|
||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Security 安全认证相关配置
|
|
||||||
* Oauth2依赖于Security 默认情况下WebSecurityConfig执行比ResourceServerConfig优先
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
@Order(99)
|
|
||||||
@Configuration
|
|
||||||
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
|
|
||||||
{
|
|
||||||
@Autowired
|
|
||||||
private UserDetailsService userDetailsService;
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
public PasswordEncoder passwordEncoder()
|
|
||||||
{
|
|
||||||
return new BCryptPasswordEncoder();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
@Override
|
|
||||||
public AuthenticationManager authenticationManagerBean() throws Exception
|
|
||||||
{
|
|
||||||
return super.authenticationManagerBean();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception
|
|
||||||
{
|
|
||||||
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void configure(HttpSecurity http) throws Exception
|
|
||||||
{
|
|
||||||
http
|
|
||||||
.authorizeRequests()
|
|
||||||
.antMatchers(
|
|
||||||
"/actuator/**",
|
|
||||||
"/oauth/*",
|
|
||||||
"/token/**").permitAll()
|
|
||||||
.anyRequest().authenticated()
|
|
||||||
.and().csrf().disable();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +1,17 @@
|
|||||||
package com.ruoyi.auth.controller;
|
package com.ruoyi.auth.controller;
|
||||||
|
|
||||||
import java.util.Map;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
|
||||||
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
|
|
||||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestHeader;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
import com.ruoyi.common.core.constant.Constants;
|
import com.ruoyi.auth.form.LoginBody;
|
||||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
import com.ruoyi.auth.service.SysLoginService;
|
||||||
import com.ruoyi.common.core.domain.R;
|
import com.ruoyi.common.core.domain.R;
|
||||||
import com.ruoyi.common.core.utils.StringUtils;
|
import com.ruoyi.common.core.utils.StringUtils;
|
||||||
import com.ruoyi.system.api.RemoteLogService;
|
import com.ruoyi.common.security.service.TokenService;
|
||||||
|
import com.ruoyi.system.api.model.LoginUser;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* token 控制
|
* token 控制
|
||||||
@@ -22,42 +19,47 @@ import com.ruoyi.system.api.RemoteLogService;
|
|||||||
* @author ruoyi
|
* @author ruoyi
|
||||||
*/
|
*/
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/token")
|
|
||||||
public class TokenController
|
public class TokenController
|
||||||
{
|
{
|
||||||
@Autowired
|
@Autowired
|
||||||
private TokenStore tokenStore;
|
private TokenService tokenService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private RemoteLogService remoteLogService;
|
private SysLoginService sysLoginService;
|
||||||
|
|
||||||
@DeleteMapping("/logout")
|
@PostMapping("login")
|
||||||
public R<?> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader)
|
public R<?> login(@RequestBody LoginBody form)
|
||||||
{
|
{
|
||||||
if (StringUtils.isEmpty(authHeader))
|
// 用户登录
|
||||||
{
|
LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
|
||||||
return R.ok();
|
// 获取登录token
|
||||||
}
|
return R.ok(tokenService.createToken(userInfo));
|
||||||
|
}
|
||||||
|
|
||||||
String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StringUtils.EMPTY).trim();
|
@DeleteMapping("logout")
|
||||||
OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
|
public R<?> logout(HttpServletRequest request)
|
||||||
if (accessToken == null || StringUtils.isEmpty(accessToken.getValue()))
|
{
|
||||||
|
LoginUser loginUser = tokenService.getLoginUser(request);
|
||||||
|
if (StringUtils.isNotNull(loginUser))
|
||||||
{
|
{
|
||||||
return R.ok();
|
String username = loginUser.getUsername();
|
||||||
}
|
// 删除用户缓存记录
|
||||||
|
tokenService.delLoginUser(loginUser.getToken());
|
||||||
// 清空 access token
|
|
||||||
tokenStore.removeAccessToken(accessToken);
|
|
||||||
|
|
||||||
// 清空 refresh token
|
|
||||||
OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
|
|
||||||
tokenStore.removeRefreshToken(refreshToken);
|
|
||||||
Map<String, ?> map = accessToken.getAdditionalInformation();
|
|
||||||
if (map.containsKey(SecurityConstants.DETAILS_USERNAME))
|
|
||||||
{
|
|
||||||
String username = (String) map.get(SecurityConstants.DETAILS_USERNAME);
|
|
||||||
// 记录用户退出日志
|
// 记录用户退出日志
|
||||||
remoteLogService.saveLogininfor(username, Constants.LOGOUT, "退出成功");
|
sysLoginService.logout(username);
|
||||||
|
}
|
||||||
|
return R.ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("refresh")
|
||||||
|
public R<?> refresh(HttpServletRequest request)
|
||||||
|
{
|
||||||
|
LoginUser loginUser = tokenService.getLoginUser(request);
|
||||||
|
if (StringUtils.isNotNull(loginUser))
|
||||||
|
{
|
||||||
|
// 刷新令牌有效期
|
||||||
|
tokenService.refreshToken(loginUser);
|
||||||
|
return R.ok();
|
||||||
}
|
}
|
||||||
return R.ok();
|
return R.ok();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
package com.ruoyi.auth.controller;
|
|
||||||
|
|
||||||
import java.security.Principal;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 身份信息获取
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/oauth")
|
|
||||||
public class UserController
|
|
||||||
{
|
|
||||||
@RequestMapping("/user")
|
|
||||||
public Principal user(Principal user)
|
|
||||||
{
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
package com.ruoyi.auth.exception;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
|
||||||
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* oauth2自定义异常
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
**/
|
|
||||||
@JsonSerialize(using = CustomOauthExceptionSerializer.class)
|
|
||||||
public class CustomOauthException extends OAuth2Exception
|
|
||||||
{
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
public CustomOauthException(String msg)
|
|
||||||
{
|
|
||||||
super(msg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
package com.ruoyi.auth.exception;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import com.fasterxml.jackson.core.JsonGenerator;
|
|
||||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
|
||||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
|
||||||
import com.ruoyi.common.core.constant.HttpStatus;
|
|
||||||
import com.ruoyi.common.core.utils.StringUtils;
|
|
||||||
import com.ruoyi.common.core.web.domain.AjaxResult;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自定义异常返回
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
**/
|
|
||||||
public class CustomOauthExceptionSerializer extends StdSerializer<CustomOauthException>
|
|
||||||
{
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(CustomOauthExceptionSerializer.class);
|
|
||||||
|
|
||||||
public static final String BAD_CREDENTIALS = "Bad credentials";
|
|
||||||
|
|
||||||
public CustomOauthExceptionSerializer()
|
|
||||||
{
|
|
||||||
super(CustomOauthException.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void serialize(CustomOauthException e, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
|
|
||||||
throws IOException
|
|
||||||
{
|
|
||||||
jsonGenerator.writeStartObject();
|
|
||||||
jsonGenerator.writeNumberField(AjaxResult.CODE_TAG, HttpStatus.ERROR);
|
|
||||||
if (StringUtils.equals(e.getMessage(), BAD_CREDENTIALS))
|
|
||||||
{
|
|
||||||
jsonGenerator.writeStringField(AjaxResult.MSG_TAG, "用户名或密码错误");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
log.warn("oauth2 认证异常 {} ", e);
|
|
||||||
jsonGenerator.writeStringField(AjaxResult.MSG_TAG, e.getMessage());
|
|
||||||
}
|
|
||||||
jsonGenerator.writeEndObject();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
package com.ruoyi.auth.exception;
|
|
||||||
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
|
|
||||||
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* OAuth2 自定义异常处理
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception>
|
|
||||||
{
|
|
||||||
@Override
|
|
||||||
public ResponseEntity<OAuth2Exception> translate(Exception e)
|
|
||||||
{
|
|
||||||
return ResponseEntity.status(HttpStatus.OK).body(new CustomOauthException(e.getMessage()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
69
ruoyi-auth/src/main/java/com/ruoyi/auth/form/LoginBody.java
Normal file
69
ruoyi-auth/src/main/java/com/ruoyi/auth/form/LoginBody.java
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
package com.ruoyi.auth.form;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录对象
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public class LoginBody
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 用户名
|
||||||
|
*/
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户密码
|
||||||
|
*/
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证码
|
||||||
|
*/
|
||||||
|
private String code;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 唯一标识
|
||||||
|
*/
|
||||||
|
private String uuid = "";
|
||||||
|
|
||||||
|
public String getUsername()
|
||||||
|
{
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUsername(String username)
|
||||||
|
{
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword()
|
||||||
|
{
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password)
|
||||||
|
{
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCode()
|
||||||
|
{
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCode(String code)
|
||||||
|
{
|
||||||
|
this.code = code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUuid()
|
||||||
|
{
|
||||||
|
return uuid;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUuid(String uuid)
|
||||||
|
{
|
||||||
|
this.uuid = uuid;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package com.ruoyi.auth.handler;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.context.ApplicationListener;
|
|
||||||
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
import com.ruoyi.common.core.constant.Constants;
|
|
||||||
import com.ruoyi.common.core.utils.StringUtils;
|
|
||||||
import com.ruoyi.common.security.domain.LoginUser;
|
|
||||||
import com.ruoyi.system.api.RemoteLogService;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 认证成功处理
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
@Component
|
|
||||||
public class AuthenticationSuccessEventHandler implements ApplicationListener<AuthenticationSuccessEvent>
|
|
||||||
{
|
|
||||||
@Autowired
|
|
||||||
private RemoteLogService remoteLogService;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onApplicationEvent(AuthenticationSuccessEvent event)
|
|
||||||
{
|
|
||||||
Authentication authentication = (Authentication) event.getSource();
|
|
||||||
if (StringUtils.isNotEmpty(authentication.getAuthorities())
|
|
||||||
&& authentication.getPrincipal() instanceof LoginUser)
|
|
||||||
{
|
|
||||||
LoginUser user = (LoginUser) authentication.getPrincipal();
|
|
||||||
|
|
||||||
String username = user.getUsername();
|
|
||||||
|
|
||||||
// 记录用户登录日志
|
|
||||||
remoteLogService.saveLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package com.ruoyi.auth.service;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import com.ruoyi.common.core.constant.Constants;
|
||||||
|
import com.ruoyi.common.core.constant.UserConstants;
|
||||||
|
import com.ruoyi.common.core.domain.R;
|
||||||
|
import com.ruoyi.common.core.enums.UserStatus;
|
||||||
|
import com.ruoyi.common.core.exception.BaseException;
|
||||||
|
import com.ruoyi.common.core.utils.StringUtils;
|
||||||
|
import com.ruoyi.common.security.utils.SecurityUtils;
|
||||||
|
import com.ruoyi.system.api.RemoteLogService;
|
||||||
|
import com.ruoyi.system.api.RemoteUserService;
|
||||||
|
import com.ruoyi.system.api.domain.SysUser;
|
||||||
|
import com.ruoyi.system.api.model.LoginUser;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录校验方法
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class SysLoginService
|
||||||
|
{
|
||||||
|
@Autowired
|
||||||
|
private RemoteLogService remoteLogService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private RemoteUserService remoteUserService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录
|
||||||
|
*/
|
||||||
|
public LoginUser login(String username, String password)
|
||||||
|
{
|
||||||
|
// 用户名或密码为空 错误
|
||||||
|
if (StringUtils.isAnyBlank(username, password))
|
||||||
|
{
|
||||||
|
remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
|
||||||
|
throw new BaseException("用户/密码必须填写");
|
||||||
|
}
|
||||||
|
// 密码如果不在指定范围内 错误
|
||||||
|
if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
|
||||||
|
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH)
|
||||||
|
{
|
||||||
|
remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
|
||||||
|
throw new BaseException("用户密码不在指定范围");
|
||||||
|
}
|
||||||
|
// 用户名不在指定范围内 错误
|
||||||
|
if (username.length() < UserConstants.USERNAME_MIN_LENGTH
|
||||||
|
|| username.length() > UserConstants.USERNAME_MAX_LENGTH)
|
||||||
|
{
|
||||||
|
remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
|
||||||
|
throw new BaseException("用户名不在指定范围");
|
||||||
|
}
|
||||||
|
// 查询用户信息
|
||||||
|
R<LoginUser> userResult = remoteUserService.getUserInfo(username);
|
||||||
|
|
||||||
|
if (R.FAIL == userResult.getCode())
|
||||||
|
{
|
||||||
|
throw new BaseException(userResult.getMsg());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
|
||||||
|
{
|
||||||
|
remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
|
||||||
|
throw new BaseException("登录用户:" + username + " 不存在");
|
||||||
|
}
|
||||||
|
LoginUser userInfo = userResult.getData();
|
||||||
|
SysUser user = userResult.getData().getSysUser();
|
||||||
|
if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
|
||||||
|
{
|
||||||
|
remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "对不起,您的账号已被删除");
|
||||||
|
|
||||||
|
throw new BaseException("对不起,您的账号:" + username + " 已被删除");
|
||||||
|
}
|
||||||
|
if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
|
||||||
|
{
|
||||||
|
remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户已停用,请联系管理员");
|
||||||
|
throw new BaseException("对不起,您的账号:" + username + " 已停用");
|
||||||
|
}
|
||||||
|
if (!SecurityUtils.matchesPassword(password, user.getPassword()))
|
||||||
|
{
|
||||||
|
remoteLogService.saveLogininfor(username, Constants.LOGIN_FAIL, "用户密码错误");
|
||||||
|
throw new BaseException("用户不存在/密码错误");
|
||||||
|
}
|
||||||
|
remoteLogService.saveLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
|
||||||
|
return userInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void logout(String loginName)
|
||||||
|
{
|
||||||
|
remoteLogService.saveLogininfor(loginName, Constants.LOGOUT, "退出成功");
|
||||||
|
}
|
||||||
|
}
|
||||||
74
ruoyi-auth/src/main/resources/logback.xml
Normal file
74
ruoyi-auth/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration scan="true" scanPeriod="60 seconds" debug="false">
|
||||||
|
<!-- 日志存放路径 -->
|
||||||
|
<property name="log.path" value="logs/ruoyi-auth" />
|
||||||
|
<!-- 日志输出格式 -->
|
||||||
|
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
|
||||||
|
|
||||||
|
<!-- 控制台输出 -->
|
||||||
|
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>${log.pattern}</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<!-- 系统日志输出 -->
|
||||||
|
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||||
|
<file>${log.path}/info.log</file>
|
||||||
|
<!-- 循环政策:基于时间创建日志文件 -->
|
||||||
|
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||||
|
<!-- 日志文件名格式 -->
|
||||||
|
<fileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||||
|
<!-- 日志最大的历史 60天 -->
|
||||||
|
<maxHistory>60</maxHistory>
|
||||||
|
</rollingPolicy>
|
||||||
|
<encoder>
|
||||||
|
<pattern>${log.pattern}</pattern>
|
||||||
|
</encoder>
|
||||||
|
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||||
|
<!-- 过滤的级别 -->
|
||||||
|
<level>INFO</level>
|
||||||
|
<!-- 匹配时的操作:接收(记录) -->
|
||||||
|
<onMatch>ACCEPT</onMatch>
|
||||||
|
<!-- 不匹配时的操作:拒绝(不记录) -->
|
||||||
|
<onMismatch>DENY</onMismatch>
|
||||||
|
</filter>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||||
|
<file>${log.path}/error.log</file>
|
||||||
|
<!-- 循环政策:基于时间创建日志文件 -->
|
||||||
|
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||||
|
<!-- 日志文件名格式 -->
|
||||||
|
<fileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||||
|
<!-- 日志最大的历史 60天 -->
|
||||||
|
<maxHistory>60</maxHistory>
|
||||||
|
</rollingPolicy>
|
||||||
|
<encoder>
|
||||||
|
<pattern>${log.pattern}</pattern>
|
||||||
|
</encoder>
|
||||||
|
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||||
|
<!-- 过滤的级别 -->
|
||||||
|
<level>ERROR</level>
|
||||||
|
<!-- 匹配时的操作:接收(记录) -->
|
||||||
|
<onMatch>ACCEPT</onMatch>
|
||||||
|
<!-- 不匹配时的操作:拒绝(不记录) -->
|
||||||
|
<onMismatch>DENY</onMismatch>
|
||||||
|
</filter>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<!-- 系统模块日志级别控制 -->
|
||||||
|
<logger name="com.ruoyi" level="info" />
|
||||||
|
<!-- Spring日志级别控制 -->
|
||||||
|
<logger name="org.springframework" level="warn" />
|
||||||
|
|
||||||
|
<root level="info">
|
||||||
|
<appender-ref ref="console" />
|
||||||
|
</root>
|
||||||
|
|
||||||
|
<!--系统操作日志-->
|
||||||
|
<root level="info">
|
||||||
|
<appender-ref ref="file_info" />
|
||||||
|
<appender-ref ref="file_error" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi</artifactId>
|
<artifactId>ruoyi</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi-common</artifactId>
|
<artifactId>ruoyi-common</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
@@ -16,13 +16,13 @@
|
|||||||
</description>
|
</description>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
||||||
<!-- SpringCloud Openfeign -->
|
<!-- SpringCloud Openfeign -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Spring Context Support -->
|
<!-- Spring Context Support -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
@@ -34,73 +34,73 @@
|
|||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-web</artifactId>
|
<artifactId>spring-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Apache Commons Pool2 -->
|
<!-- Apache Commons Pool2 -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-pool2</artifactId>
|
<artifactId>commons-pool2</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Pagehelper -->
|
<!-- Pagehelper -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.github.pagehelper</groupId>
|
<groupId>com.github.pagehelper</groupId>
|
||||||
<artifactId>pagehelper-spring-boot-starter</artifactId>
|
<artifactId>pagehelper-spring-boot-starter</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Java Validation -->
|
<!-- Hibernate Validator -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.validation</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>validation-api</artifactId>
|
<artifactId>spring-boot-starter-validation</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Jackson -->
|
<!-- Jackson -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Alibaba Fastjson -->
|
<!-- Alibaba Fastjson -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.alibaba</groupId>
|
<groupId>com.alibaba</groupId>
|
||||||
<artifactId>fastjson</artifactId>
|
<artifactId>fastjson</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Apache Lang3 -->
|
<!-- Apache Lang3 -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Commons Io -->
|
<!-- Commons Io -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-io</groupId>
|
<groupId>commons-io</groupId>
|
||||||
<artifactId>commons-io</artifactId>
|
<artifactId>commons-io</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Commons Fileupload -->
|
<!-- Commons Fileupload -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-fileupload</groupId>
|
<groupId>commons-fileupload</groupId>
|
||||||
<artifactId>commons-fileupload</artifactId>
|
<artifactId>commons-fileupload</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- excel工具 -->
|
<!-- excel工具 -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.poi</groupId>
|
<groupId>org.apache.poi</groupId>
|
||||||
<artifactId>poi-ooxml</artifactId>
|
<artifactId>poi-ooxml</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Java Servlet -->
|
<!-- Java Servlet -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.servlet</groupId>
|
<groupId>javax.servlet</groupId>
|
||||||
<artifactId>javax.servlet-api</artifactId>
|
<artifactId>javax.servlet-api</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Swagger -->
|
<!-- Swagger -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.swagger</groupId>
|
<groupId>io.swagger</groupId>
|
||||||
<artifactId>swagger-annotations</artifactId>
|
<artifactId>swagger-annotations</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import java.lang.annotation.ElementType;
|
|||||||
import java.lang.annotation.Retention;
|
import java.lang.annotation.Retention;
|
||||||
import java.lang.annotation.RetentionPolicy;
|
import java.lang.annotation.RetentionPolicy;
|
||||||
import java.lang.annotation.Target;
|
import java.lang.annotation.Target;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 自定义导出Excel数据注解
|
* 自定义导出Excel数据注解
|
||||||
@@ -39,6 +40,16 @@ public @interface Excel
|
|||||||
*/
|
*/
|
||||||
public String separator() default ",";
|
public String separator() default ",";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* BigDecimal 精度 默认:-1(默认不开启BigDecimal格式化)
|
||||||
|
*/
|
||||||
|
public int scale() default -1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* BigDecimal 舍入规则 默认:BigDecimal.ROUND_HALF_EVEN
|
||||||
|
*/
|
||||||
|
public int roundingMode() default BigDecimal.ROUND_HALF_EVEN;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 导出类型(0数字 1字符串)
|
* 导出类型(0数字 1字符串)
|
||||||
*/
|
*/
|
||||||
@@ -84,6 +95,11 @@ public @interface Excel
|
|||||||
*/
|
*/
|
||||||
public String targetAttr() default "";
|
public String targetAttr() default "";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否自动统计数据,在最后追加一行统计数据总和
|
||||||
|
*/
|
||||||
|
public boolean isStatistics() default false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 字段类型(0:导出导入;1:仅导出;2:仅导入)
|
* 字段类型(0:导出导入;1:仅导出;2:仅导入)
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -8,12 +8,27 @@ package com.ruoyi.common.core.constant;
|
|||||||
public class CacheConstants
|
public class CacheConstants
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* oauth 缓存前缀
|
* 令牌自定义标识
|
||||||
*/
|
*/
|
||||||
public static final String OAUTH_ACCESS = "oauth:access:";
|
public static final String HEADER = "Authorization";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* oauth 客户端信息
|
* 令牌前缀
|
||||||
*/
|
*/
|
||||||
public static final String CLIENT_DETAILS_KEY = "oauth:client:details";
|
public static final String TOKEN_PREFIX = "Bearer ";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 权限缓存前缀
|
||||||
|
*/
|
||||||
|
public final static String LOGIN_TOKEN_KEY = "login_tokens:";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户ID字段
|
||||||
|
*/
|
||||||
|
public static final String DETAILS_USER_ID = "user_id";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户名字段
|
||||||
|
*/
|
||||||
|
public static final String DETAILS_USERNAME = "username";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,7 +85,12 @@ public class Constants
|
|||||||
/**
|
/**
|
||||||
* 验证码有效期(分钟)
|
* 验证码有效期(分钟)
|
||||||
*/
|
*/
|
||||||
public static final Integer CAPTCHA_EXPIRATION = 2;
|
public static final long CAPTCHA_EXPIRATION = 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 令牌有效期(分钟)
|
||||||
|
*/
|
||||||
|
public final static long TOKEN_EXPIRE = 720;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 参数管理 cache key
|
* 参数管理 cache key
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ public class GenConstants
|
|||||||
public static final String PARENT_MENU_NAME = "parentMenuName";
|
public static final String PARENT_MENU_NAME = "parentMenuName";
|
||||||
|
|
||||||
/** 数据库字符串类型 */
|
/** 数据库字符串类型 */
|
||||||
public static final String[] COLUMNTYPE_STR = { "char", "varchar", "narchar", "varchar2", "tinytext", "text",
|
public static final String[] COLUMNTYPE_STR = { "char", "varchar", "nvarchar", "varchar2", "tinytext", "text",
|
||||||
"mediumtext", "longtext" };
|
"mediumtext", "longtext" };
|
||||||
|
|
||||||
/** 数据库时间类型 */
|
/** 数据库时间类型 */
|
||||||
@@ -74,6 +74,12 @@ public class GenConstants
|
|||||||
/** 日期控件 */
|
/** 日期控件 */
|
||||||
public static final String HTML_DATETIME = "datetime";
|
public static final String HTML_DATETIME = "datetime";
|
||||||
|
|
||||||
|
/** 上传控件 */
|
||||||
|
public static final String HTML_UPLOAD_IMAGE = "uploadImage";
|
||||||
|
|
||||||
|
/** 富文本控件 */
|
||||||
|
public static final String HTML_EDITOR = "editor";
|
||||||
|
|
||||||
/** 字符串类型 */
|
/** 字符串类型 */
|
||||||
public static final String TYPE_STRING = "String";
|
public static final String TYPE_STRING = "String";
|
||||||
|
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
package com.ruoyi.common.core.constant;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 权限相关通用常量
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
public class SecurityConstants
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* 令牌类型
|
|
||||||
*/
|
|
||||||
public static final String BEARER_TOKEN_TYPE = "Bearer";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 授权token url
|
|
||||||
*/
|
|
||||||
public static final String AUTH_TOKEN = "/oauth/token";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 注销token url
|
|
||||||
*/
|
|
||||||
public static final String TOKEN_LOGOUT = "/token/logout";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 用户ID字段
|
|
||||||
*/
|
|
||||||
public static final String DETAILS_USER_ID = "user_id";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 用户名字段
|
|
||||||
*/
|
|
||||||
public static final String DETAILS_USERNAME = "username";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* sys_oauth_client_details 表的字段,不包括client_id、client_secret
|
|
||||||
*/
|
|
||||||
public static final String CLIENT_FIELDS = "client_id, client_secret, resource_ids, scope, "
|
|
||||||
+ "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, "
|
|
||||||
+ "refresh_token_validity, additional_information, autoapprove";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* JdbcClientDetailsService 查询语句
|
|
||||||
*/
|
|
||||||
public static final String BASE_FIND_STATEMENT = "select " + CLIENT_FIELDS + " from sys_oauth_client_details";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按条件client_id 查询
|
|
||||||
*/
|
|
||||||
public static final String DEFAULT_SELECT_STATEMENT = BASE_FIND_STATEMENT + " where client_id = ?";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 默认的查询语句
|
|
||||||
*/
|
|
||||||
public static final String DEFAULT_FIND_STATEMENT = BASE_FIND_STATEMENT + " order by client_id";
|
|
||||||
}
|
|
||||||
@@ -16,4 +16,9 @@ public class ServiceNameConstants
|
|||||||
* 系统模块的serviceid
|
* 系统模块的serviceid
|
||||||
*/
|
*/
|
||||||
public static final String SYSTEM_SERVICE = "ruoyi-system";
|
public static final String SYSTEM_SERVICE = "ruoyi-system";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件服务的serviceid
|
||||||
|
*/
|
||||||
|
public static final String FILE_SERVICE = "ruoyi-file";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,5 +56,20 @@ public class UserConstants
|
|||||||
|
|
||||||
/** 校验返回结果码 */
|
/** 校验返回结果码 */
|
||||||
public final static String UNIQUE = "0";
|
public final static String UNIQUE = "0";
|
||||||
|
|
||||||
public final static String NOT_UNIQUE = "1";
|
public final static String NOT_UNIQUE = "1";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户名长度限制
|
||||||
|
*/
|
||||||
|
public static final int USERNAME_MIN_LENGTH = 2;
|
||||||
|
|
||||||
|
public static final int USERNAME_MAX_LENGTH = 20;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 密码长度限制
|
||||||
|
*/
|
||||||
|
public static final int PASSWORD_MIN_LENGTH = 5;
|
||||||
|
|
||||||
|
public static final int PASSWORD_MAX_LENGTH = 20;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.ruoyi.common.core.exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 权限异常
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public class PreAuthorizeException extends RuntimeException
|
||||||
|
{
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public PreAuthorizeException()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.ruoyi.common.core.exception.file;
|
||||||
|
|
||||||
|
import com.ruoyi.common.core.exception.BaseException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件信息异常类
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public class FileException extends BaseException
|
||||||
|
{
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public FileException(String code, Object[] args)
|
||||||
|
{
|
||||||
|
super("file", code, args, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.ruoyi.common.core.exception.file;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件名称超长限制异常类
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public class FileNameLengthLimitExceededException extends FileException
|
||||||
|
{
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public FileNameLengthLimitExceededException(int defaultFileNameLength)
|
||||||
|
{
|
||||||
|
super("upload.filename.exceed.length", new Object[] { defaultFileNameLength });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.ruoyi.common.core.exception.file;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件名大小限制异常类
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public class FileSizeLimitExceededException extends FileException
|
||||||
|
{
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public FileSizeLimitExceededException(long defaultMaxSize)
|
||||||
|
{
|
||||||
|
super("upload.exceed.maxSize", new Object[] { defaultMaxSize });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package com.ruoyi.common.core.exception.file;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import org.apache.commons.fileupload.FileUploadException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件上传 误异常类
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public class InvalidExtensionException extends FileUploadException
|
||||||
|
{
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
private String[] allowedExtension;
|
||||||
|
private String extension;
|
||||||
|
private String filename;
|
||||||
|
|
||||||
|
public InvalidExtensionException(String[] allowedExtension, String extension, String filename)
|
||||||
|
{
|
||||||
|
super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]");
|
||||||
|
this.allowedExtension = allowedExtension;
|
||||||
|
this.extension = extension;
|
||||||
|
this.filename = filename;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String[] getAllowedExtension()
|
||||||
|
{
|
||||||
|
return allowedExtension;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getExtension()
|
||||||
|
{
|
||||||
|
return extension;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFilename()
|
||||||
|
{
|
||||||
|
return filename;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class InvalidImageExtensionException extends InvalidExtensionException
|
||||||
|
{
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename)
|
||||||
|
{
|
||||||
|
super(allowedExtension, extension, filename);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class InvalidFlashExtensionException extends InvalidExtensionException
|
||||||
|
{
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename)
|
||||||
|
{
|
||||||
|
super(allowedExtension, extension, filename);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class InvalidMediaExtensionException extends InvalidExtensionException
|
||||||
|
{
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename)
|
||||||
|
{
|
||||||
|
super(allowedExtension, extension, filename);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class InvalidVideoExtensionException extends InvalidExtensionException
|
||||||
|
{
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename)
|
||||||
|
{
|
||||||
|
super(allowedExtension, extension, filename);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.ruoyi.common.core.utils;
|
package com.ruoyi.common.core.utils;
|
||||||
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import com.ruoyi.common.core.text.StrFormatter;
|
import com.ruoyi.common.core.text.StrFormatter;
|
||||||
|
|
||||||
@@ -17,6 +18,9 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
|
|||||||
/** 下划线 */
|
/** 下划线 */
|
||||||
private static final char SEPARATOR = '_';
|
private static final char SEPARATOR = '_';
|
||||||
|
|
||||||
|
/** 星号 */
|
||||||
|
private static final String START = "*";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取参数不为空值
|
* 获取参数不为空值
|
||||||
*
|
*
|
||||||
@@ -396,6 +400,121 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
|
|||||||
return sb.toString();
|
return sb.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
|
||||||
|
*
|
||||||
|
* @param str 指定字符串
|
||||||
|
* @param strs 需要检查的字符串数组
|
||||||
|
* @return 是否匹配
|
||||||
|
*/
|
||||||
|
public static boolean matches(String str, List<String> strs)
|
||||||
|
{
|
||||||
|
if (isEmpty(str) || isEmpty(strs))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (String testStr : strs)
|
||||||
|
{
|
||||||
|
if (matches(str, testStr))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查找指定字符串是否匹配指定字符串数组中的任意一个字符串
|
||||||
|
*
|
||||||
|
* @param str 指定字符串
|
||||||
|
* @param strs 需要检查的字符串数组
|
||||||
|
* @return 是否匹配
|
||||||
|
*/
|
||||||
|
public static boolean matches(String str, String... strs)
|
||||||
|
{
|
||||||
|
if (isEmpty(str) || isEmpty(strs))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (String testStr : strs)
|
||||||
|
{
|
||||||
|
if (matches(str, testStr))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查找指定字符串是否匹配
|
||||||
|
*
|
||||||
|
* @param str 指定字符串
|
||||||
|
* @param pattern 需要检查的字符串
|
||||||
|
* @return 是否匹配
|
||||||
|
*/
|
||||||
|
public static boolean matches(String str, String pattern)
|
||||||
|
{
|
||||||
|
if (isEmpty(pattern) || isEmpty(str))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
pattern = pattern.replaceAll("\\s*", ""); // 替换空格
|
||||||
|
int beginOffset = 0; // pattern截取开始位置
|
||||||
|
int formerStarOffset = -1; // 前星号的偏移位置
|
||||||
|
int latterStarOffset = -1; // 后星号的偏移位置
|
||||||
|
|
||||||
|
String remainingURI = str;
|
||||||
|
String prefixPattern = "";
|
||||||
|
String suffixPattern = "";
|
||||||
|
|
||||||
|
boolean result = false;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
formerStarOffset = indexOf(pattern, START, beginOffset);
|
||||||
|
prefixPattern = substring(pattern, beginOffset, formerStarOffset > -1 ? formerStarOffset : pattern.length());
|
||||||
|
|
||||||
|
// 匹配前缀Pattern
|
||||||
|
result = remainingURI.contains(prefixPattern);
|
||||||
|
// 已经没有星号,直接返回
|
||||||
|
if (formerStarOffset == -1)
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 匹配失败,直接返回
|
||||||
|
if (!result)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!isEmpty(prefixPattern))
|
||||||
|
{
|
||||||
|
remainingURI = substringAfter(str, prefixPattern);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 匹配后缀Pattern
|
||||||
|
latterStarOffset = indexOf(pattern, START, formerStarOffset + 1);
|
||||||
|
suffixPattern = substring(pattern, formerStarOffset + 1, latterStarOffset > -1 ? latterStarOffset : pattern.length());
|
||||||
|
|
||||||
|
result = remainingURI.contains(suffixPattern);
|
||||||
|
// 匹配失败,直接返回
|
||||||
|
if (!result)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
if (!isEmpty(suffixPattern))
|
||||||
|
{
|
||||||
|
remainingURI = substringAfter(str, suffixPattern);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 移动指针
|
||||||
|
beginOffset = latterStarOffset + 1;
|
||||||
|
|
||||||
|
}
|
||||||
|
while (!isEmpty(suffixPattern) && !isEmpty(remainingURI));
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public static <T> T cast(Object obj)
|
public static <T> T cast(Object obj)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package com.ruoyi.common.core.utils.file;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件类型工具类
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public class FileTypeUtils
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 获取文件类型
|
||||||
|
* <p>
|
||||||
|
* 例如: ruoyi.txt, 返回: txt
|
||||||
|
*
|
||||||
|
* @param file 文件名
|
||||||
|
* @return 后缀(不含".")
|
||||||
|
*/
|
||||||
|
public static String getFileType(File file)
|
||||||
|
{
|
||||||
|
if (null == file)
|
||||||
|
{
|
||||||
|
return StringUtils.EMPTY;
|
||||||
|
}
|
||||||
|
return getFileType(file.getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取文件类型
|
||||||
|
* <p>
|
||||||
|
* 例如: ruoyi.txt, 返回: txt
|
||||||
|
*
|
||||||
|
* @param fileName 文件名
|
||||||
|
* @return 后缀(不含".")
|
||||||
|
*/
|
||||||
|
public static String getFileType(String fileName)
|
||||||
|
{
|
||||||
|
int separatorIndex = fileName.lastIndexOf(".");
|
||||||
|
if (separatorIndex < 0)
|
||||||
|
{
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return fileName.substring(separatorIndex + 1).toLowerCase();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,11 @@ import java.io.IOException;
|
|||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.io.UnsupportedEncodingException;
|
import java.io.UnsupportedEncodingException;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import org.apache.commons.lang3.ArrayUtils;
|
||||||
|
import com.ruoyi.common.core.utils.StringUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 文件处理工具类
|
* 文件处理工具类
|
||||||
@@ -16,6 +20,12 @@ import javax.servlet.http.HttpServletRequest;
|
|||||||
*/
|
*/
|
||||||
public class FileUtils extends org.apache.commons.io.FileUtils
|
public class FileUtils extends org.apache.commons.io.FileUtils
|
||||||
{
|
{
|
||||||
|
/** 字符常量:斜杠 {@code '/'} */
|
||||||
|
public static final char SLASH = '/';
|
||||||
|
|
||||||
|
/** 字符常量:反斜杠 {@code '\\'} */
|
||||||
|
public static final char BACKSLASH = '\\';
|
||||||
|
|
||||||
public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
|
public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -104,6 +114,30 @@ public class FileUtils extends org.apache.commons.io.FileUtils
|
|||||||
return filename.matches(FILENAME_PATTERN);
|
return filename.matches(FILENAME_PATTERN);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查文件是否可下载
|
||||||
|
*
|
||||||
|
* @param resource 需要下载的文件
|
||||||
|
* @return true 正常 false 非法
|
||||||
|
*/
|
||||||
|
public static boolean checkAllowDownload(String resource)
|
||||||
|
{
|
||||||
|
// 禁止目录上跳级别
|
||||||
|
if (StringUtils.contains(resource, ".."))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查允许下载的文件规则
|
||||||
|
if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource)))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 不在允许下载的文件规则
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 下载文件名重新编码
|
* 下载文件名重新编码
|
||||||
*
|
*
|
||||||
@@ -111,8 +145,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils
|
|||||||
* @param fileName 文件名
|
* @param fileName 文件名
|
||||||
* @return 编码后的文件名
|
* @return 编码后的文件名
|
||||||
*/
|
*/
|
||||||
public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
|
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
|
||||||
throws UnsupportedEncodingException
|
|
||||||
{
|
{
|
||||||
final String agent = request.getHeader("USER-AGENT");
|
final String agent = request.getHeader("USER-AGENT");
|
||||||
String filename = fileName;
|
String filename = fileName;
|
||||||
@@ -139,4 +172,89 @@ public class FileUtils extends org.apache.commons.io.FileUtils
|
|||||||
}
|
}
|
||||||
return filename;
|
return filename;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 返回文件名
|
||||||
|
*
|
||||||
|
* @param filePath 文件
|
||||||
|
* @return 文件名
|
||||||
|
*/
|
||||||
|
public static String getName(String filePath)
|
||||||
|
{
|
||||||
|
if (null == filePath)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
int len = filePath.length();
|
||||||
|
if (0 == len)
|
||||||
|
{
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
|
if (isFileSeparator(filePath.charAt(len - 1)))
|
||||||
|
{
|
||||||
|
// 以分隔符结尾的去掉结尾分隔符
|
||||||
|
len--;
|
||||||
|
}
|
||||||
|
|
||||||
|
int begin = 0;
|
||||||
|
char c;
|
||||||
|
for (int i = len - 1; i > -1; i--)
|
||||||
|
{
|
||||||
|
c = filePath.charAt(i);
|
||||||
|
if (isFileSeparator(c))
|
||||||
|
{
|
||||||
|
// 查找最后一个路径分隔符(/或者\)
|
||||||
|
begin = i + 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return filePath.substring(begin, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否为Windows或者Linux(Unix)文件分隔符<br>
|
||||||
|
* Windows平台下分隔符为\,Linux(Unix)为/
|
||||||
|
*
|
||||||
|
* @param c 字符
|
||||||
|
* @return 是否为Windows或者Linux(Unix)文件分隔符
|
||||||
|
*/
|
||||||
|
public static boolean isFileSeparator(char c)
|
||||||
|
{
|
||||||
|
return SLASH == c || BACKSLASH == c;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 下载文件名重新编码
|
||||||
|
*
|
||||||
|
* @param response 响应对象
|
||||||
|
* @param realFileName 真实文件名
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
|
||||||
|
{
|
||||||
|
String percentEncodedFileName = percentEncode(realFileName);
|
||||||
|
|
||||||
|
StringBuilder contentDispositionValue = new StringBuilder();
|
||||||
|
contentDispositionValue.append("attachment; filename=")
|
||||||
|
.append(percentEncodedFileName)
|
||||||
|
.append(";")
|
||||||
|
.append("filename*=")
|
||||||
|
.append("utf-8''")
|
||||||
|
.append(percentEncodedFileName);
|
||||||
|
|
||||||
|
response.setHeader("Content-disposition", contentDispositionValue.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 百分号编码工具方法
|
||||||
|
*
|
||||||
|
* @param s 需要百分号编码的字符串
|
||||||
|
* @return 百分号编码后的字符串
|
||||||
|
*/
|
||||||
|
public static String percentEncode(String s) throws UnsupportedEncodingException
|
||||||
|
{
|
||||||
|
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
|
||||||
|
return encode.replaceAll("\\+", "%20");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package com.ruoyi.common.core.utils.file;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 媒体类型工具类
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public class MimeTypeUtils
|
||||||
|
{
|
||||||
|
public static final String IMAGE_PNG = "image/png";
|
||||||
|
|
||||||
|
public static final String IMAGE_JPG = "image/jpg";
|
||||||
|
|
||||||
|
public static final String IMAGE_JPEG = "image/jpeg";
|
||||||
|
|
||||||
|
public static final String IMAGE_BMP = "image/bmp";
|
||||||
|
|
||||||
|
public static final String IMAGE_GIF = "image/gif";
|
||||||
|
|
||||||
|
public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" };
|
||||||
|
|
||||||
|
public static final String[] FLASH_EXTENSION = { "swf", "flv" };
|
||||||
|
|
||||||
|
public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
|
||||||
|
"asf", "rm", "rmvb" };
|
||||||
|
|
||||||
|
public static final String[] VIDEO_EXTENSION = { "mp4", "avi", "rmvb" };
|
||||||
|
|
||||||
|
public static final String[] DEFAULT_ALLOWED_EXTENSION = {
|
||||||
|
// 图片
|
||||||
|
"bmp", "gif", "jpg", "jpeg", "png",
|
||||||
|
// word excel powerpoint
|
||||||
|
"doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
|
||||||
|
// 压缩文件
|
||||||
|
"rar", "zip", "gz", "bz2",
|
||||||
|
// 视频格式
|
||||||
|
"mp4", "avi", "rmvb",
|
||||||
|
// pdf
|
||||||
|
"pdf" };
|
||||||
|
|
||||||
|
public static String getExtension(String prefix)
|
||||||
|
{
|
||||||
|
switch (prefix)
|
||||||
|
{
|
||||||
|
case IMAGE_PNG:
|
||||||
|
return "png";
|
||||||
|
case IMAGE_JPG:
|
||||||
|
return "jpg";
|
||||||
|
case IMAGE_JPEG:
|
||||||
|
return "jpeg";
|
||||||
|
case IMAGE_BMP:
|
||||||
|
return "bmp";
|
||||||
|
case IMAGE_GIF:
|
||||||
|
return "gif";
|
||||||
|
default:
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,34 +14,43 @@ public class IpUtils
|
|||||||
{
|
{
|
||||||
public static String getIpAddr(HttpServletRequest request)
|
public static String getIpAddr(HttpServletRequest request)
|
||||||
{
|
{
|
||||||
if (request == null)
|
String ip = null;
|
||||||
|
|
||||||
|
// X-Forwarded-For:Squid 服务代理
|
||||||
|
String ipAddresses = request.getHeader("X-Forwarded-For");
|
||||||
|
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses))
|
||||||
{
|
{
|
||||||
return "unknown";
|
// Proxy-Client-IP:apache 服务代理
|
||||||
|
ipAddresses = request.getHeader("Proxy-Client-IP");
|
||||||
}
|
}
|
||||||
String ip = request.getHeader("x-forwarded-for");
|
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses))
|
||||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
|
|
||||||
{
|
{
|
||||||
ip = request.getHeader("Proxy-Client-IP");
|
// WL-Proxy-Client-IP:weblogic 服务代理
|
||||||
|
ipAddresses = request.getHeader("WL-Proxy-Client-IP");
|
||||||
}
|
}
|
||||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
|
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses))
|
||||||
{
|
{
|
||||||
ip = request.getHeader("X-Forwarded-For");
|
// HTTP_CLIENT_IP:有些代理服务器
|
||||||
|
ipAddresses = request.getHeader("HTTP_CLIENT_IP");
|
||||||
}
|
}
|
||||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
|
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses))
|
||||||
{
|
{
|
||||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
// X-Real-IP:nginx服务代理
|
||||||
}
|
ipAddresses = request.getHeader("X-Real-IP");
|
||||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
|
|
||||||
{
|
|
||||||
ip = request.getHeader("X-Real-IP");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
|
// 有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP
|
||||||
|
if (ipAddresses != null && ipAddresses.length() != 0)
|
||||||
|
{
|
||||||
|
ip = ipAddresses.split(",")[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 还是不能获取到,最后再通过request.getRemoteAddr();获取
|
||||||
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses))
|
||||||
{
|
{
|
||||||
ip = request.getRemoteAddr();
|
ip = request.getRemoteAddr();
|
||||||
}
|
}
|
||||||
|
return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
|
||||||
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean internalIp(String ip)
|
public static boolean internalIp(String ip)
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ import java.io.IOException;
|
|||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
import java.lang.reflect.Method;
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
|
import java.text.DecimalFormat;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
@@ -13,6 +13,7 @@ import java.util.Date;
|
|||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
|
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
|
||||||
@@ -96,6 +97,16 @@ public class ExcelUtil<T>
|
|||||||
*/
|
*/
|
||||||
private List<Object[]> fields;
|
private List<Object[]> fields;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计列表
|
||||||
|
*/
|
||||||
|
private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数字格式
|
||||||
|
*/
|
||||||
|
private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 实体对象
|
* 实体对象
|
||||||
*/
|
*/
|
||||||
@@ -226,19 +237,19 @@ public class ExcelUtil<T>
|
|||||||
val = Convert.toStr(val);
|
val = Convert.toStr(val);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType))
|
else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
|
||||||
{
|
{
|
||||||
val = Convert.toInt(val);
|
val = Convert.toInt(val);
|
||||||
}
|
}
|
||||||
else if ((Long.TYPE == fieldType) || (Long.class == fieldType))
|
else if (Long.TYPE == fieldType || Long.class == fieldType)
|
||||||
{
|
{
|
||||||
val = Convert.toLong(val);
|
val = Convert.toLong(val);
|
||||||
}
|
}
|
||||||
else if ((Double.TYPE == fieldType) || (Double.class == fieldType))
|
else if (Double.TYPE == fieldType || Double.class == fieldType)
|
||||||
{
|
{
|
||||||
val = Convert.toDouble(val);
|
val = Convert.toDouble(val);
|
||||||
}
|
}
|
||||||
else if ((Float.TYPE == fieldType) || (Float.class == fieldType))
|
else if (Float.TYPE == fieldType || Float.class == fieldType)
|
||||||
{
|
{
|
||||||
val = Convert.toFloat(val);
|
val = Convert.toFloat(val);
|
||||||
}
|
}
|
||||||
@@ -336,6 +347,7 @@ public class ExcelUtil<T>
|
|||||||
if (Type.EXPORT.equals(type))
|
if (Type.EXPORT.equals(type))
|
||||||
{
|
{
|
||||||
fillExcelData(index, row);
|
fillExcelData(index, row);
|
||||||
|
addStatisticsRow();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
wb.write(outputStream);
|
wb.write(outputStream);
|
||||||
@@ -438,6 +450,15 @@ public class ExcelUtil<T>
|
|||||||
headerFont.setColor(IndexedColors.WHITE.getIndex());
|
headerFont.setColor(IndexedColors.WHITE.getIndex());
|
||||||
style.setFont(headerFont);
|
style.setFont(headerFont);
|
||||||
styles.put("header", style);
|
styles.put("header", style);
|
||||||
|
|
||||||
|
style = wb.createCellStyle();
|
||||||
|
style.setAlignment(HorizontalAlignment.CENTER);
|
||||||
|
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||||
|
Font totalFont = wb.createFont();
|
||||||
|
totalFont.setFontName("Arial");
|
||||||
|
totalFont.setFontHeightInPoints((short) 10);
|
||||||
|
style.setFont(totalFont);
|
||||||
|
styles.put("total", style);
|
||||||
|
|
||||||
return styles;
|
return styles;
|
||||||
}
|
}
|
||||||
@@ -467,13 +488,13 @@ public class ExcelUtil<T>
|
|||||||
{
|
{
|
||||||
if (ColumnType.STRING == attr.cellType())
|
if (ColumnType.STRING == attr.cellType())
|
||||||
{
|
{
|
||||||
cell.setCellType(CellType.NUMERIC);
|
cell.setCellType(CellType.STRING);
|
||||||
cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
|
cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
|
||||||
}
|
}
|
||||||
else if (ColumnType.NUMERIC == attr.cellType())
|
else if (ColumnType.NUMERIC == attr.cellType())
|
||||||
{
|
{
|
||||||
cell.setCellType(CellType.NUMERIC);
|
cell.setCellType(CellType.NUMERIC);
|
||||||
cell.setCellValue(Integer.parseInt(value + ""));
|
cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -536,11 +557,16 @@ public class ExcelUtil<T>
|
|||||||
{
|
{
|
||||||
cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
|
cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
|
||||||
}
|
}
|
||||||
|
else if (value instanceof BigDecimal && -1 != attr.scale())
|
||||||
|
{
|
||||||
|
cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
|
||||||
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// 设置列类型
|
// 设置列类型
|
||||||
setCellVo(value, attr, cell);
|
setCellVo(value, attr, cell);
|
||||||
}
|
}
|
||||||
|
addStatisticsData(column, Convert.toStr(value), attr);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
@@ -681,6 +707,53 @@ public class ExcelUtil<T>
|
|||||||
return StringUtils.stripEnd(propertyString.toString(), separator);
|
return StringUtils.stripEnd(propertyString.toString(), separator);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 合计统计信息
|
||||||
|
*/
|
||||||
|
private void addStatisticsData(Integer index, String text, Excel entity)
|
||||||
|
{
|
||||||
|
if (entity != null && entity.isStatistics())
|
||||||
|
{
|
||||||
|
Double temp = 0D;
|
||||||
|
if (!statistics.containsKey(index))
|
||||||
|
{
|
||||||
|
statistics.put(index, temp);
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
temp = Double.valueOf(text);
|
||||||
|
}
|
||||||
|
catch (NumberFormatException e)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
statistics.put(index, statistics.get(index) + temp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建统计行
|
||||||
|
*/
|
||||||
|
public void addStatisticsRow()
|
||||||
|
{
|
||||||
|
if (statistics.size() > 0)
|
||||||
|
{
|
||||||
|
Cell cell = null;
|
||||||
|
Row row = sheet.createRow(sheet.getLastRowNum() + 1);
|
||||||
|
Set<Integer> keys = statistics.keySet();
|
||||||
|
cell = row.createCell(0);
|
||||||
|
cell.setCellStyle(styles.get("total"));
|
||||||
|
cell.setCellValue("合计");
|
||||||
|
|
||||||
|
for (Integer key : keys)
|
||||||
|
{
|
||||||
|
cell = row.createCell(key);
|
||||||
|
cell.setCellStyle(styles.get("total"));
|
||||||
|
cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
|
||||||
|
}
|
||||||
|
statistics.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取bean中的属性值
|
* 获取bean中的属性值
|
||||||
*
|
*
|
||||||
@@ -725,9 +798,9 @@ public class ExcelUtil<T>
|
|||||||
if (StringUtils.isNotEmpty(name))
|
if (StringUtils.isNotEmpty(name))
|
||||||
{
|
{
|
||||||
Class<?> clazz = o.getClass();
|
Class<?> clazz = o.getClass();
|
||||||
String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
|
Field field = clazz.getDeclaredField(name);
|
||||||
Method method = clazz.getMethod(methodName);
|
field.setAccessible(true);
|
||||||
o = method.invoke(o);
|
o = field.get(o);
|
||||||
}
|
}
|
||||||
return o;
|
return o;
|
||||||
}
|
}
|
||||||
@@ -831,7 +904,14 @@ public class ExcelUtil<T>
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
val = new BigDecimal(val.toString()); // 浮点格式处理
|
if ((Double) val % 1 > 0)
|
||||||
|
{
|
||||||
|
val = new BigDecimal(val.toString());
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
val = new DecimalFormat("0").format(val);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (cell.getCellTypeEnum() == CellType.STRING)
|
else if (cell.getCellTypeEnum() == CellType.STRING)
|
||||||
|
|||||||
@@ -57,6 +57,20 @@ public class AjaxResult extends HashMap<String, Object>
|
|||||||
super.put(DATA_TAG, data);
|
super.put(DATA_TAG, data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 方便链式调用
|
||||||
|
*
|
||||||
|
* @param key
|
||||||
|
* @param value
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public AjaxResult put(String key, Object value)
|
||||||
|
{
|
||||||
|
super.put(key, value);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 返回成功消息
|
* 返回成功消息
|
||||||
|
|||||||
@@ -17,9 +17,9 @@ public class PageDomain
|
|||||||
|
|
||||||
/** 排序列 */
|
/** 排序列 */
|
||||||
private String orderByColumn;
|
private String orderByColumn;
|
||||||
/** 排序的方向 "desc" 或者 "asc". */
|
|
||||||
|
|
||||||
private String isAsc;
|
/** 排序的方向desc或者asc */
|
||||||
|
private String isAsc = "asc";
|
||||||
|
|
||||||
public String getOrderBy()
|
public String getOrderBy()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi-common</artifactId>
|
<artifactId>ruoyi-common</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
|||||||
@@ -12,10 +12,10 @@ import org.springframework.stereotype.Component;
|
|||||||
import com.ruoyi.common.core.utils.StringUtils;
|
import com.ruoyi.common.core.utils.StringUtils;
|
||||||
import com.ruoyi.common.core.web.domain.BaseEntity;
|
import com.ruoyi.common.core.web.domain.BaseEntity;
|
||||||
import com.ruoyi.common.datascope.annotation.DataScope;
|
import com.ruoyi.common.datascope.annotation.DataScope;
|
||||||
import com.ruoyi.common.datascope.service.AwaitUserService;
|
import com.ruoyi.common.security.service.TokenService;
|
||||||
import com.ruoyi.system.api.domain.SysRole;
|
import com.ruoyi.system.api.domain.SysRole;
|
||||||
import com.ruoyi.system.api.domain.SysUser;
|
import com.ruoyi.system.api.domain.SysUser;
|
||||||
import com.ruoyi.system.api.model.UserInfo;
|
import com.ruoyi.system.api.model.LoginUser;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 数据过滤处理
|
* 数据过滤处理
|
||||||
@@ -57,7 +57,7 @@ public class DataScopeAspect
|
|||||||
public static final String DATA_SCOPE = "dataScope";
|
public static final String DATA_SCOPE = "dataScope";
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private AwaitUserService awaitUserService;
|
private TokenService tokenService;
|
||||||
|
|
||||||
// 配置织入点
|
// 配置织入点
|
||||||
@Pointcut("@annotation(com.ruoyi.common.datascope.annotation.DataScope)")
|
@Pointcut("@annotation(com.ruoyi.common.datascope.annotation.DataScope)")
|
||||||
@@ -80,12 +80,12 @@ public class DataScopeAspect
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 获取当前的用户
|
// 获取当前的用户
|
||||||
UserInfo loginUser = awaitUserService.info();
|
LoginUser loginUser = tokenService.getLoginUser();
|
||||||
SysUser currentUser = loginUser.getSysUser();
|
if (StringUtils.isNotNull(loginUser))
|
||||||
if (currentUser != null)
|
|
||||||
{
|
{
|
||||||
|
SysUser currentUser = loginUser.getSysUser();
|
||||||
// 如果是超级管理员,则不过滤数据
|
// 如果是超级管理员,则不过滤数据
|
||||||
if (!currentUser.isAdmin())
|
if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())
|
||||||
{
|
{
|
||||||
dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
|
dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
|
||||||
controllerDataScope.userAlias());
|
controllerDataScope.userAlias());
|
||||||
@@ -145,8 +145,12 @@ public class DataScopeAspect
|
|||||||
|
|
||||||
if (StringUtils.isNotBlank(sqlString.toString()))
|
if (StringUtils.isNotBlank(sqlString.toString()))
|
||||||
{
|
{
|
||||||
BaseEntity baseEntity = (BaseEntity) joinPoint.getArgs()[0];
|
Object params = joinPoint.getArgs()[0];
|
||||||
baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
|
if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
|
||||||
|
{
|
||||||
|
BaseEntity baseEntity = (BaseEntity) params;
|
||||||
|
baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,42 +0,0 @@
|
|||||||
package com.ruoyi.common.datascope.service;
|
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import com.ruoyi.common.core.domain.R;
|
|
||||||
import com.ruoyi.common.core.utils.StringUtils;
|
|
||||||
import com.ruoyi.common.security.utils.SecurityUtils;
|
|
||||||
import com.ruoyi.system.api.RemoteUserService;
|
|
||||||
import com.ruoyi.system.api.model.UserInfo;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 同步调用用户服务
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
@Service
|
|
||||||
public class AwaitUserService
|
|
||||||
{
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(AwaitUserService.class);
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private RemoteUserService remoteUserService;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 查询当前用户信息
|
|
||||||
*
|
|
||||||
* @return 用户基本信息
|
|
||||||
*/
|
|
||||||
public UserInfo info()
|
|
||||||
{
|
|
||||||
String username = SecurityUtils.getUsername();
|
|
||||||
R<UserInfo> userResult = remoteUserService.getUserInfo(username);
|
|
||||||
if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
|
|
||||||
{
|
|
||||||
log.info("数据权限范围查询用户:{} 不存在.", username);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return userResult.getData();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||||
com.ruoyi.common.datascope.service.AwaitUserService,\
|
|
||||||
com.ruoyi.common.datascope.aspect.DataScopeAspect
|
com.ruoyi.common.datascope.aspect.DataScopeAspect
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi-common</artifactId>
|
<artifactId>ruoyi-common</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package com.ruoyi.common.log.aspect;
|
package com.ruoyi.common.log.aspect;
|
||||||
|
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.util.Map;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import org.aspectj.lang.JoinPoint;
|
import org.aspectj.lang.JoinPoint;
|
||||||
@@ -17,16 +16,14 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
import org.springframework.web.servlet.HandlerMapping;
|
|
||||||
import com.alibaba.fastjson.JSON;
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.ruoyi.common.core.constant.CacheConstants;
|
||||||
import com.ruoyi.common.core.utils.ServletUtils;
|
import com.ruoyi.common.core.utils.ServletUtils;
|
||||||
import com.ruoyi.common.core.utils.StringUtils;
|
import com.ruoyi.common.core.utils.StringUtils;
|
||||||
import com.ruoyi.common.core.utils.ip.IpUtils;
|
import com.ruoyi.common.core.utils.ip.IpUtils;
|
||||||
import com.ruoyi.common.log.annotation.Log;
|
import com.ruoyi.common.log.annotation.Log;
|
||||||
import com.ruoyi.common.log.enums.BusinessStatus;
|
import com.ruoyi.common.log.enums.BusinessStatus;
|
||||||
import com.ruoyi.common.log.service.AsyncLogService;
|
import com.ruoyi.common.log.service.AsyncLogService;
|
||||||
import com.ruoyi.common.security.domain.LoginUser;
|
|
||||||
import com.ruoyi.common.security.utils.SecurityUtils;
|
|
||||||
import com.ruoyi.system.api.domain.SysOperLog;
|
import com.ruoyi.system.api.domain.SysOperLog;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -83,9 +80,6 @@ public class LogAspect
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取当前的用户
|
|
||||||
LoginUser loginUser = SecurityUtils.getLoginUser();
|
|
||||||
|
|
||||||
// *========数据库日志=========*//
|
// *========数据库日志=========*//
|
||||||
SysOperLog operLog = new SysOperLog();
|
SysOperLog operLog = new SysOperLog();
|
||||||
operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
|
operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
|
||||||
@@ -96,9 +90,11 @@ public class LogAspect
|
|||||||
operLog.setJsonResult(JSON.toJSONString(jsonResult));
|
operLog.setJsonResult(JSON.toJSONString(jsonResult));
|
||||||
|
|
||||||
operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
|
operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
|
||||||
if (loginUser != null)
|
HttpServletRequest request = ServletUtils.getRequest();
|
||||||
|
String username = request.getHeader(CacheConstants.DETAILS_USERNAME);
|
||||||
|
if (StringUtils.isNotBlank(username))
|
||||||
{
|
{
|
||||||
operLog.setOperName(loginUser.getUsername());
|
operLog.setOperName(username);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (e != null)
|
if (e != null)
|
||||||
@@ -163,11 +159,6 @@ public class LogAspect
|
|||||||
String params = argsArrayToString(joinPoint.getArgs());
|
String params = argsArrayToString(joinPoint.getArgs());
|
||||||
operLog.setOperParam(StringUtils.substring(params, 0, 2000));
|
operLog.setOperParam(StringUtils.substring(params, 0, 2000));
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
|
||||||
Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
|
|
||||||
operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi-common</artifactId>
|
<artifactId>ruoyi-common</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ public class RedisService
|
|||||||
* @param timeout 时间
|
* @param timeout 时间
|
||||||
* @param timeUnit 时间颗粒度
|
* @param timeUnit 时间颗粒度
|
||||||
*/
|
*/
|
||||||
public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
|
public <T> void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit)
|
||||||
{
|
{
|
||||||
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
|
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi-common</artifactId>
|
<artifactId>ruoyi-common</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
@@ -16,18 +16,18 @@
|
|||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
||||||
<!-- Spring Security Oauth2 -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.cloud</groupId>
|
|
||||||
<artifactId>spring-cloud-starter-oauth2</artifactId>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<!-- RuoYi Api System -->
|
<!-- RuoYi Api System -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi-api-system</artifactId>
|
<artifactId>ruoyi-api-system</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- RuoYi Common Redis-->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.ruoyi</groupId>
|
||||||
|
<artifactId>ruoyi-common-redis</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -5,9 +5,7 @@ import org.mybatis.spring.annotation.MapperScan;
|
|||||||
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||||
import org.springframework.context.annotation.Import;
|
import org.springframework.context.annotation.Import;
|
||||||
import org.springframework.scheduling.annotation.EnableAsync;
|
import org.springframework.scheduling.annotation.EnableAsync;
|
||||||
import com.ruoyi.common.security.feign.OAuth2FeignConfig;
|
|
||||||
import com.ruoyi.common.security.config.ApplicationConfig;
|
import com.ruoyi.common.security.config.ApplicationConfig;
|
||||||
import com.ruoyi.common.security.config.SecurityImportBeanDefinitionRegistrar;
|
|
||||||
|
|
||||||
@Target(ElementType.TYPE)
|
@Target(ElementType.TYPE)
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
@@ -20,7 +18,7 @@ import com.ruoyi.common.security.config.SecurityImportBeanDefinitionRegistrar;
|
|||||||
// 开启线程异步执行
|
// 开启线程异步执行
|
||||||
@EnableAsync
|
@EnableAsync
|
||||||
// 自动加载类
|
// 自动加载类
|
||||||
@Import({ SecurityImportBeanDefinitionRegistrar.class, OAuth2FeignConfig.class, ApplicationConfig.class })
|
@Import({ApplicationConfig.class})
|
||||||
public @interface EnableCustomConfig
|
public @interface EnableCustomConfig
|
||||||
{
|
{
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.ruoyi.common.security.annotation;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 权限注解
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@Target({ ElementType.TYPE, ElementType.METHOD })
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
public @interface PreAuthorize
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 验证用户是否具备某权限
|
||||||
|
*/
|
||||||
|
public String hasPermi() default "";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证用户是否不具备某权限,与 hasPermi逻辑相反
|
||||||
|
*/
|
||||||
|
public String lacksPermi() default "";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证用户是否具有以下任意一个权限
|
||||||
|
*/
|
||||||
|
public String[] hasAnyPermi() default {};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断用户是否拥有某个角色
|
||||||
|
*/
|
||||||
|
public String hasRole() default "";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证用户是否不具备某角色,与 isRole逻辑相反
|
||||||
|
*/
|
||||||
|
public String lacksRole() default "";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证用户是否具有以下任意一个角色
|
||||||
|
*/
|
||||||
|
public String[] hasAnyRoles() default {};
|
||||||
|
}
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
package com.ruoyi.common.security.aspect;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Collection;
|
||||||
|
import org.aspectj.lang.ProceedingJoinPoint;
|
||||||
|
import org.aspectj.lang.Signature;
|
||||||
|
import org.aspectj.lang.annotation.Around;
|
||||||
|
import org.aspectj.lang.annotation.Aspect;
|
||||||
|
import org.aspectj.lang.reflect.MethodSignature;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.util.CollectionUtils;
|
||||||
|
import org.springframework.util.PatternMatchUtils;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import com.ruoyi.common.core.exception.PreAuthorizeException;
|
||||||
|
import com.ruoyi.common.security.annotation.PreAuthorize;
|
||||||
|
import com.ruoyi.common.security.service.TokenService;
|
||||||
|
import com.ruoyi.system.api.model.LoginUser;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自定义权限实现
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@Aspect
|
||||||
|
@Component
|
||||||
|
public class PreAuthorizeAspect
|
||||||
|
{
|
||||||
|
@Autowired
|
||||||
|
private TokenService tokenService;
|
||||||
|
|
||||||
|
/** 所有权限标识 */
|
||||||
|
private static final String ALL_PERMISSION = "*:*:*";
|
||||||
|
|
||||||
|
/** 管理员角色权限标识 */
|
||||||
|
private static final String SUPER_ADMIN = "admin";
|
||||||
|
|
||||||
|
/** 数组为0时 */
|
||||||
|
private static final Integer ARRAY_EMPTY = 0;
|
||||||
|
|
||||||
|
@Around("@annotation(com.ruoyi.common.security.annotation.PreAuthorize)")
|
||||||
|
public Object around(ProceedingJoinPoint point) throws Throwable
|
||||||
|
{
|
||||||
|
Signature signature = point.getSignature();
|
||||||
|
MethodSignature methodSignature = (MethodSignature) signature;
|
||||||
|
Method method = methodSignature.getMethod();
|
||||||
|
PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
|
||||||
|
if (annotation == null)
|
||||||
|
{
|
||||||
|
return point.proceed();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!StringUtils.isEmpty(annotation.hasPermi()))
|
||||||
|
{
|
||||||
|
if (hasPermi(annotation.hasPermi()))
|
||||||
|
{
|
||||||
|
return point.proceed();
|
||||||
|
}
|
||||||
|
throw new PreAuthorizeException();
|
||||||
|
}
|
||||||
|
else if (!StringUtils.isEmpty(annotation.lacksPermi()))
|
||||||
|
{
|
||||||
|
if (lacksPermi(annotation.lacksPermi()))
|
||||||
|
{
|
||||||
|
return point.proceed();
|
||||||
|
}
|
||||||
|
throw new PreAuthorizeException();
|
||||||
|
}
|
||||||
|
else if (ARRAY_EMPTY < annotation.hasAnyPermi().length)
|
||||||
|
{
|
||||||
|
if (hasAnyPermi(annotation.hasAnyPermi()))
|
||||||
|
{
|
||||||
|
return point.proceed();
|
||||||
|
}
|
||||||
|
throw new PreAuthorizeException();
|
||||||
|
}
|
||||||
|
else if (!StringUtils.isEmpty(annotation.hasRole()))
|
||||||
|
{
|
||||||
|
if (hasRole(annotation.hasRole()))
|
||||||
|
{
|
||||||
|
return point.proceed();
|
||||||
|
}
|
||||||
|
throw new PreAuthorizeException();
|
||||||
|
}
|
||||||
|
else if (!StringUtils.isEmpty(annotation.lacksRole()))
|
||||||
|
{
|
||||||
|
if (lacksRole(annotation.lacksRole()))
|
||||||
|
{
|
||||||
|
return point.proceed();
|
||||||
|
}
|
||||||
|
throw new PreAuthorizeException();
|
||||||
|
}
|
||||||
|
else if (ARRAY_EMPTY < annotation.hasAnyRoles().length)
|
||||||
|
{
|
||||||
|
if (hasAnyRoles(annotation.hasAnyRoles()))
|
||||||
|
{
|
||||||
|
return point.proceed();
|
||||||
|
}
|
||||||
|
throw new PreAuthorizeException();
|
||||||
|
}
|
||||||
|
|
||||||
|
return point.proceed();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证用户是否具备某权限
|
||||||
|
*
|
||||||
|
* @param permission 权限字符串
|
||||||
|
* @return 用户是否具备某权限
|
||||||
|
*/
|
||||||
|
public boolean hasPermi(String permission)
|
||||||
|
{
|
||||||
|
LoginUser userInfo = tokenService.getLoginUser();
|
||||||
|
if (StringUtils.isEmpty(userInfo) || CollectionUtils.isEmpty(userInfo.getPermissions()))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return hasPermissions(userInfo.getPermissions(), permission);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证用户是否不具备某权限,与 hasPermi逻辑相反
|
||||||
|
*
|
||||||
|
* @param permission 权限字符串
|
||||||
|
* @return 用户是否不具备某权限
|
||||||
|
*/
|
||||||
|
public boolean lacksPermi(String permission)
|
||||||
|
{
|
||||||
|
return hasPermi(permission) != true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证用户是否具有以下任意一个权限
|
||||||
|
*
|
||||||
|
* @param permissions 权限列表
|
||||||
|
* @return 用户是否具有以下任意一个权限
|
||||||
|
*/
|
||||||
|
public boolean hasAnyPermi(String[] permissions)
|
||||||
|
{
|
||||||
|
LoginUser userInfo = tokenService.getLoginUser();
|
||||||
|
if (StringUtils.isEmpty(userInfo) || CollectionUtils.isEmpty(userInfo.getPermissions()))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Collection<String> authorities = userInfo.getPermissions();
|
||||||
|
for (String permission : permissions)
|
||||||
|
{
|
||||||
|
if (permission != null && hasPermissions(authorities, permission))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断用户是否拥有某个角色
|
||||||
|
*
|
||||||
|
* @param role 角色字符串
|
||||||
|
* @return 用户是否具备某角色
|
||||||
|
*/
|
||||||
|
public boolean hasRole(String role)
|
||||||
|
{
|
||||||
|
LoginUser userInfo = tokenService.getLoginUser();
|
||||||
|
if (StringUtils.isEmpty(userInfo) || CollectionUtils.isEmpty(userInfo.getRoles()))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (String roleKey : userInfo.getRoles())
|
||||||
|
{
|
||||||
|
if (SUPER_ADMIN.equals(roleKey) || roleKey.equals(role))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证用户是否不具备某角色,与 isRole逻辑相反。
|
||||||
|
*
|
||||||
|
* @param role 角色名称
|
||||||
|
* @return 用户是否不具备某角色
|
||||||
|
*/
|
||||||
|
public boolean lacksRole(String role)
|
||||||
|
{
|
||||||
|
return hasRole(role) != true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证用户是否具有以下任意一个角色
|
||||||
|
*
|
||||||
|
* @param roles 角色列表
|
||||||
|
* @return 用户是否具有以下任意一个角色
|
||||||
|
*/
|
||||||
|
public boolean hasAnyRoles(String[] roles)
|
||||||
|
{
|
||||||
|
LoginUser userInfo = tokenService.getLoginUser();
|
||||||
|
if (StringUtils.isEmpty(userInfo) || CollectionUtils.isEmpty(userInfo.getRoles()))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (String role : roles)
|
||||||
|
{
|
||||||
|
if (hasRole(role))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否包含权限
|
||||||
|
*
|
||||||
|
* @param authorities 权限列表
|
||||||
|
* @param permission 权限字符串
|
||||||
|
* @return 用户是否具备某权限
|
||||||
|
*/
|
||||||
|
private boolean hasPermissions(Collection<String> authorities, String permission)
|
||||||
|
{
|
||||||
|
return authorities.stream().filter(StringUtils::hasText)
|
||||||
|
.anyMatch(x -> ALL_PERMISSION.contains(x) || PatternMatchUtils.simpleMatch(permission, x));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
package com.ruoyi.common.security.config;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import org.springframework.beans.factory.annotation.Configurable;
|
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 忽略服务间的认证
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
**/
|
|
||||||
@Component
|
|
||||||
@Configurable
|
|
||||||
@ConfigurationProperties(prefix = "security.oauth2.ignore")
|
|
||||||
public class AuthIgnoreConfig
|
|
||||||
{
|
|
||||||
private List<String> urls = new ArrayList<>();
|
|
||||||
|
|
||||||
public List<String> getUrls()
|
|
||||||
{
|
|
||||||
return urls;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUrls(List<String> urls)
|
|
||||||
{
|
|
||||||
this.urls = urls;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
package com.ruoyi.common.security.config;
|
|
||||||
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
|
||||||
import org.springframework.security.core.authority.AuthorityUtils;
|
|
||||||
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
|
|
||||||
import org.springframework.util.StringUtils;
|
|
||||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
|
||||||
import com.ruoyi.common.core.text.Convert;
|
|
||||||
import com.ruoyi.common.security.domain.LoginUser;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* https://my.oschina.net/giegie/blog/3023768 根据checktoken 的结果转化用户信息
|
|
||||||
*
|
|
||||||
* @author lengleng
|
|
||||||
*/
|
|
||||||
public class CommonUserConverter implements UserAuthenticationConverter
|
|
||||||
{
|
|
||||||
private static final String N_A = "N/A";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 将授权信息返回到资源服务
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public Map<String, ?> convertUserAuthentication(Authentication userAuthentication)
|
|
||||||
{
|
|
||||||
Map<String, Object> authMap = new LinkedHashMap<>();
|
|
||||||
authMap.put(USERNAME, userAuthentication.getName());
|
|
||||||
if (userAuthentication.getAuthorities() != null && !userAuthentication.getAuthorities().isEmpty())
|
|
||||||
{
|
|
||||||
authMap.put(AUTHORITIES, AuthorityUtils.authorityListToSet(userAuthentication.getAuthorities()));
|
|
||||||
}
|
|
||||||
return authMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取用户认证信息
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public Authentication extractAuthentication(Map<String, ?> map)
|
|
||||||
{
|
|
||||||
if (map.containsKey(USERNAME))
|
|
||||||
{
|
|
||||||
Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
|
|
||||||
|
|
||||||
Long userId = Convert.toLong(map.get(SecurityConstants.DETAILS_USER_ID));
|
|
||||||
String username = (String) map.get(SecurityConstants.DETAILS_USERNAME);
|
|
||||||
LoginUser user = new LoginUser(userId, username, N_A, true, true, true, true, authorities);
|
|
||||||
return new UsernamePasswordAuthenticationToken(user, N_A, authorities);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取权限资源信息
|
|
||||||
*/
|
|
||||||
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map)
|
|
||||||
{
|
|
||||||
Object authorities = map.get(AUTHORITIES);
|
|
||||||
if (authorities instanceof String)
|
|
||||||
{
|
|
||||||
return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
|
|
||||||
}
|
|
||||||
if (authorities instanceof Collection)
|
|
||||||
{
|
|
||||||
return AuthorityUtils.commaSeparatedStringToAuthorityList(
|
|
||||||
StringUtils.collectionToCommaDelimitedString((Collection<?>) authorities));
|
|
||||||
}
|
|
||||||
throw new IllegalArgumentException("Authorities must be either a String or a Collection");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
package com.ruoyi.common.security.config;
|
|
||||||
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @EnableGlobalMethodSecurity(securedEnabled=true)
|
|
||||||
* 开启@Secured 注解过滤权限
|
|
||||||
*
|
|
||||||
* @EnableGlobalMethodSecurity(jsr250Enabled=true)
|
|
||||||
* 开启@RolesAllowed 注解过滤权限
|
|
||||||
*
|
|
||||||
* @EnableGlobalMethodSecurity(prePostEnabled=true)
|
|
||||||
* 使用表达式时间方法级别的安全性 4个注解可用
|
|
||||||
* -@PreAuthorize 在方法调用之前,基于表达式的计算结果来限制对方法的访问
|
|
||||||
* -@PostAuthorize 允许方法调用,但是如果表达式计算结果为false,将抛出一个安全性异常
|
|
||||||
* -@PostFilter 允许方法调用,但必须按照表达式来过滤方法的结果
|
|
||||||
* -@PreFilter 允许方法调用,但必须在进入方法之前过滤输入值
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
@Configuration
|
|
||||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
|
||||||
public class MethodSecurityConfig
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
package com.ruoyi.common.security.config;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
|
|
||||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
|
|
||||||
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
|
||||||
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
|
|
||||||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
|
|
||||||
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
|
|
||||||
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
|
|
||||||
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
|
|
||||||
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
|
|
||||||
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
|
|
||||||
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
|
|
||||||
import org.springframework.web.client.DefaultResponseErrorHandler;
|
|
||||||
import org.springframework.web.client.RestTemplate;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* oauth2 服务配置
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
@Configuration
|
|
||||||
@EnableResourceServer
|
|
||||||
public class ResourceServerConfig extends ResourceServerConfigurerAdapter
|
|
||||||
{
|
|
||||||
@Autowired
|
|
||||||
private ResourceServerProperties resourceServerProperties;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private OAuth2ClientProperties oAuth2ClientProperties;
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
public AuthIgnoreConfig authIgnoreConfig()
|
|
||||||
{
|
|
||||||
return new AuthIgnoreConfig();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
@LoadBalanced
|
|
||||||
public RestTemplate restTemplate()
|
|
||||||
{
|
|
||||||
RestTemplate restTemplate = new RestTemplate();
|
|
||||||
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
|
|
||||||
return restTemplate;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
public ResourceServerTokenServices tokenServices()
|
|
||||||
{
|
|
||||||
RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
|
|
||||||
DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
|
|
||||||
UserAuthenticationConverter userTokenConverter = new CommonUserConverter();
|
|
||||||
accessTokenConverter.setUserTokenConverter(userTokenConverter);
|
|
||||||
remoteTokenServices.setCheckTokenEndpointUrl(resourceServerProperties.getTokenInfoUri());
|
|
||||||
remoteTokenServices.setClientId(oAuth2ClientProperties.getClientId());
|
|
||||||
remoteTokenServices.setClientSecret(oAuth2ClientProperties.getClientSecret());
|
|
||||||
remoteTokenServices.setRestTemplate(restTemplate());
|
|
||||||
remoteTokenServices.setAccessTokenConverter(accessTokenConverter);
|
|
||||||
return remoteTokenServices;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void configure(HttpSecurity http) throws Exception
|
|
||||||
{
|
|
||||||
http.csrf().disable();
|
|
||||||
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
|
|
||||||
.authorizeRequests();
|
|
||||||
// 不登录可以访问
|
|
||||||
authIgnoreConfig().getUrls().forEach(url -> registry.antMatchers(url).permitAll());
|
|
||||||
registry.anyRequest().authenticated();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void configure(ResourceServerSecurityConfigurer resources)
|
|
||||||
{
|
|
||||||
resources.tokenServices(tokenServices());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
package com.ruoyi.common.security.config;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
|
||||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
|
||||||
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
|
|
||||||
import org.springframework.core.type.AnnotationMetadata;
|
|
||||||
import com.ruoyi.common.core.utils.StringUtils;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 导入 SecurityImportBeanDefinitionRegistrar 自动加载类
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
public class SecurityImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar
|
|
||||||
{
|
|
||||||
@Override
|
|
||||||
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry)
|
|
||||||
{
|
|
||||||
Class<ResourceServerConfig> aClass = ResourceServerConfig.class;
|
|
||||||
String beanName = StringUtils.uncapitalize(aClass.getSimpleName());
|
|
||||||
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(ResourceServerConfig.class);
|
|
||||||
registry.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
package com.ruoyi.common.security.domain;
|
|
||||||
|
|
||||||
import java.util.Collection;
|
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
|
||||||
import org.springframework.security.core.userdetails.User;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 登录用户身份权限
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
public class LoginUser extends User
|
|
||||||
{
|
|
||||||
private static final long serialVersionUID = 1L;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 用户ID
|
|
||||||
*/
|
|
||||||
private Long userId;
|
|
||||||
|
|
||||||
public LoginUser(Long userId, String username, String password, boolean enabled, boolean accountNonExpired,
|
|
||||||
boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities)
|
|
||||||
{
|
|
||||||
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
|
|
||||||
this.userId = userId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getUserId()
|
|
||||||
{
|
|
||||||
return userId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUserId(Long userId)
|
|
||||||
{
|
|
||||||
this.userId = userId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
package com.ruoyi.common.security.feign;
|
|
||||||
|
|
||||||
import org.springframework.context.annotation.Bean;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import feign.RequestInterceptor;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Feign配置注册
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
**/
|
|
||||||
@Configuration
|
|
||||||
public class OAuth2FeignConfig
|
|
||||||
{
|
|
||||||
@Bean
|
|
||||||
public RequestInterceptor requestInterceptor()
|
|
||||||
{
|
|
||||||
return new OAuth2FeignRequestInterceptor();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
package com.ruoyi.common.security.feign;
|
|
||||||
|
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.context.SecurityContext;
|
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
|
||||||
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
|
||||||
import feign.RequestInterceptor;
|
|
||||||
import feign.RequestTemplate;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* feign 请求拦截器
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
@Component
|
|
||||||
public class OAuth2FeignRequestInterceptor implements RequestInterceptor
|
|
||||||
{
|
|
||||||
@Override
|
|
||||||
public void apply(RequestTemplate requestTemplate)
|
|
||||||
{
|
|
||||||
SecurityContext securityContext = SecurityContextHolder.getContext();
|
|
||||||
Authentication authentication = securityContext.getAuthentication();
|
|
||||||
if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails)
|
|
||||||
{
|
|
||||||
OAuth2AuthenticationDetails dateils = (OAuth2AuthenticationDetails) authentication.getDetails();
|
|
||||||
requestTemplate.header(HttpHeaders.AUTHORIZATION,
|
|
||||||
String.format("%s %s", SecurityConstants.BEARER_TOKEN_TYPE, dateils.getTokenValue()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
package com.ruoyi.common.security.handler;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.security.access.AccessDeniedException;
|
|
||||||
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
import com.alibaba.fastjson.JSON;
|
|
||||||
import com.ruoyi.common.core.constant.HttpStatus;
|
|
||||||
import com.ruoyi.common.core.domain.R;
|
|
||||||
import com.ruoyi.common.core.utils.ServletUtils;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自定义访问无权限资源时的异常
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
@Component
|
|
||||||
public class CustomAccessDeniedHandler extends OAuth2AccessDeniedHandler
|
|
||||||
{
|
|
||||||
private final Logger logger = LoggerFactory.getLogger(CustomAccessDeniedHandler.class);
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException)
|
|
||||||
{
|
|
||||||
logger.info("权限不足,请联系管理员 {}", request.getRequestURI());
|
|
||||||
|
|
||||||
String msg = authException.getMessage();
|
|
||||||
ServletUtils.renderString(response, JSON.toJSONString(R.fail(HttpStatus.FORBIDDEN, msg)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,18 +2,14 @@ package com.ruoyi.common.security.handler;
|
|||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.security.access.AccessDeniedException;
|
|
||||||
import org.springframework.security.authentication.AccountExpiredException;
|
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
|
||||||
import org.springframework.validation.BindException;
|
import org.springframework.validation.BindException;
|
||||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
|
||||||
import com.ruoyi.common.core.constant.HttpStatus;
|
|
||||||
import com.ruoyi.common.core.exception.BaseException;
|
import com.ruoyi.common.core.exception.BaseException;
|
||||||
import com.ruoyi.common.core.exception.CustomException;
|
import com.ruoyi.common.core.exception.CustomException;
|
||||||
import com.ruoyi.common.core.exception.DemoModeException;
|
import com.ruoyi.common.core.exception.DemoModeException;
|
||||||
|
import com.ruoyi.common.core.exception.PreAuthorizeException;
|
||||||
import com.ruoyi.common.core.utils.StringUtils;
|
import com.ruoyi.common.core.utils.StringUtils;
|
||||||
import com.ruoyi.common.core.web.domain.AjaxResult;
|
import com.ruoyi.common.core.web.domain.AjaxResult;
|
||||||
|
|
||||||
@@ -33,7 +29,7 @@ public class GlobalExceptionHandler
|
|||||||
@ExceptionHandler(BaseException.class)
|
@ExceptionHandler(BaseException.class)
|
||||||
public AjaxResult baseException(BaseException e)
|
public AjaxResult baseException(BaseException e)
|
||||||
{
|
{
|
||||||
return AjaxResult.error(e.getMessage());
|
return AjaxResult.error(e.getDefaultMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -49,34 +45,6 @@ public class GlobalExceptionHandler
|
|||||||
return AjaxResult.error(e.getCode(), e.getMessage());
|
return AjaxResult.error(e.getCode(), e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ExceptionHandler(NoHandlerFoundException.class)
|
|
||||||
public AjaxResult handlerNoFoundException(Exception e)
|
|
||||||
{
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return AjaxResult.error(HttpStatus.NOT_FOUND, "路径不存在,请检查路径是否正确");
|
|
||||||
}
|
|
||||||
|
|
||||||
@ExceptionHandler(AccessDeniedException.class)
|
|
||||||
public AjaxResult handleAuthorizationException(AccessDeniedException e)
|
|
||||||
{
|
|
||||||
log.error(e.getMessage());
|
|
||||||
return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权");
|
|
||||||
}
|
|
||||||
|
|
||||||
@ExceptionHandler(AccountExpiredException.class)
|
|
||||||
public AjaxResult handleAccountExpiredException(AccountExpiredException e)
|
|
||||||
{
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return AjaxResult.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
@ExceptionHandler(UsernameNotFoundException.class)
|
|
||||||
public AjaxResult handleUsernameNotFoundException(UsernameNotFoundException e)
|
|
||||||
{
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return AjaxResult.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
@ExceptionHandler(Exception.class)
|
@ExceptionHandler(Exception.class)
|
||||||
public AjaxResult handleException(Exception e)
|
public AjaxResult handleException(Exception e)
|
||||||
{
|
{
|
||||||
@@ -105,7 +73,16 @@ public class GlobalExceptionHandler
|
|||||||
String message = e.getBindingResult().getFieldError().getDefaultMessage();
|
String message = e.getBindingResult().getFieldError().getDefaultMessage();
|
||||||
return AjaxResult.error(message);
|
return AjaxResult.error(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 权限异常
|
||||||
|
*/
|
||||||
|
@ExceptionHandler(PreAuthorizeException.class)
|
||||||
|
public AjaxResult preAuthorizeException(PreAuthorizeException e)
|
||||||
|
{
|
||||||
|
return AjaxResult.error("没有权限,请联系管理员授权");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 演示模式异常
|
* 演示模式异常
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,167 +0,0 @@
|
|||||||
package com.ruoyi.common.security.service;
|
|
||||||
|
|
||||||
import java.util.Collection;
|
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import org.springframework.util.CollectionUtils;
|
|
||||||
import org.springframework.util.PatternMatchUtils;
|
|
||||||
import org.springframework.util.StringUtils;
|
|
||||||
import com.ruoyi.common.security.domain.LoginUser;
|
|
||||||
import com.ruoyi.common.security.utils.SecurityUtils;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 自定义权限实现
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
@Service("ss")
|
|
||||||
public class PermissionService
|
|
||||||
{
|
|
||||||
/** 所有权限标识 */
|
|
||||||
private static final String ALL_PERMISSION = "*:*:*";
|
|
||||||
|
|
||||||
/** 管理员角色权限标识 */
|
|
||||||
private static final String SUPER_ADMIN = "admin";
|
|
||||||
|
|
||||||
private static final String ROLE_DELIMETER = ",";
|
|
||||||
|
|
||||||
private static final String PERMISSION_DELIMETER = ",";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证用户是否具备某权限
|
|
||||||
*
|
|
||||||
* @param permission 权限字符串
|
|
||||||
* @return 用户是否具备某权限
|
|
||||||
*/
|
|
||||||
public boolean hasPermi(String permission)
|
|
||||||
{
|
|
||||||
if (StringUtils.isEmpty(permission))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
LoginUser loginUser = SecurityUtils.getLoginUser();
|
|
||||||
if (StringUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getAuthorities()))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return hasPermissions(loginUser.getAuthorities(), permission);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证用户是否不具备某权限,与 hasPermi逻辑相反
|
|
||||||
*
|
|
||||||
* @param permission 权限字符串
|
|
||||||
* @return 用户是否不具备某权限
|
|
||||||
*/
|
|
||||||
public boolean lacksPermi(String permission)
|
|
||||||
{
|
|
||||||
return hasPermi(permission) != true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证用户是否具有以下任意一个权限
|
|
||||||
*
|
|
||||||
* @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表
|
|
||||||
* @return 用户是否具有以下任意一个权限
|
|
||||||
*/
|
|
||||||
public boolean hasAnyPermi(String permissions)
|
|
||||||
{
|
|
||||||
if (StringUtils.isEmpty(permissions))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
LoginUser loginUser = SecurityUtils.getLoginUser();
|
|
||||||
if (StringUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getAuthorities()))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
Collection<? extends GrantedAuthority> authorities = loginUser.getAuthorities();
|
|
||||||
for (String permission : permissions.split(PERMISSION_DELIMETER))
|
|
||||||
{
|
|
||||||
if (permission != null && hasPermissions(authorities, permission))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 判断用户是否拥有某个角色
|
|
||||||
*
|
|
||||||
* @param role 角色字符串
|
|
||||||
* @return 用户是否具备某角色
|
|
||||||
*/
|
|
||||||
public boolean hasRole(String role)
|
|
||||||
{
|
|
||||||
if (StringUtils.isEmpty(role))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
LoginUser loginUser = SecurityUtils.getLoginUser();
|
|
||||||
if (StringUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getAuthorities()))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
for (GrantedAuthority authorities : loginUser.getAuthorities())
|
|
||||||
{
|
|
||||||
String roleKey = authorities.getAuthority();
|
|
||||||
if (SUPER_ADMIN.contains(roleKey) || roleKey.contains(role))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证用户是否不具备某角色,与 isRole逻辑相反。
|
|
||||||
*
|
|
||||||
* @param role 角色名称
|
|
||||||
* @return 用户是否不具备某角色
|
|
||||||
*/
|
|
||||||
public boolean lacksRole(String role)
|
|
||||||
{
|
|
||||||
return hasRole(role) != true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证用户是否具有以下任意一个角色
|
|
||||||
*
|
|
||||||
* @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表
|
|
||||||
* @return 用户是否具有以下任意一个角色
|
|
||||||
*/
|
|
||||||
public boolean hasAnyRoles(String roles)
|
|
||||||
{
|
|
||||||
if (StringUtils.isEmpty(roles))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
LoginUser loginUser = SecurityUtils.getLoginUser();
|
|
||||||
if (StringUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getAuthorities()))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
for (String role : roles.split(ROLE_DELIMETER))
|
|
||||||
{
|
|
||||||
if (hasRole(role))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 判断是否包含权限
|
|
||||||
*
|
|
||||||
* @param authorities 权限列表
|
|
||||||
* @param permission 权限字符串
|
|
||||||
* @return 用户是否具备某权限
|
|
||||||
*/
|
|
||||||
private boolean hasPermissions(Collection<? extends GrantedAuthority> authorities, String permission)
|
|
||||||
{
|
|
||||||
return authorities.stream().map(GrantedAuthority::getAuthority).filter(StringUtils::hasText)
|
|
||||||
.anyMatch(x -> ALL_PERMISSION.contains(x) || PatternMatchUtils.simpleMatch(permission, x));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
package com.ruoyi.common.security.service;
|
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
|
||||||
import org.springframework.cache.annotation.Cacheable;
|
|
||||||
import org.springframework.security.oauth2.provider.ClientDetails;
|
|
||||||
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
|
|
||||||
import com.ruoyi.common.core.constant.CacheConstants;
|
|
||||||
import com.ruoyi.common.core.constant.SecurityConstants;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 重写原生方法支持redis缓存
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
public class RedisClientDetailsService extends JdbcClientDetailsService
|
|
||||||
{
|
|
||||||
public RedisClientDetailsService(DataSource dataSource)
|
|
||||||
{
|
|
||||||
super(dataSource);
|
|
||||||
super.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
|
|
||||||
super.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
@Cacheable(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#clientId", unless = "#result == null")
|
|
||||||
public ClientDetails loadClientByClientId(String clientId)
|
|
||||||
{
|
|
||||||
return super.loadClientByClientId(clientId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
package com.ruoyi.common.security.service;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import com.ruoyi.common.core.constant.CacheConstants;
|
||||||
|
import com.ruoyi.common.core.constant.Constants;
|
||||||
|
import com.ruoyi.common.core.utils.IdUtils;
|
||||||
|
import com.ruoyi.common.core.utils.ServletUtils;
|
||||||
|
import com.ruoyi.common.core.utils.StringUtils;
|
||||||
|
import com.ruoyi.common.core.utils.ip.IpUtils;
|
||||||
|
import com.ruoyi.common.redis.service.RedisService;
|
||||||
|
import com.ruoyi.system.api.model.LoginUser;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* token验证处理
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class TokenService
|
||||||
|
{
|
||||||
|
@Autowired
|
||||||
|
private RedisService redisService;
|
||||||
|
|
||||||
|
private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;
|
||||||
|
|
||||||
|
private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;
|
||||||
|
|
||||||
|
protected static final long MILLIS_SECOND = 1000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建令牌
|
||||||
|
*/
|
||||||
|
public Map<String, Object> createToken(LoginUser loginUser)
|
||||||
|
{
|
||||||
|
// 生成token
|
||||||
|
String token = IdUtils.fastUUID();
|
||||||
|
loginUser.setToken(token);
|
||||||
|
loginUser.setUserid(loginUser.getSysUser().getUserId());
|
||||||
|
loginUser.setUsername(loginUser.getSysUser().getUserName());
|
||||||
|
loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
|
||||||
|
refreshToken(loginUser);
|
||||||
|
|
||||||
|
// 保存或更新用户token
|
||||||
|
Map<String, Object> map = new HashMap<String, Object>();
|
||||||
|
map.put("access_token", token);
|
||||||
|
map.put("expires_in", EXPIRE_TIME);
|
||||||
|
redisService.setCacheObject(ACCESS_TOKEN + token, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取用户身份信息
|
||||||
|
*
|
||||||
|
* @return 用户信息
|
||||||
|
*/
|
||||||
|
public LoginUser getLoginUser()
|
||||||
|
{
|
||||||
|
return getLoginUser(ServletUtils.getRequest());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取用户身份信息
|
||||||
|
*
|
||||||
|
* @return 用户信息
|
||||||
|
*/
|
||||||
|
public LoginUser getLoginUser(HttpServletRequest request)
|
||||||
|
{
|
||||||
|
// 获取请求携带的令牌
|
||||||
|
String token = getToken(request);
|
||||||
|
if (StringUtils.isNotEmpty(token))
|
||||||
|
{
|
||||||
|
String userKey = getTokenKey(token);
|
||||||
|
LoginUser user = redisService.getCacheObject(userKey);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置用户身份信息
|
||||||
|
*/
|
||||||
|
public void setLoginUser(LoginUser loginUser)
|
||||||
|
{
|
||||||
|
if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
|
||||||
|
{
|
||||||
|
refreshToken(loginUser);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delLoginUser(String token)
|
||||||
|
{
|
||||||
|
if (StringUtils.isNotEmpty(token))
|
||||||
|
{
|
||||||
|
String userKey = getTokenKey(token);
|
||||||
|
redisService.deleteObject(userKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 刷新令牌有效期
|
||||||
|
*
|
||||||
|
* @param loginUser 登录信息
|
||||||
|
*/
|
||||||
|
public void refreshToken(LoginUser loginUser)
|
||||||
|
{
|
||||||
|
loginUser.setLoginTime(System.currentTimeMillis());
|
||||||
|
loginUser.setExpireTime(loginUser.getLoginTime() + EXPIRE_TIME * MILLIS_SECOND);
|
||||||
|
// 根据uuid将loginUser缓存
|
||||||
|
String userKey = getTokenKey(loginUser.getToken());
|
||||||
|
redisService.setCacheObject(userKey, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getTokenKey(String token)
|
||||||
|
{
|
||||||
|
return ACCESS_TOKEN + token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取请求token
|
||||||
|
*/
|
||||||
|
private String getToken(HttpServletRequest request)
|
||||||
|
{
|
||||||
|
String token = request.getHeader(CacheConstants.HEADER);
|
||||||
|
if (StringUtils.isNotEmpty(token) && token.startsWith(CacheConstants.TOKEN_PREFIX))
|
||||||
|
{
|
||||||
|
token = token.replace(CacheConstants.TOKEN_PREFIX, "");
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
package com.ruoyi.common.security.service;
|
|
||||||
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Set;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
|
||||||
import org.springframework.security.core.authority.AuthorityUtils;
|
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
|
||||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
import com.ruoyi.common.core.domain.R;
|
|
||||||
import com.ruoyi.common.core.enums.UserStatus;
|
|
||||||
import com.ruoyi.common.core.exception.BaseException;
|
|
||||||
import com.ruoyi.common.core.utils.StringUtils;
|
|
||||||
import com.ruoyi.common.security.domain.LoginUser;
|
|
||||||
import com.ruoyi.system.api.RemoteUserService;
|
|
||||||
import com.ruoyi.system.api.domain.SysUser;
|
|
||||||
import com.ruoyi.system.api.model.UserInfo;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 用户信息处理
|
|
||||||
*
|
|
||||||
* @author ruoyi
|
|
||||||
*/
|
|
||||||
@Service
|
|
||||||
public class UserDetailsServiceImpl implements UserDetailsService
|
|
||||||
{
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private RemoteUserService remoteUserService;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public UserDetails loadUserByUsername(String username)
|
|
||||||
{
|
|
||||||
R<UserInfo> userResult = remoteUserService.getUserInfo(username);
|
|
||||||
checkUser(userResult, username);
|
|
||||||
return getUserDetails(userResult);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void checkUser(R<UserInfo> userResult, String username)
|
|
||||||
{
|
|
||||||
if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
|
|
||||||
{
|
|
||||||
log.info("登录用户:{} 不存在.", username);
|
|
||||||
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
|
|
||||||
}
|
|
||||||
else if (UserStatus.DELETED.getCode().equals(userResult.getData().getSysUser().getDelFlag()))
|
|
||||||
{
|
|
||||||
log.info("登录用户:{} 已被删除.", username);
|
|
||||||
throw new BaseException("对不起,您的账号:" + username + " 已被删除");
|
|
||||||
}
|
|
||||||
else if (UserStatus.DISABLE.getCode().equals(userResult.getData().getSysUser().getStatus()))
|
|
||||||
{
|
|
||||||
log.info("登录用户:{} 已被停用.", username);
|
|
||||||
throw new BaseException("对不起,您的账号:" + username + " 已停用");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private UserDetails getUserDetails(R<UserInfo> result)
|
|
||||||
{
|
|
||||||
UserInfo info = result.getData();
|
|
||||||
Set<String> dbAuthsSet = new HashSet<String>();
|
|
||||||
if (StringUtils.isNotEmpty(info.getRoles()))
|
|
||||||
{
|
|
||||||
// 获取角色
|
|
||||||
dbAuthsSet.addAll(info.getRoles());
|
|
||||||
// 获取权限
|
|
||||||
dbAuthsSet.addAll(info.getPermissions());
|
|
||||||
}
|
|
||||||
|
|
||||||
Collection<? extends GrantedAuthority> authorities = AuthorityUtils
|
|
||||||
.createAuthorityList(dbAuthsSet.toArray(new String[0]));
|
|
||||||
SysUser user = info.getSysUser();
|
|
||||||
|
|
||||||
return new LoginUser(user.getUserId(), user.getUserName(), user.getPassword(), true, true, true, true,
|
|
||||||
authorities);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
package com.ruoyi.common.security.utils;
|
package com.ruoyi.common.security.utils;
|
||||||
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
|
||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
import com.ruoyi.common.security.domain.LoginUser;
|
import com.ruoyi.common.core.constant.CacheConstants;
|
||||||
|
import com.ruoyi.common.core.text.Convert;
|
||||||
|
import com.ruoyi.common.core.utils.ServletUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 权限获取工具类
|
* 权限获取工具类
|
||||||
@@ -12,46 +12,31 @@ import com.ruoyi.common.security.domain.LoginUser;
|
|||||||
*/
|
*/
|
||||||
public class SecurityUtils
|
public class SecurityUtils
|
||||||
{
|
{
|
||||||
/**
|
|
||||||
* 获取Authentication
|
|
||||||
*/
|
|
||||||
public static Authentication getAuthentication()
|
|
||||||
{
|
|
||||||
return SecurityContextHolder.getContext().getAuthentication();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取用户
|
* 获取用户
|
||||||
*/
|
*/
|
||||||
public static String getUsername()
|
public static String getUsername()
|
||||||
{
|
{
|
||||||
return getLoginUser().getUsername();
|
return ServletUtils.getRequest().getHeader(CacheConstants.DETAILS_USERNAME);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取用户
|
* 获取用户ID
|
||||||
*/
|
*/
|
||||||
public static LoginUser getLoginUser(Authentication authentication)
|
public static Long getUserId()
|
||||||
{
|
{
|
||||||
Object principal = authentication.getPrincipal();
|
return Convert.toLong(ServletUtils.getRequest().getHeader(CacheConstants.DETAILS_USER_ID));
|
||||||
if (principal instanceof LoginUser)
|
|
||||||
{
|
|
||||||
return (LoginUser) principal;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取用户
|
* 是否为管理员
|
||||||
|
*
|
||||||
|
* @param userId 用户ID
|
||||||
|
* @return 结果
|
||||||
*/
|
*/
|
||||||
public static LoginUser getLoginUser()
|
public static boolean isAdmin(Long userId)
|
||||||
{
|
{
|
||||||
Authentication authentication = getAuthentication();
|
return userId != null && 1L == userId;
|
||||||
if (authentication == null)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return getLoginUser(authentication);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -78,15 +63,4 @@ public class SecurityUtils
|
|||||||
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
||||||
return passwordEncoder.matches(rawPassword, encodedPassword);
|
return passwordEncoder.matches(rawPassword, encodedPassword);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 是否为管理员
|
|
||||||
*
|
|
||||||
* @param userId 用户ID
|
|
||||||
* @return 结果
|
|
||||||
*/
|
|
||||||
public static boolean isAdmin(Long userId)
|
|
||||||
{
|
|
||||||
return userId != null && 1L == userId;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,4 @@
|
|||||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||||
com.ruoyi.common.security.service.UserDetailsServiceImpl,\
|
com.ruoyi.common.security.service.TokenService,\
|
||||||
com.ruoyi.common.security.service.PermissionService,\
|
com.ruoyi.common.security.aspect.PreAuthorizeAspect,\
|
||||||
com.ruoyi.common.security.config.MethodSecurityConfig,\
|
|
||||||
com.ruoyi.common.security.handler.CustomAccessDeniedHandler,\
|
|
||||||
com.ruoyi.common.security.handler.GlobalExceptionHandler
|
com.ruoyi.common.security.handler.GlobalExceptionHandler
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi-common</artifactId>
|
<artifactId>ruoyi-common</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package com.ruoyi.common.swagger.config;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
@@ -15,11 +14,9 @@ import springfox.documentation.builders.ApiInfoBuilder;
|
|||||||
import springfox.documentation.builders.PathSelectors;
|
import springfox.documentation.builders.PathSelectors;
|
||||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||||
import springfox.documentation.service.ApiInfo;
|
import springfox.documentation.service.ApiInfo;
|
||||||
|
import springfox.documentation.service.ApiKey;
|
||||||
import springfox.documentation.service.AuthorizationScope;
|
import springfox.documentation.service.AuthorizationScope;
|
||||||
import springfox.documentation.service.Contact;
|
import springfox.documentation.service.Contact;
|
||||||
import springfox.documentation.service.GrantType;
|
|
||||||
import springfox.documentation.service.OAuth;
|
|
||||||
import springfox.documentation.service.ResourceOwnerPasswordCredentialsGrant;
|
|
||||||
import springfox.documentation.service.SecurityReference;
|
import springfox.documentation.service.SecurityReference;
|
||||||
import springfox.documentation.spi.DocumentationType;
|
import springfox.documentation.spi.DocumentationType;
|
||||||
import springfox.documentation.spi.service.contexts.SecurityContext;
|
import springfox.documentation.spi.service.contexts.SecurityContext;
|
||||||
@@ -66,54 +63,55 @@ public class SwaggerAutoConfiguration
|
|||||||
List<Predicate<String>> excludePath = new ArrayList<>();
|
List<Predicate<String>> excludePath = new ArrayList<>();
|
||||||
swaggerProperties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path)));
|
swaggerProperties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path)));
|
||||||
|
|
||||||
//noinspection Guava
|
//noinspection Guava
|
||||||
return new Docket(DocumentationType.SWAGGER_2)
|
return new Docket(DocumentationType.SWAGGER_2)
|
||||||
.host(swaggerProperties.getHost())
|
.host(swaggerProperties.getHost())
|
||||||
.apiInfo(apiInfo(swaggerProperties)).select()
|
.apiInfo(apiInfo(swaggerProperties)).select()
|
||||||
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
|
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
|
||||||
.paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
|
.paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
|
||||||
.build()
|
.build()
|
||||||
.securitySchemes(Collections.singletonList(securitySchema()))
|
.securitySchemes(securitySchemes())
|
||||||
.securityContexts(Collections.singletonList(securityContext()))
|
.securityContexts(securityContexts())
|
||||||
.pathMapping("/");
|
.pathMapping("/");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 配置默认的全局鉴权策略的开关,通过正则表达式进行匹配;默认匹配所有URL
|
* 安全模式,这里指定token通过Authorization头请求头传递
|
||||||
*
|
*/
|
||||||
* @return
|
private List<ApiKey> securitySchemes()
|
||||||
*/
|
|
||||||
private SecurityContext securityContext()
|
|
||||||
{
|
{
|
||||||
return SecurityContext.builder()
|
List<ApiKey> apiKeyList = new ArrayList<ApiKey>();
|
||||||
.securityReferences(defaultAuth())
|
apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
|
||||||
.forPaths(PathSelectors.regex(swaggerProperties().getAuthorization().getAuthRegex()))
|
return apiKeyList;
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 默认的全局鉴权策略
|
* 安全上下文
|
||||||
*
|
*/
|
||||||
* @return
|
private List<SecurityContext> securityContexts()
|
||||||
*/
|
{
|
||||||
|
List<SecurityContext> securityContexts = new ArrayList<>();
|
||||||
|
securityContexts.add(
|
||||||
|
SecurityContext.builder()
|
||||||
|
.securityReferences(defaultAuth())
|
||||||
|
.forPaths(PathSelectors.regex("^(?!auth).*$"))
|
||||||
|
.build());
|
||||||
|
return securityContexts;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 默认的全局鉴权策略
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
private List<SecurityReference> defaultAuth()
|
private List<SecurityReference> defaultAuth()
|
||||||
{
|
{
|
||||||
ArrayList<AuthorizationScope> authorizationScopeList = new ArrayList<>();
|
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
|
||||||
swaggerProperties().getAuthorization().getAuthorizationScopeList().forEach(authorizationScope -> authorizationScopeList.add(new AuthorizationScope(authorizationScope.getScope(), authorizationScope.getDescription())));
|
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
|
||||||
AuthorizationScope[] authorizationScopes = new AuthorizationScope[authorizationScopeList.size()];
|
authorizationScopes[0] = authorizationScope;
|
||||||
return Collections.singletonList(SecurityReference.builder()
|
List<SecurityReference> securityReferences = new ArrayList<>();
|
||||||
.reference(swaggerProperties().getAuthorization().getName())
|
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
|
||||||
.scopes(authorizationScopeList.toArray(authorizationScopes))
|
return securityReferences;
|
||||||
.build());
|
|
||||||
}
|
|
||||||
|
|
||||||
private OAuth securitySchema()
|
|
||||||
{
|
|
||||||
ArrayList<AuthorizationScope> authorizationScopeList = new ArrayList<>();
|
|
||||||
swaggerProperties().getAuthorization().getAuthorizationScopeList().forEach(authorizationScope -> authorizationScopeList.add(new AuthorizationScope(authorizationScope.getScope(), authorizationScope.getDescription())));
|
|
||||||
ArrayList<GrantType> grantTypes = new ArrayList<>();
|
|
||||||
swaggerProperties().getAuthorization().getTokenUrlList().forEach(tokenUrl -> grantTypes.add(new ResourceOwnerPasswordCredentialsGrant(tokenUrl)));
|
|
||||||
return new OAuth(swaggerProperties().getAuthorization().getName(), authorizationScopeList, grantTypes);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private ApiInfo apiInfo(SwaggerProperties swaggerProperties)
|
private ApiInfo apiInfo(SwaggerProperties swaggerProperties)
|
||||||
@@ -128,5 +126,4 @@ public class SwaggerAutoConfiguration
|
|||||||
.version(swaggerProperties.getVersion())
|
.version(swaggerProperties.getVersion())
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi</artifactId>
|
<artifactId>ruoyi</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.ruoyi.gateway.config.properties;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 放行白名单配置
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
@RefreshScope
|
||||||
|
@ConfigurationProperties(prefix = "ignore")
|
||||||
|
public class IgnoreWhiteProperties
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 放行白名单配置,网关不校验此处的白名单
|
||||||
|
*/
|
||||||
|
private List<String> whites = new ArrayList<>();
|
||||||
|
|
||||||
|
public List<String> getWhites()
|
||||||
|
{
|
||||||
|
return whites;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setWhites(List<String> whites)
|
||||||
|
{
|
||||||
|
this.whites = whites;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
package com.ruoyi.gateway.filter;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
|
||||||
|
import org.springframework.cloud.gateway.filter.GlobalFilter;
|
||||||
|
import org.springframework.core.Ordered;
|
||||||
|
import org.springframework.core.io.buffer.DataBufferFactory;
|
||||||
|
import org.springframework.data.redis.core.ValueOperations;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.server.reactive.ServerHttpRequest;
|
||||||
|
import org.springframework.http.server.reactive.ServerHttpResponse;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.server.ServerWebExchange;
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import com.ruoyi.common.core.constant.CacheConstants;
|
||||||
|
import com.ruoyi.common.core.constant.Constants;
|
||||||
|
import com.ruoyi.common.core.domain.R;
|
||||||
|
import com.ruoyi.common.core.utils.StringUtils;
|
||||||
|
import com.ruoyi.common.redis.service.RedisService;
|
||||||
|
import com.ruoyi.gateway.config.properties.IgnoreWhiteProperties;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网关鉴权
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class AuthFilter implements GlobalFilter, Ordered
|
||||||
|
{
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);
|
||||||
|
|
||||||
|
private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;
|
||||||
|
|
||||||
|
// 排除过滤的 uri 地址,nacos自行添加
|
||||||
|
@Autowired
|
||||||
|
private IgnoreWhiteProperties ignoreWhite;
|
||||||
|
|
||||||
|
@Resource(name = "stringRedisTemplate")
|
||||||
|
private ValueOperations<String, String> sops;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private RedisService redisService;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
|
||||||
|
{
|
||||||
|
String url = exchange.getRequest().getURI().getPath();
|
||||||
|
// 跳过不需要验证的路径
|
||||||
|
if (StringUtils.matches(url, ignoreWhite.getWhites()))
|
||||||
|
{
|
||||||
|
return chain.filter(exchange);
|
||||||
|
}
|
||||||
|
String token = getToken(exchange.getRequest());
|
||||||
|
if (StringUtils.isBlank(token))
|
||||||
|
{
|
||||||
|
return setUnauthorizedResponse(exchange, "令牌不能为空");
|
||||||
|
}
|
||||||
|
String userStr = sops.get(getTokenKey(token));
|
||||||
|
if (StringUtils.isNull(userStr))
|
||||||
|
{
|
||||||
|
return setUnauthorizedResponse(exchange, "登录状态已过期");
|
||||||
|
}
|
||||||
|
JSONObject obj = JSONObject.parseObject(userStr);
|
||||||
|
String userid = obj.getString("userid");
|
||||||
|
String username = obj.getString("username");
|
||||||
|
if (StringUtils.isBlank(userid) || StringUtils.isBlank(username))
|
||||||
|
{
|
||||||
|
return setUnauthorizedResponse(exchange, "令牌验证失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置过期时间
|
||||||
|
redisService.expire(getTokenKey(token), EXPIRE_TIME);
|
||||||
|
// 设置用户信息到请求
|
||||||
|
ServerHttpRequest mutableReq = exchange.getRequest().mutate().header(CacheConstants.DETAILS_USER_ID, userid)
|
||||||
|
.header(CacheConstants.DETAILS_USERNAME, username).build();
|
||||||
|
ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
|
||||||
|
|
||||||
|
return chain.filter(mutableExchange);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Void> setUnauthorizedResponse(ServerWebExchange exchange, String msg)
|
||||||
|
{
|
||||||
|
ServerHttpResponse response = exchange.getResponse();
|
||||||
|
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
response.setStatusCode(HttpStatus.OK);
|
||||||
|
|
||||||
|
log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
|
||||||
|
|
||||||
|
return response.writeWith(Mono.fromSupplier(() -> {
|
||||||
|
DataBufferFactory bufferFactory = response.bufferFactory();
|
||||||
|
return bufferFactory.wrap(JSON.toJSONBytes(R.fail(msg)));
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getTokenKey(String token)
|
||||||
|
{
|
||||||
|
return CacheConstants.LOGIN_TOKEN_KEY + token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取请求token
|
||||||
|
*/
|
||||||
|
private String getToken(ServerHttpRequest request)
|
||||||
|
{
|
||||||
|
String token = request.getHeaders().getFirst(CacheConstants.HEADER);
|
||||||
|
if (StringUtils.isNotEmpty(token) && token.startsWith(CacheConstants.TOKEN_PREFIX))
|
||||||
|
{
|
||||||
|
token = token.replace(CacheConstants.TOKEN_PREFIX, "");
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getOrder()
|
||||||
|
{
|
||||||
|
return -200;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package com.ruoyi.gateway.filter;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
||||||
|
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
|
||||||
|
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
|
||||||
|
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
|
||||||
|
import org.springframework.core.io.buffer.DataBuffer;
|
||||||
|
import org.springframework.core.io.buffer.DataBufferFactory;
|
||||||
|
import org.springframework.core.io.buffer.DataBufferUtils;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.server.ServerWebExchange;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class CacheRequestFilter extends AbstractGatewayFilterFactory<CacheRequestFilter.Config>
|
||||||
|
{
|
||||||
|
public CacheRequestFilter()
|
||||||
|
{
|
||||||
|
super(Config.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String name()
|
||||||
|
{
|
||||||
|
return "CacheRequestFilter";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public GatewayFilter apply(Config config)
|
||||||
|
{
|
||||||
|
CacheRequestGatewayFilter cacheRequestGatewayFilter = new CacheRequestGatewayFilter();
|
||||||
|
Integer order = config.getOrder();
|
||||||
|
if (order == null)
|
||||||
|
{
|
||||||
|
return cacheRequestGatewayFilter;
|
||||||
|
}
|
||||||
|
return new OrderedGatewayFilter(cacheRequestGatewayFilter, order);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class CacheRequestGatewayFilter implements GatewayFilter
|
||||||
|
{
|
||||||
|
@Override
|
||||||
|
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
|
||||||
|
{
|
||||||
|
// GET DELETE 不过滤
|
||||||
|
HttpMethod method = exchange.getRequest().getMethod();
|
||||||
|
if (method == null || method.matches("GET") || method.matches("DELETE"))
|
||||||
|
{
|
||||||
|
return chain.filter(exchange);
|
||||||
|
}
|
||||||
|
return DataBufferUtils.join(exchange.getRequest().getBody()).map(dataBuffer -> {
|
||||||
|
byte[] bytes = new byte[dataBuffer.readableByteCount()];
|
||||||
|
dataBuffer.read(bytes);
|
||||||
|
DataBufferUtils.release(dataBuffer);
|
||||||
|
return bytes;
|
||||||
|
}).defaultIfEmpty(new byte[0]).flatMap(bytes -> {
|
||||||
|
DataBufferFactory dataBufferFactory = exchange.getResponse().bufferFactory();
|
||||||
|
ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(exchange.getRequest())
|
||||||
|
{
|
||||||
|
@Override
|
||||||
|
public Flux<DataBuffer> getBody()
|
||||||
|
{
|
||||||
|
if (bytes.length > 0)
|
||||||
|
{
|
||||||
|
return Flux.just(dataBufferFactory.wrap(bytes));
|
||||||
|
}
|
||||||
|
return Flux.empty();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return chain.filter(exchange.mutate().request(decorator).build());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> shortcutFieldOrder()
|
||||||
|
{
|
||||||
|
return Collections.singletonList("order");
|
||||||
|
}
|
||||||
|
|
||||||
|
static class Config
|
||||||
|
{
|
||||||
|
private Integer order;
|
||||||
|
|
||||||
|
public Integer getOrder()
|
||||||
|
{
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setOrder(Integer order)
|
||||||
|
{
|
||||||
|
this.order = order;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,16 +1,22 @@
|
|||||||
package com.ruoyi.gateway.filter;
|
package com.ruoyi.gateway.filter;
|
||||||
|
|
||||||
|
import java.nio.CharBuffer;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
||||||
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
|
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.core.io.buffer.DataBuffer;
|
||||||
|
import org.springframework.core.io.buffer.DataBufferUtils;
|
||||||
import org.springframework.http.server.reactive.ServerHttpRequest;
|
import org.springframework.http.server.reactive.ServerHttpRequest;
|
||||||
import org.springframework.http.server.reactive.ServerHttpResponse;
|
import org.springframework.http.server.reactive.ServerHttpResponse;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import com.alibaba.fastjson.JSON;
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
import com.ruoyi.common.core.utils.StringUtils;
|
import com.ruoyi.common.core.utils.StringUtils;
|
||||||
import com.ruoyi.common.core.web.domain.AjaxResult;
|
import com.ruoyi.common.core.web.domain.AjaxResult;
|
||||||
import com.ruoyi.gateway.service.ValidateCodeService;
|
import com.ruoyi.gateway.service.ValidateCodeService;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -21,20 +27,14 @@ import reactor.core.publisher.Mono;
|
|||||||
@Component
|
@Component
|
||||||
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
|
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
|
||||||
{
|
{
|
||||||
private final static String AUTH_URL = "/oauth/token";
|
private final static String AUTH_URL = "/auth/login";
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ValidateCodeService validateCodeService;
|
private ValidateCodeService validateCodeService;
|
||||||
|
|
||||||
private static final String BASIC_ = "Basic ";
|
|
||||||
|
|
||||||
private static final String CODE = "code";
|
private static final String CODE = "code";
|
||||||
|
|
||||||
private static final String UUID = "uuid";
|
private static final String UUID = "uuid";
|
||||||
|
|
||||||
private static final String GRANT_TYPE = "grant_type";
|
|
||||||
|
|
||||||
private static final String REFRESH_TOKEN = "refresh_token";
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public GatewayFilter apply(Object config)
|
public GatewayFilter apply(Object config)
|
||||||
@@ -47,25 +47,12 @@ public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
|
|||||||
{
|
{
|
||||||
return chain.filter(exchange);
|
return chain.filter(exchange);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 刷新token请求,不处理
|
|
||||||
String grantType = request.getQueryParams().getFirst(GRANT_TYPE);
|
|
||||||
if (StringUtils.containsIgnoreCase(request.getURI().getPath(), AUTH_URL) && StringUtils.containsIgnoreCase(grantType, REFRESH_TOKEN))
|
|
||||||
{
|
|
||||||
return chain.filter(exchange);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 消息头存在内容,且不存在验证码参数,不处理
|
|
||||||
String header = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
|
|
||||||
if (StringUtils.isNotEmpty(header) && StringUtils.startsWith(header, BASIC_)
|
|
||||||
&& !request.getQueryParams().containsKey(CODE) && !request.getQueryParams().containsKey(UUID))
|
|
||||||
{
|
|
||||||
return chain.filter(exchange);
|
|
||||||
}
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
validateCodeService.checkCapcha(request.getQueryParams().getFirst(CODE),
|
String rspStr = resolveBodyFromRequest(request);
|
||||||
request.getQueryParams().getFirst(UUID));
|
JSONObject obj = JSONObject.parseObject(rspStr);
|
||||||
|
validateCodeService.checkCapcha(obj.getString(CODE), obj.getString(UUID));
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
@@ -77,4 +64,17 @@ public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
|
|||||||
return chain.filter(exchange);
|
return chain.filter(exchange);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest)
|
||||||
|
{
|
||||||
|
// 获取请求体
|
||||||
|
Flux<DataBuffer> body = serverHttpRequest.getBody();
|
||||||
|
AtomicReference<String> bodyRef = new AtomicReference<>();
|
||||||
|
body.subscribe(buffer -> {
|
||||||
|
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
|
||||||
|
DataBufferUtils.release(buffer);
|
||||||
|
bodyRef.set(charBuffer.toString());
|
||||||
|
});
|
||||||
|
return bodyRef.get();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
74
ruoyi-gateway/src/main/resources/logback.xml
Normal file
74
ruoyi-gateway/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration scan="true" scanPeriod="60 seconds" debug="false">
|
||||||
|
<!-- 日志存放路径 -->
|
||||||
|
<property name="log.path" value="logs/ruoyi-gateway" />
|
||||||
|
<!-- 日志输出格式 -->
|
||||||
|
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
|
||||||
|
|
||||||
|
<!-- 控制台输出 -->
|
||||||
|
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>${log.pattern}</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<!-- 系统日志输出 -->
|
||||||
|
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||||
|
<file>${log.path}/info.log</file>
|
||||||
|
<!-- 循环政策:基于时间创建日志文件 -->
|
||||||
|
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||||
|
<!-- 日志文件名格式 -->
|
||||||
|
<fileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||||
|
<!-- 日志最大的历史 60天 -->
|
||||||
|
<maxHistory>60</maxHistory>
|
||||||
|
</rollingPolicy>
|
||||||
|
<encoder>
|
||||||
|
<pattern>${log.pattern}</pattern>
|
||||||
|
</encoder>
|
||||||
|
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||||
|
<!-- 过滤的级别 -->
|
||||||
|
<level>INFO</level>
|
||||||
|
<!-- 匹配时的操作:接收(记录) -->
|
||||||
|
<onMatch>ACCEPT</onMatch>
|
||||||
|
<!-- 不匹配时的操作:拒绝(不记录) -->
|
||||||
|
<onMismatch>DENY</onMismatch>
|
||||||
|
</filter>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||||
|
<file>${log.path}/error.log</file>
|
||||||
|
<!-- 循环政策:基于时间创建日志文件 -->
|
||||||
|
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||||
|
<!-- 日志文件名格式 -->
|
||||||
|
<fileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||||
|
<!-- 日志最大的历史 60天 -->
|
||||||
|
<maxHistory>60</maxHistory>
|
||||||
|
</rollingPolicy>
|
||||||
|
<encoder>
|
||||||
|
<pattern>${log.pattern}</pattern>
|
||||||
|
</encoder>
|
||||||
|
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||||
|
<!-- 过滤的级别 -->
|
||||||
|
<level>ERROR</level>
|
||||||
|
<!-- 匹配时的操作:接收(记录) -->
|
||||||
|
<onMatch>ACCEPT</onMatch>
|
||||||
|
<!-- 不匹配时的操作:拒绝(不记录) -->
|
||||||
|
<onMismatch>DENY</onMismatch>
|
||||||
|
</filter>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<!-- 系统模块日志级别控制 -->
|
||||||
|
<logger name="com.ruoyi" level="info" />
|
||||||
|
<!-- Spring日志级别控制 -->
|
||||||
|
<logger name="org.springframework" level="warn" />
|
||||||
|
|
||||||
|
<root level="info">
|
||||||
|
<appender-ref ref="console" />
|
||||||
|
</root>
|
||||||
|
|
||||||
|
<!--系统操作日志-->
|
||||||
|
<root level="info">
|
||||||
|
<appender-ref ref="file_info" />
|
||||||
|
<appender-ref ref="file_error" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi</artifactId>
|
<artifactId>ruoyi</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
@@ -12,6 +12,7 @@
|
|||||||
<module>ruoyi-system</module>
|
<module>ruoyi-system</module>
|
||||||
<module>ruoyi-gen</module>
|
<module>ruoyi-gen</module>
|
||||||
<module>ruoyi-job</module>
|
<module>ruoyi-job</module>
|
||||||
|
<module>ruoyi-file</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<artifactId>ruoyi-modules</artifactId>
|
<artifactId>ruoyi-modules</artifactId>
|
||||||
|
|||||||
88
ruoyi-modules/ruoyi-file/pom.xml
Normal file
88
ruoyi-modules/ruoyi-file/pom.xml
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<parent>
|
||||||
|
<groupId>com.ruoyi</groupId>
|
||||||
|
<artifactId>ruoyi-modules</artifactId>
|
||||||
|
<version>2.3.0</version>
|
||||||
|
</parent>
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<artifactId>ruoyi-modules-file</artifactId>
|
||||||
|
|
||||||
|
<description>
|
||||||
|
ruoyi-modules-file文件服务
|
||||||
|
</description>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<!-- SpringCloud Ailibaba Nacos -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- SpringCloud Ailibaba Nacos Config -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- SpringCloud Ailibaba Sentinel -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- SpringBoot Actuator -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Swagger -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.springfox</groupId>
|
||||||
|
<artifactId>springfox-swagger-ui</artifactId>
|
||||||
|
<version>${swagger.fox.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- FastDFS -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.tobato</groupId>
|
||||||
|
<artifactId>fastdfs-client</artifactId>
|
||||||
|
<version>1.26.5</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Ruoyi Common Security -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.ruoyi</groupId>
|
||||||
|
<artifactId>ruoyi-common-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Ruoyi Common Swagger -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.ruoyi</groupId>
|
||||||
|
<artifactId>ruoyi-common-swagger</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>repackage</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.ruoyi.file;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||||
|
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||||
|
import com.ruoyi.common.security.annotation.EnableRyFeignClients;
|
||||||
|
import com.ruoyi.common.swagger.annotation.EnableCustomSwagger2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件服务
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@EnableCustomSwagger2
|
||||||
|
@EnableRyFeignClients
|
||||||
|
@EnableDiscoveryClient
|
||||||
|
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
|
||||||
|
public class RuoYFileApplication
|
||||||
|
{
|
||||||
|
public static void main(String[] args)
|
||||||
|
{
|
||||||
|
SpringApplication.run(RuoYFileApplication.class, args);
|
||||||
|
System.out.println("(♥◠‿◠)ノ゙ 文件服务模块启动成功 ლ(´ڡ`ლ)゙ \n" +
|
||||||
|
" .-------. ____ __ \n" +
|
||||||
|
" | _ _ \\ \\ \\ / / \n" +
|
||||||
|
" | ( ' ) | \\ _. / ' \n" +
|
||||||
|
" |(_ o _) / _( )_ .' \n" +
|
||||||
|
" | (_,_).' __ ___(_ o _)' \n" +
|
||||||
|
" | |\\ \\ | || |(_,_)' \n" +
|
||||||
|
" | | \\ `' /| `-' / \n" +
|
||||||
|
" | | \\ / \\ / \n" +
|
||||||
|
" ''-' `'-' `-..-' ");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.ruoyi.file.config;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通用映射配置
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
public class ResourcesConfig implements WebMvcConfigurer
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 上传文件存储在本地的根路径
|
||||||
|
*/
|
||||||
|
@Value("${file.path}")
|
||||||
|
private String localFilePath;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 资源映射路径 前缀
|
||||||
|
*/
|
||||||
|
@Value("${file.prefix}")
|
||||||
|
public String localFilePrefix;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addResourceHandlers(ResourceHandlerRegistry registry)
|
||||||
|
{
|
||||||
|
/** 本地文件上传路径 */
|
||||||
|
registry.addResourceHandler(localFilePrefix + "/**")
|
||||||
|
.addResourceLocations("file:" + localFilePath + File.separator);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.ruoyi.file.controller;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import com.ruoyi.common.core.domain.R;
|
||||||
|
import com.ruoyi.common.core.utils.file.FileUtils;
|
||||||
|
import com.ruoyi.file.service.ISysFileService;
|
||||||
|
import com.ruoyi.system.api.domain.SysFile;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件请求处理
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
public class SysFileController
|
||||||
|
{
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(SysFileController.class);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上传文件存储在本地的根路径
|
||||||
|
*/
|
||||||
|
@Value("${file.path}")
|
||||||
|
private String localFilePath;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ISysFileService sysFileService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件上传请求
|
||||||
|
*/
|
||||||
|
@PostMapping("upload")
|
||||||
|
public R<SysFile> upload(MultipartFile file)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 上传并返回访问地址
|
||||||
|
String url = sysFileService.uploadFile(file, localFilePath);
|
||||||
|
SysFile sysFile = new SysFile();
|
||||||
|
sysFile.setName(FileUtils.getName(url));
|
||||||
|
sysFile.setUrl(url);
|
||||||
|
return R.ok(sysFile);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
log.error("上传文件失败", e);
|
||||||
|
return R.fail(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.ruoyi.file.service;
|
||||||
|
|
||||||
|
import org.apache.commons.io.FilenameUtils;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
|
||||||
|
import com.github.tobato.fastdfs.service.FastFileStorageClient;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FastDFS文件存储
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class FastDfsSysFileServiceImpl implements ISysFileService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 域名或本机访问地址
|
||||||
|
*/
|
||||||
|
@Value("${fdfs.domain}")
|
||||||
|
public String domain;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private FastFileStorageClient storageClient;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FastDfs文件上传接口
|
||||||
|
*
|
||||||
|
* @param file 上传的文件
|
||||||
|
* @param baseDir 相对应用的基目录
|
||||||
|
* @return 访问地址
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public String uploadFile(MultipartFile file, String baseDir) throws Exception
|
||||||
|
{
|
||||||
|
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
|
||||||
|
FilenameUtils.getExtension(file.getOriginalFilename()), null);
|
||||||
|
return domain + "/" + storePath.getFullPath();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.ruoyi.file.service;
|
||||||
|
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件上传接口
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public interface ISysFileService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 文件上传接口
|
||||||
|
*
|
||||||
|
* @param file 上传的文件
|
||||||
|
* @param baseDir 相对应用的基目录
|
||||||
|
* @return 访问地址
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
public String uploadFile(MultipartFile file, String baseDir) throws Exception;
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.ruoyi.file.service;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.annotation.Primary;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import com.ruoyi.file.utils.FileUploadUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 本地文件存储
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
@Primary
|
||||||
|
@Service
|
||||||
|
public class LocalSysFileServiceImpl implements ISysFileService
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 资源映射路径 前缀
|
||||||
|
*/
|
||||||
|
@Value("${file.prefix}")
|
||||||
|
public String localFilePrefix;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 域名或本机访问地址
|
||||||
|
*/
|
||||||
|
@Value("${file.domain}")
|
||||||
|
public String domain;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 本地文件上传接口
|
||||||
|
*
|
||||||
|
* @param file 上传的文件
|
||||||
|
* @param baseDir 相对应用的基目录
|
||||||
|
* @return 访问地址
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
public String uploadFile(MultipartFile file, String baseDir) throws Exception
|
||||||
|
{
|
||||||
|
String name = FileUploadUtils.upload(baseDir, file);
|
||||||
|
String url = domain + localFilePrefix + name;
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
package com.ruoyi.file.utils;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import org.apache.commons.io.FilenameUtils;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
import com.ruoyi.common.core.exception.file.FileNameLengthLimitExceededException;
|
||||||
|
import com.ruoyi.common.core.exception.file.FileSizeLimitExceededException;
|
||||||
|
import com.ruoyi.common.core.exception.file.InvalidExtensionException;
|
||||||
|
import com.ruoyi.common.core.utils.DateUtils;
|
||||||
|
import com.ruoyi.common.core.utils.IdUtils;
|
||||||
|
import com.ruoyi.common.core.utils.StringUtils;
|
||||||
|
import com.ruoyi.common.core.utils.file.MimeTypeUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件上传工具类
|
||||||
|
*
|
||||||
|
* @author ruoyi
|
||||||
|
*/
|
||||||
|
public class FileUploadUtils
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 默认大小 50M
|
||||||
|
*/
|
||||||
|
public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 默认的文件名最大长度 100
|
||||||
|
*/
|
||||||
|
public static final int DEFAULT_FILE_NAME_LENGTH = 100;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 资源映射路径 前缀
|
||||||
|
*/
|
||||||
|
@Value("${file.prefix}")
|
||||||
|
public String localFilePrefix;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据文件路径上传
|
||||||
|
*
|
||||||
|
* @param baseDir 相对应用的基目录
|
||||||
|
* @param file 上传的文件
|
||||||
|
* @return 文件名称
|
||||||
|
* @throws IOException
|
||||||
|
*/
|
||||||
|
public static final String upload(String baseDir, MultipartFile file) throws IOException
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
throw new IOException(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件上传
|
||||||
|
*
|
||||||
|
* @param baseDir 相对应用的基目录
|
||||||
|
* @param file 上传的文件
|
||||||
|
* @param extension 上传文件类型
|
||||||
|
* @return 返回上传成功的文件名
|
||||||
|
* @throws FileSizeLimitExceededException 如果超出最大大小
|
||||||
|
* @throws FileNameLengthLimitExceededException 文件名太长
|
||||||
|
* @throws IOException 比如读写文件出错时
|
||||||
|
* @throws InvalidExtensionException 文件校验异常
|
||||||
|
*/
|
||||||
|
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
|
||||||
|
throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
|
||||||
|
InvalidExtensionException
|
||||||
|
{
|
||||||
|
int fileNamelength = file.getOriginalFilename().length();
|
||||||
|
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
|
||||||
|
{
|
||||||
|
throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertAllowed(file, allowedExtension);
|
||||||
|
|
||||||
|
String fileName = extractFilename(file);
|
||||||
|
|
||||||
|
File desc = getAbsoluteFile(baseDir, fileName);
|
||||||
|
file.transferTo(desc);
|
||||||
|
String pathFileName = getPathFileName(fileName);
|
||||||
|
return pathFileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 编码文件名
|
||||||
|
*/
|
||||||
|
public static final String extractFilename(MultipartFile file)
|
||||||
|
{
|
||||||
|
String fileName = file.getOriginalFilename();
|
||||||
|
String extension = getExtension(file);
|
||||||
|
fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
|
||||||
|
return fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
|
||||||
|
{
|
||||||
|
File desc = new File(uploadDir + File.separator + fileName);
|
||||||
|
|
||||||
|
if (!desc.exists())
|
||||||
|
{
|
||||||
|
if (!desc.getParentFile().exists())
|
||||||
|
{
|
||||||
|
desc.getParentFile().mkdirs();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final String getPathFileName(String fileName) throws IOException
|
||||||
|
{
|
||||||
|
String pathFileName = "/" + fileName;
|
||||||
|
return pathFileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件大小校验
|
||||||
|
*
|
||||||
|
* @param file 上传的文件
|
||||||
|
* @return
|
||||||
|
* @throws FileSizeLimitExceededException 如果超出最大大小
|
||||||
|
* @throws InvalidExtensionException
|
||||||
|
*/
|
||||||
|
public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
|
||||||
|
throws FileSizeLimitExceededException, InvalidExtensionException
|
||||||
|
{
|
||||||
|
long size = file.getSize();
|
||||||
|
if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE)
|
||||||
|
{
|
||||||
|
throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
|
||||||
|
}
|
||||||
|
|
||||||
|
String fileName = file.getOriginalFilename();
|
||||||
|
String extension = getExtension(file);
|
||||||
|
if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
|
||||||
|
{
|
||||||
|
if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
|
||||||
|
{
|
||||||
|
throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
|
||||||
|
fileName);
|
||||||
|
}
|
||||||
|
else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
|
||||||
|
{
|
||||||
|
throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
|
||||||
|
fileName);
|
||||||
|
}
|
||||||
|
else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
|
||||||
|
{
|
||||||
|
throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
|
||||||
|
fileName);
|
||||||
|
}
|
||||||
|
else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION)
|
||||||
|
{
|
||||||
|
throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
|
||||||
|
fileName);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new InvalidExtensionException(allowedExtension, extension, fileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断MIME类型是否是允许的MIME类型
|
||||||
|
*
|
||||||
|
* @param extension
|
||||||
|
* @param allowedExtension
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
|
||||||
|
{
|
||||||
|
for (String str : allowedExtension)
|
||||||
|
{
|
||||||
|
if (str.equalsIgnoreCase(extension))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取文件名的后缀
|
||||||
|
*
|
||||||
|
* @param file 表单文件
|
||||||
|
* @return 后缀名
|
||||||
|
*/
|
||||||
|
public static final String getExtension(MultipartFile file)
|
||||||
|
{
|
||||||
|
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
|
||||||
|
if (StringUtils.isEmpty(extension))
|
||||||
|
{
|
||||||
|
extension = MimeTypeUtils.getExtension(file.getContentType());
|
||||||
|
}
|
||||||
|
return extension;
|
||||||
|
}
|
||||||
|
}
|
||||||
10
ruoyi-modules/ruoyi-file/src/main/resources/banner.txt
Normal file
10
ruoyi-modules/ruoyi-file/src/main/resources/banner.txt
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
Spring Boot Version: ${spring-boot.version}
|
||||||
|
Spring Application Name: ${spring.application.name}
|
||||||
|
_ __ _ _
|
||||||
|
(_) / _|(_)| |
|
||||||
|
_ __ _ _ ___ _ _ _ ______ | |_ _ | | ___
|
||||||
|
| '__|| | | | / _ \ | | | || ||______|| _|| || | / _ \
|
||||||
|
| | | |_| || (_) || |_| || | | | | || || __/
|
||||||
|
|_| \__,_| \___/ \__, ||_| |_| |_||_| \___|
|
||||||
|
__/ |
|
||||||
|
|___/
|
||||||
24
ruoyi-modules/ruoyi-file/src/main/resources/bootstrap.yml
Normal file
24
ruoyi-modules/ruoyi-file/src/main/resources/bootstrap.yml
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Tomcat
|
||||||
|
server:
|
||||||
|
port: 9300
|
||||||
|
|
||||||
|
# Spring
|
||||||
|
spring:
|
||||||
|
application:
|
||||||
|
# 应用名称
|
||||||
|
name: ruoyi-file
|
||||||
|
profiles:
|
||||||
|
# 环境配置
|
||||||
|
active: dev
|
||||||
|
cloud:
|
||||||
|
nacos:
|
||||||
|
discovery:
|
||||||
|
# 服务注册地址
|
||||||
|
server-addr: 127.0.0.1:8848
|
||||||
|
config:
|
||||||
|
# 配置中心地址
|
||||||
|
server-addr: 127.0.0.1:8848
|
||||||
|
# 配置文件格式
|
||||||
|
file-extension: yml
|
||||||
|
# 共享配置
|
||||||
|
shared-dataids: application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
|
||||||
74
ruoyi-modules/ruoyi-file/src/main/resources/logback.xml
Normal file
74
ruoyi-modules/ruoyi-file/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration scan="true" scanPeriod="60 seconds" debug="false">
|
||||||
|
<!-- 日志存放路径 -->
|
||||||
|
<property name="log.path" value="logs/ruoyi-file" />
|
||||||
|
<!-- 日志输出格式 -->
|
||||||
|
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
|
||||||
|
|
||||||
|
<!-- 控制台输出 -->
|
||||||
|
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>${log.pattern}</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<!-- 系统日志输出 -->
|
||||||
|
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||||
|
<file>${log.path}/info.log</file>
|
||||||
|
<!-- 循环政策:基于时间创建日志文件 -->
|
||||||
|
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||||
|
<!-- 日志文件名格式 -->
|
||||||
|
<fileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||||
|
<!-- 日志最大的历史 60天 -->
|
||||||
|
<maxHistory>60</maxHistory>
|
||||||
|
</rollingPolicy>
|
||||||
|
<encoder>
|
||||||
|
<pattern>${log.pattern}</pattern>
|
||||||
|
</encoder>
|
||||||
|
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||||
|
<!-- 过滤的级别 -->
|
||||||
|
<level>INFO</level>
|
||||||
|
<!-- 匹配时的操作:接收(记录) -->
|
||||||
|
<onMatch>ACCEPT</onMatch>
|
||||||
|
<!-- 不匹配时的操作:拒绝(不记录) -->
|
||||||
|
<onMismatch>DENY</onMismatch>
|
||||||
|
</filter>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||||
|
<file>${log.path}/error.log</file>
|
||||||
|
<!-- 循环政策:基于时间创建日志文件 -->
|
||||||
|
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||||
|
<!-- 日志文件名格式 -->
|
||||||
|
<fileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||||
|
<!-- 日志最大的历史 60天 -->
|
||||||
|
<maxHistory>60</maxHistory>
|
||||||
|
</rollingPolicy>
|
||||||
|
<encoder>
|
||||||
|
<pattern>${log.pattern}</pattern>
|
||||||
|
</encoder>
|
||||||
|
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||||
|
<!-- 过滤的级别 -->
|
||||||
|
<level>ERROR</level>
|
||||||
|
<!-- 匹配时的操作:接收(记录) -->
|
||||||
|
<onMatch>ACCEPT</onMatch>
|
||||||
|
<!-- 不匹配时的操作:拒绝(不记录) -->
|
||||||
|
<onMismatch>DENY</onMismatch>
|
||||||
|
</filter>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<!-- 系统模块日志级别控制 -->
|
||||||
|
<logger name="com.ruoyi" level="info" />
|
||||||
|
<!-- Spring日志级别控制 -->
|
||||||
|
<logger name="org.springframework" level="warn" />
|
||||||
|
|
||||||
|
<root level="info">
|
||||||
|
<appender-ref ref="console" />
|
||||||
|
</root>
|
||||||
|
|
||||||
|
<!--系统操作日志-->
|
||||||
|
<root level="info">
|
||||||
|
<appender-ref ref="file_info" />
|
||||||
|
<appender-ref ref="file_error" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi-modules</artifactId>
|
<artifactId>ruoyi-modules</artifactId>
|
||||||
<version>2.1.0</version>
|
<version>2.3.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
@@ -35,10 +35,10 @@
|
|||||||
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- SpringBoot Web -->
|
<!-- SpringBoot Actuator -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Swagger -->
|
<!-- Swagger -->
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import java.util.Map;
|
|||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import org.apache.commons.io.IOUtils;
|
import org.apache.commons.io.IOUtils;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
|
||||||
import org.springframework.validation.annotation.Validated;
|
import org.springframework.validation.annotation.Validated;
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
@@ -23,6 +22,7 @@ import com.ruoyi.common.core.web.domain.AjaxResult;
|
|||||||
import com.ruoyi.common.core.web.page.TableDataInfo;
|
import com.ruoyi.common.core.web.page.TableDataInfo;
|
||||||
import com.ruoyi.common.log.annotation.Log;
|
import com.ruoyi.common.log.annotation.Log;
|
||||||
import com.ruoyi.common.log.enums.BusinessType;
|
import com.ruoyi.common.log.enums.BusinessType;
|
||||||
|
import com.ruoyi.common.security.annotation.PreAuthorize;
|
||||||
import com.ruoyi.gen.domain.GenTable;
|
import com.ruoyi.gen.domain.GenTable;
|
||||||
import com.ruoyi.gen.domain.GenTableColumn;
|
import com.ruoyi.gen.domain.GenTableColumn;
|
||||||
import com.ruoyi.gen.service.IGenTableColumnService;
|
import com.ruoyi.gen.service.IGenTableColumnService;
|
||||||
@@ -46,7 +46,7 @@ public class GenController extends BaseController
|
|||||||
/**
|
/**
|
||||||
* 查询代码生成列表
|
* 查询代码生成列表
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("@ss.hasPermi('tool:gen:list')")
|
@PreAuthorize(hasPermi = "tool:gen:list")
|
||||||
@GetMapping("/list")
|
@GetMapping("/list")
|
||||||
public TableDataInfo genList(GenTable genTable)
|
public TableDataInfo genList(GenTable genTable)
|
||||||
{
|
{
|
||||||
@@ -58,7 +58,7 @@ public class GenController extends BaseController
|
|||||||
/**
|
/**
|
||||||
* 修改代码生成业务
|
* 修改代码生成业务
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("@ss.hasPermi('tool:gen:query')")
|
@PreAuthorize(hasPermi = "tool:gen:query")
|
||||||
@GetMapping(value = "/{talbleId}")
|
@GetMapping(value = "/{talbleId}")
|
||||||
public AjaxResult getInfo(@PathVariable Long talbleId)
|
public AjaxResult getInfo(@PathVariable Long talbleId)
|
||||||
{
|
{
|
||||||
@@ -73,7 +73,7 @@ public class GenController extends BaseController
|
|||||||
/**
|
/**
|
||||||
* 查询数据库列表
|
* 查询数据库列表
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("@ss.hasPermi('tool:gen:list')")
|
@PreAuthorize(hasPermi = "tool:gen:list")
|
||||||
@GetMapping("/db/list")
|
@GetMapping("/db/list")
|
||||||
public TableDataInfo dataList(GenTable genTable)
|
public TableDataInfo dataList(GenTable genTable)
|
||||||
{
|
{
|
||||||
@@ -85,7 +85,6 @@ public class GenController extends BaseController
|
|||||||
/**
|
/**
|
||||||
* 查询数据表字段列表
|
* 查询数据表字段列表
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("@ss.hasPermi('tool:gen:list')")
|
|
||||||
@GetMapping(value = "/column/{talbleId}")
|
@GetMapping(value = "/column/{talbleId}")
|
||||||
public TableDataInfo columnList(Long tableId)
|
public TableDataInfo columnList(Long tableId)
|
||||||
{
|
{
|
||||||
@@ -99,7 +98,7 @@ public class GenController extends BaseController
|
|||||||
/**
|
/**
|
||||||
* 导入表结构(保存)
|
* 导入表结构(保存)
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("@ss.hasPermi('tool:gen:list')")
|
@PreAuthorize(hasPermi = "tool:gen:list")
|
||||||
@Log(title = "代码生成", businessType = BusinessType.IMPORT)
|
@Log(title = "代码生成", businessType = BusinessType.IMPORT)
|
||||||
@PostMapping("/importTable")
|
@PostMapping("/importTable")
|
||||||
public AjaxResult importTableSave(String tables)
|
public AjaxResult importTableSave(String tables)
|
||||||
@@ -114,7 +113,7 @@ public class GenController extends BaseController
|
|||||||
/**
|
/**
|
||||||
* 修改保存代码生成业务
|
* 修改保存代码生成业务
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("@ss.hasPermi('tool:gen:edit')")
|
@PreAuthorize(hasPermi = "tool:gen:edit")
|
||||||
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
|
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
|
||||||
@PutMapping
|
@PutMapping
|
||||||
public AjaxResult editSave(@Validated @RequestBody GenTable genTable)
|
public AjaxResult editSave(@Validated @RequestBody GenTable genTable)
|
||||||
@@ -127,7 +126,7 @@ public class GenController extends BaseController
|
|||||||
/**
|
/**
|
||||||
* 删除代码生成
|
* 删除代码生成
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("@ss.hasPermi('tool:gen:remove')")
|
@PreAuthorize(hasPermi = "tool:gen:remove")
|
||||||
@Log(title = "代码生成", businessType = BusinessType.DELETE)
|
@Log(title = "代码生成", businessType = BusinessType.DELETE)
|
||||||
@DeleteMapping("/{tableIds}")
|
@DeleteMapping("/{tableIds}")
|
||||||
public AjaxResult remove(@PathVariable Long[] tableIds)
|
public AjaxResult remove(@PathVariable Long[] tableIds)
|
||||||
@@ -139,7 +138,7 @@ public class GenController extends BaseController
|
|||||||
/**
|
/**
|
||||||
* 预览代码
|
* 预览代码
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("@ss.hasPermi('tool:gen:preview')")
|
@PreAuthorize(hasPermi = "tool:gen:preview")
|
||||||
@GetMapping("/preview/{tableId}")
|
@GetMapping("/preview/{tableId}")
|
||||||
public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException
|
public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException
|
||||||
{
|
{
|
||||||
@@ -150,7 +149,7 @@ public class GenController extends BaseController
|
|||||||
/**
|
/**
|
||||||
* 生成代码(下载方式)
|
* 生成代码(下载方式)
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("@ss.hasPermi('tool:gen:code')")
|
@PreAuthorize(hasPermi = "tool:gen:code")
|
||||||
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
||||||
@GetMapping("/download/{tableName}")
|
@GetMapping("/download/{tableName}")
|
||||||
public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
|
public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
|
||||||
@@ -162,19 +161,31 @@ public class GenController extends BaseController
|
|||||||
/**
|
/**
|
||||||
* 生成代码(自定义路径)
|
* 生成代码(自定义路径)
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("@ss.hasPermi('tool:gen:code')")
|
@PreAuthorize(hasPermi = "tool:gen:code")
|
||||||
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
||||||
@GetMapping("/genCode/{tableName}")
|
@GetMapping("/genCode/{tableName}")
|
||||||
public AjaxResult genCode(HttpServletResponse response, @PathVariable("tableName") String tableName)
|
public AjaxResult genCode(@PathVariable("tableName") String tableName)
|
||||||
{
|
{
|
||||||
genTableService.generatorCode(tableName);
|
genTableService.generatorCode(tableName);
|
||||||
return AjaxResult.success();
|
return AjaxResult.success();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步数据库
|
||||||
|
*/
|
||||||
|
@PreAuthorize(hasPermi = "tool:gen:edit")
|
||||||
|
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
|
||||||
|
@GetMapping("/synchDb/{tableName}")
|
||||||
|
public AjaxResult synchDb(@PathVariable("tableName") String tableName)
|
||||||
|
{
|
||||||
|
genTableService.synchDb(tableName);
|
||||||
|
return AjaxResult.success();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量生成代码
|
* 批量生成代码
|
||||||
*/
|
*/
|
||||||
@PreAuthorize("@ss.hasPermi('tool:gen:code')")
|
@PreAuthorize(hasPermi = "tool:gen:code")
|
||||||
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
||||||
@GetMapping("/batchGenCode")
|
@GetMapping("/batchGenCode")
|
||||||
public void batchGenCode(HttpServletResponse response, String tables) throws IOException
|
public void batchGenCode(HttpServletResponse response, String tables) throws IOException
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ public class GenTableColumn extends BaseEntity
|
|||||||
/** 查询方式(EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围) */
|
/** 查询方式(EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围) */
|
||||||
private String queryType;
|
private String queryType;
|
||||||
|
|
||||||
/** 显示类型(input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件) */
|
/** 显示类型(input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件、upload上传控件、editor富文本控件) */
|
||||||
private String htmlType;
|
private String htmlType;
|
||||||
|
|
||||||
/** 字典类型 */
|
/** 字典类型 */
|
||||||
@@ -341,7 +341,7 @@ public class GenTableColumn extends BaseEntity
|
|||||||
public static boolean isUsableColumn(String javaField)
|
public static boolean isUsableColumn(String javaField)
|
||||||
{
|
{
|
||||||
// isSuperColumn()中的名单用于避免生成多余Domain属性,若某些属性在生成页面时需要用到不能忽略,则放在此处白名单
|
// isSuperColumn()中的名单用于避免生成多余Domain属性,若某些属性在生成页面时需要用到不能忽略,则放在此处白名单
|
||||||
return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum");
|
return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark");
|
||||||
}
|
}
|
||||||
|
|
||||||
public String readConverterExp()
|
public String readConverterExp()
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ public interface GenTableColumnMapper
|
|||||||
* @return 列信息
|
* @return 列信息
|
||||||
*/
|
*/
|
||||||
public List<GenTableColumn> selectDbTableColumnsByName(String tableName);
|
public List<GenTableColumn> selectDbTableColumnsByName(String tableName);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询业务字段列表
|
* 查询业务字段列表
|
||||||
*
|
*
|
||||||
@@ -42,6 +42,14 @@ public interface GenTableColumnMapper
|
|||||||
*/
|
*/
|
||||||
public int updateGenTableColumn(GenTableColumn genTableColumn);
|
public int updateGenTableColumn(GenTableColumn genTableColumn);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除业务字段
|
||||||
|
*
|
||||||
|
* @param genTableColumns 列数据
|
||||||
|
* @return 结果
|
||||||
|
*/
|
||||||
|
public int deleteGenTableColumns(List<GenTableColumn> genTableColumns);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量删除业务字段
|
* 批量删除业务字段
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import java.io.StringWriter;
|
|||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipOutputStream;
|
import java.util.zip.ZipOutputStream;
|
||||||
import org.apache.commons.io.IOUtils;
|
import org.apache.commons.io.IOUtils;
|
||||||
@@ -223,7 +224,6 @@ public class GenTableServiceImpl implements IGenTableService
|
|||||||
* 生成代码(自定义路径)
|
* 生成代码(自定义路径)
|
||||||
*
|
*
|
||||||
* @param tableName 表名称
|
* @param tableName 表名称
|
||||||
* @return 数据
|
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void generatorCode(String tableName)
|
public void generatorCode(String tableName)
|
||||||
@@ -261,6 +261,37 @@ public class GenTableServiceImpl implements IGenTableService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步数据库
|
||||||
|
*
|
||||||
|
* @param tableName 表名称
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public void synchDb(String tableName)
|
||||||
|
{
|
||||||
|
GenTable table = genTableMapper.selectGenTableByName(tableName);
|
||||||
|
List<GenTableColumn> tableColumns = table.getColumns();
|
||||||
|
List<String> tableColumnNames = tableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
|
||||||
|
|
||||||
|
List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
|
||||||
|
List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
|
||||||
|
|
||||||
|
dbTableColumns.forEach(column -> {
|
||||||
|
if (!tableColumnNames.contains(column.getColumnName()))
|
||||||
|
{
|
||||||
|
GenUtils.initColumnField(column, table);
|
||||||
|
genTableColumnMapper.insertGenTableColumn(column);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
|
||||||
|
if (StringUtils.isNotEmpty(delColumns))
|
||||||
|
{
|
||||||
|
genTableColumnMapper.deleteGenTableColumns(delColumns);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量生成代码(下载方式)
|
* 批量生成代码(下载方式)
|
||||||
*
|
*
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user