first commit
This commit is contained in:
parent
0dfb783d9d
commit
c39927451e
compose.yamlpom.xml
src/main/java/com/zsc/edu/dify
DifyBackendApplication.javaFirstTimeInitializer.java
common
exception
ApiException.javaApiExceptionHandler.javaConstraintException.javaExceptionResult.javaJwtAuthenticationException.javaNotExistException.javaOutlineException.javaStateException.javaStorageException.javaUserHasNoIdentityException.javaValidateException.java
framework
AppConfig.javaJsonExceptionUtil.javaSpringBeanUtil.javaWebMvcConfiguration.java
async
json
message
mybatisplus
DataPermission.javaDataPermissionContext.javaDataScopeAspect.javaDataScopeHandler.javaDataScopeType.javaListTypeHandler.javaMyMetaObjectHandler.javaMybatisPlusConfig.java
redis
response
security
CustomAccessDeniedHandler.javaCustomAuthenticationEntryPoint.javaCustomAuthenticationFailureHandler.javaCustomAuthenticationSuccessHandler.javaCustomSessionInformationExpiredStrategy.javaJpaUserDetailsServiceImpl.javaJsonAuthenticationFilter.javaSecurityBeanConfig.javaSecurityUtil.javaSpringSecurityConfig.javaUserDetailsImpl.java
storage
modules
attachment
controller
dto
entity
repo
service
message
controller
dto
entity
mapper
query
repo
BulletinAttachmentRepository.javaBulletinRepository.javaNoticeRepository.javaUserNoticeRepository.java
service
vo
operationLog
21
compose.yaml
Normal file
21
compose.yaml
Normal file
@ -0,0 +1,21 @@
|
||||
services:
|
||||
mongodb:
|
||||
image: 'mongo:latest'
|
||||
environment:
|
||||
- 'MONGO_INITDB_DATABASE=mydatabase'
|
||||
- 'MONGO_INITDB_ROOT_PASSWORD=secret'
|
||||
- 'MONGO_INITDB_ROOT_USERNAME=root'
|
||||
ports:
|
||||
- '27017'
|
||||
postgres:
|
||||
image: 'postgres:latest'
|
||||
environment:
|
||||
- 'POSTGRES_DB=mydatabase'
|
||||
- 'POSTGRES_PASSWORD=secret'
|
||||
- 'POSTGRES_USER=myuser'
|
||||
ports:
|
||||
- '5432'
|
||||
redis:
|
||||
image: 'redis:latest'
|
||||
ports:
|
||||
- '6379'
|
220
pom.xml
Normal file
220
pom.xml
Normal file
@ -0,0 +1,220 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>3.4.0</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>com.zsc.edu</groupId>
|
||||
<artifactId>dify</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>dify-backend</name>
|
||||
<description>dify-backend</description>
|
||||
<url/>
|
||||
<licenses>
|
||||
<license/>
|
||||
</licenses>
|
||||
<developers>
|
||||
<developer/>
|
||||
</developers>
|
||||
<scm>
|
||||
<connection/>
|
||||
<developerConnection/>
|
||||
<tag/>
|
||||
<url/>
|
||||
</scm>
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<mybatis-plus.version>3.5.9</mybatis-plus.version>
|
||||
<mapstruct.version>1.6.2</mapstruct.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.springframework.boot</groupId>-->
|
||||
<!-- <artifactId>spring-boot-starter-data-mongodb</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-aop</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-freemarker</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-integration</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-mail</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-quartz</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<scope>runtime</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-docker-compose</artifactId>
|
||||
<scope>runtime</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>42.6</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-jsqlparser</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct</artifactId>
|
||||
<version>${mapstruct.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mapstruct</groupId>
|
||||
<artifactId>mapstruct-processor</artifactId>
|
||||
<version>${mapstruct.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.17.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>1.17.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.tika</groupId>
|
||||
<artifactId>tika-core</artifactId>
|
||||
<version>3.0.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt</artifactId>
|
||||
<version>0.9.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>2.0.21</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.integration</groupId>
|
||||
<artifactId>spring-integration-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.restdocs</groupId>
|
||||
<artifactId>spring-restdocs-mockmvc</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.asciidoctor</groupId>
|
||||
<artifactId>asciidoctor-maven-plugin</artifactId>
|
||||
<version>2.2.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>generate-docs</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>process-asciidoc</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<backend>html</backend>
|
||||
<doctype>book</doctype>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.restdocs</groupId>
|
||||
<artifactId>spring-restdocs-asciidoctor</artifactId>
|
||||
<version>${spring-restdocs.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
15
src/main/java/com/zsc/edu/dify/DifyBackendApplication.java
Normal file
15
src/main/java/com/zsc/edu/dify/DifyBackendApplication.java
Normal file
@ -0,0 +1,15 @@
|
||||
package com.zsc.edu.dify;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableAspectJAutoProxy
|
||||
public class DifyBackendApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DifyBackendApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
89
src/main/java/com/zsc/edu/dify/FirstTimeInitializer.java
Normal file
89
src/main/java/com/zsc/edu/dify/FirstTimeInitializer.java
Normal file
@ -0,0 +1,89 @@
|
||||
package com.zsc.edu.dify;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.zsc.edu.dify.modules.system.entity.Dept;
|
||||
import com.zsc.edu.dify.modules.system.entity.Role;
|
||||
import com.zsc.edu.dify.modules.system.entity.User;
|
||||
import com.zsc.edu.dify.modules.system.repo.DeptRepository;
|
||||
import com.zsc.edu.dify.modules.system.service.AuthorityService;
|
||||
import com.zsc.edu.dify.modules.system.service.DeptService;
|
||||
import com.zsc.edu.dify.modules.system.service.RoleService;
|
||||
import com.zsc.edu.dify.modules.system.service.UserService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 系统初始化程序
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
@Profile("!test")
|
||||
public class FirstTimeInitializer implements CommandLineRunner {
|
||||
|
||||
private final AuthorityService authorityService;
|
||||
private final UserService userService;
|
||||
private final RoleService roleService;
|
||||
private final DeptService deptService;
|
||||
private final DeptRepository deptRepo;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
//TODO 初始化赋权给admin
|
||||
@Override
|
||||
public void run(String... args) {
|
||||
// if (authorityService.count() == 0L) {
|
||||
// Authority userPerm = new Authority(null, "用户模块", "用户管理", "SYSTEM:USER", true, null);
|
||||
// Authority rolePerm = new Authority(null, "角色模块", "角色管理", "SYSTEM:ROLE", true, null);
|
||||
// Authority deptPerm = new Authority(null, "部门模块", "部门管理", "SYSTEM:DEPT", true, null);
|
||||
// Authority AuthorityPerm = new Authority(null, "权限模块", "权限管理", "SYSTEM:AUTHORITY", true, null);
|
||||
// authorityService.saveBatch(List.of(userPerm, rolePerm, deptPerm, AuthorityPerm));
|
||||
// List<Authority> authorities = new ArrayList<>();
|
||||
// authorities.add(new Authority(userPerm.getId(), "用户管理", "用户列表", "SYSTEM:USER:QUERY", true, null));
|
||||
// authorities.add(new Authority(userPerm.getId(), "用户管理", "用户新增", "SYSTEM:USER:CREATE",true, null));
|
||||
// authorities.add(new Authority(userPerm.getId(), "用户管理", "用户修改", "SYSTEM:USER:UPDATE",true, null));
|
||||
// authorities.add(new Authority(userPerm.getId(), "用户管理", "用户删除", "SYSTEM:USER:DELETE",true, null));
|
||||
// authorities.add(new Authority(rolePerm.getId(), "角色管理", "角色列表", "SYSTEM:ROLE:QUERY", true, null));
|
||||
// authorities.add(new Authority(rolePerm.getId(), "角色管理", "角色新增", "SYSTEM:ROLE:CREATE",true, null));
|
||||
// authorities.add(new Authority(rolePerm.getId(), "角色管理", "角色修改", "SYSTEM:ROLE:UPDATE",true, null));
|
||||
// authorities.add(new Authority(rolePerm.getId(), "角色管理", "角色删除", "SYSTEM:ROLE:DELETE",true, null));
|
||||
// authorities.add(new Authority(deptPerm.getId(), "部门管理", "部门列表", "SYSTEM:DEPT:QUERY", true, null));
|
||||
// authorities.add(new Authority(deptPerm.getId(), "部门管理", "部门新增", "SYSTEM:DEPT:CREATE",true, null));
|
||||
// authorities.add(new Authority(deptPerm.getId(), "部门管理", "部门修改", "SYSTEM:DEPT:UPDATE",true, null));
|
||||
// authorities.add(new Authority(deptPerm.getId(), "部门管理", "部门删除", "SYSTEM:DEPT:DELETE",true, null));
|
||||
// authorities.add(new Authority(AuthorityPerm.getId(), "权限管理", "权限列表", "SYSTEM:AUTHORITY:QUERY", true, null));
|
||||
// authorities.add(new Authority(AuthorityPerm.getId(), "权限管理", "权限新增", "SYSTEM:AUTHORITY:CREATE",true, null));
|
||||
// authorities.add(new Authority(AuthorityPerm.getId(), "权限管理", "权限修改", "SYSTEM:AUTHORITY:UPDATE",true, null));
|
||||
// authorities.add(new Authority(AuthorityPerm.getId(), "权限管理", "权限删除", "SYSTEM:AUTHORITY:DELETE",true, null));
|
||||
// authorityService.saveBatch(authorities);
|
||||
// }
|
||||
if (roleService.count() == 0L) {
|
||||
Role admin = new Role();
|
||||
admin.setName("管理员");
|
||||
admin.setEnabled(true);
|
||||
roleService.save(admin);
|
||||
}
|
||||
if (deptService.count() == 0L) {
|
||||
Dept dept = new Dept();
|
||||
dept.setName("总公司");
|
||||
deptService.save(dept);
|
||||
}
|
||||
if (userService.count() == 0L) {
|
||||
Dept dept = deptService.getOne(new QueryWrapper<>());
|
||||
Role role = roleService.getOne(new QueryWrapper<>());
|
||||
User user = new User();
|
||||
user.setUsername("admin");
|
||||
user.setPassword(passwordEncoder.encode("admin"));
|
||||
user.setPhone("15913375741");
|
||||
user.setEmail("admin@zsc.edu.cn");
|
||||
user.setName("admin");
|
||||
user.setRoleId(role.getId());
|
||||
user.setDeptId(dept.getId());
|
||||
userService.save(user);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
23
src/main/java/com/zsc/edu/dify/common/enums/EnableState.java
Normal file
23
src/main/java/com/zsc/edu/dify/common/enums/EnableState.java
Normal file
@ -0,0 +1,23 @@
|
||||
package com.zsc.edu.dify.common.enums;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IEnum;
|
||||
|
||||
public enum EnableState implements IEnum<Boolean> {
|
||||
ENABLE(Boolean.TRUE),
|
||||
DISABLE(Boolean.FALSE);
|
||||
|
||||
private boolean value;
|
||||
|
||||
EnableState(Boolean value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean getValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public EnableState reverse() {
|
||||
return this == ENABLE ? DISABLE : ENABLE;
|
||||
}
|
||||
}
|
36
src/main/java/com/zsc/edu/dify/common/enums/IState.java
Normal file
36
src/main/java/com/zsc/edu/dify/common/enums/IState.java
Normal file
@ -0,0 +1,36 @@
|
||||
package com.zsc.edu.dify.common.enums;
|
||||
|
||||
|
||||
import com.zsc.edu.dify.exception.StateException;
|
||||
|
||||
import java.util.EnumSet;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
public interface IState<T extends Enum<T>> {
|
||||
|
||||
/**
|
||||
* 用于检查对象当前状态是否等于correctStatus
|
||||
*
|
||||
* @param correctState 正确状态
|
||||
*/
|
||||
default void checkStatus(T correctState) {
|
||||
if (this != correctState) {
|
||||
throw new StateException(correctState.getClass(), this, correctState);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用于检查对象当前状态是否在集合correctStates中
|
||||
*
|
||||
* @param correctStates 正确状态集合
|
||||
*/
|
||||
@SuppressWarnings("SuspiciousMethodCalls")
|
||||
default void checkStatus(EnumSet<T> correctStates) {
|
||||
if (!correctStates.contains(this)) {
|
||||
throw new StateException(this.getClass(), this, correctStates);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.zsc.edu.dify.common.mapstruct;
|
||||
|
||||
import org.mapstruct.MappingTarget;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface BaseMapper<D, E> {
|
||||
D toDto(E entity);
|
||||
|
||||
E toEntity(D dto);
|
||||
|
||||
List<D> toDto(List<E> entityList);
|
||||
|
||||
List<E> toEntity(List<D> dtoList);
|
||||
|
||||
/**
|
||||
* 更新实体类
|
||||
*
|
||||
* @param dto
|
||||
* @param entity
|
||||
*/
|
||||
void convert(D dto, @MappingTarget E entity);
|
||||
}
|
133
src/main/java/com/zsc/edu/dify/common/util/TreeUtil.java
Normal file
133
src/main/java/com/zsc/edu/dify/common/util/TreeUtil.java
Normal file
@ -0,0 +1,133 @@
|
||||
package com.zsc.edu.dify.common.util;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* @Description: 树操作方法工具类
|
||||
* @Copyright: Copyright (c) 赵侠客
|
||||
* @Date: 2024-07-22 10:42
|
||||
* @Version: 1.0
|
||||
*/
|
||||
public class TreeUtil {
|
||||
|
||||
/**
|
||||
* 将list合成树
|
||||
*
|
||||
* @param list 需要合成树的List
|
||||
* @param rootCheck 判断E中为根节点的条件,如:x->x.getPId()==-1L , x->x.getParentId()==null,x->x.getParentMenuId()==0
|
||||
* @param parentCheck 判断E中为父节点条件,如:(x,y)->x.getId().equals(y.getPId())
|
||||
* @param setSubChildren E中设置下级数据方法,如:Menu::setSubMenus
|
||||
* @param <E> 泛型实体对象
|
||||
* @return 合成好的树
|
||||
*/
|
||||
public static <E> List<E> makeTree(List<E> list, Predicate<E> rootCheck, BiFunction<E, E, Boolean> parentCheck, BiConsumer<E, List<E>> setSubChildren) {
|
||||
return list.stream().filter(rootCheck).peek(x -> setSubChildren.accept(x, makeChildren(x, list, parentCheck, setSubChildren))).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 将树打平成list
|
||||
*
|
||||
* @param tree 需要打平的树
|
||||
* @param getSubChildren 设置下级数据方法,如:Menu::getSubMenus,x->x.setSubMenus(null)
|
||||
* @param setSubChildren 将下级数据置空方法,如:x->x.setSubMenus(null)
|
||||
* @param <E> 泛型实体对象
|
||||
* @return 打平后的数据
|
||||
*/
|
||||
public static <E> List<E> flat(List<E> tree, Function<E, List<E>> getSubChildren, Consumer<E> setSubChildren) {
|
||||
List<E> res = new ArrayList<>();
|
||||
forPostOrder(tree, item -> {
|
||||
setSubChildren.accept(item);
|
||||
res.add(item);
|
||||
}, getSubChildren);
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* 前序遍历
|
||||
*
|
||||
* @param tree 需要遍历的树
|
||||
* @param consumer 遍历后对单个元素的处理方法,如:x-> System.out.println(x)、 System.out::println打印元素
|
||||
* @param setSubChildren 设置下级数据方法,如:Menu::getSubMenus,x->x.setSubMenus(null)
|
||||
* @param <E> 泛型实体对象
|
||||
*/
|
||||
public static <E> void forPreOrder(List<E> tree, Consumer<E> consumer, Function<E, List<E>> setSubChildren) {
|
||||
for (E l : tree) {
|
||||
consumer.accept(l);
|
||||
List<E> es = setSubChildren.apply(l);
|
||||
if (es != null && es.size() > 0) {
|
||||
forPreOrder(es, consumer, setSubChildren);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 层序遍历
|
||||
*
|
||||
* @param tree 需要遍历的树
|
||||
* @param consumer 遍历后对单个元素的处理方法,如:x-> System.out.println(x)、 System.out::println打印元素
|
||||
* @param setSubChildren 设置下级数据方法,如:Menu::getSubMenus,x->x.setSubMenus(null)
|
||||
* @param <E> 泛型实体对象
|
||||
*/
|
||||
public static <E> void forLevelOrder(List<E> tree, Consumer<E> consumer, Function<E, List<E>> setSubChildren) {
|
||||
Queue<E> queue = new LinkedList<>(tree);
|
||||
while (!queue.isEmpty()) {
|
||||
E item = queue.poll();
|
||||
consumer.accept(item);
|
||||
List<E> childList = setSubChildren.apply(item);
|
||||
if (childList != null && !childList.isEmpty()) {
|
||||
queue.addAll(childList);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 后序遍历
|
||||
*
|
||||
* @param tree 需要遍历的树
|
||||
* @param consumer 遍历后对单个元素的处理方法,如:x-> System.out.println(x)、 System.out::println打印元素
|
||||
* @param setSubChildren 设置下级数据方法,如:Menu::getSubMenus,x->x.setSubMenus(null)
|
||||
* @param <E> 泛型实体对象
|
||||
*/
|
||||
public static <E> void forPostOrder(List<E> tree, Consumer<E> consumer, Function<E, List<E>> setSubChildren) {
|
||||
for (E item : tree) {
|
||||
List<E> childList = setSubChildren.apply(item);
|
||||
if (childList != null && !childList.isEmpty()) {
|
||||
forPostOrder(childList, consumer, setSubChildren);
|
||||
}
|
||||
consumer.accept(item);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 对树所有子节点按comparator排序
|
||||
*
|
||||
* @param tree 需要排序的树
|
||||
* @param comparator 排序规则Comparator,如:Comparator.comparing(MenuVo::getRank)按Rank正序 ,(x,y)->y.getRank().compareTo(x.getRank()),按Rank倒序
|
||||
* @param getChildren 获取下级数据方法,如:MenuVo::getSubMenus
|
||||
* @param <E> 泛型实体对象
|
||||
* @return 排序好的树
|
||||
*/
|
||||
public static <E> List<E> sort(List<E> tree, Comparator<? super E> comparator, Function<E, List<E>> getChildren) {
|
||||
for (E item : tree) {
|
||||
List<E> childList = getChildren.apply(item);
|
||||
if (childList != null && !childList.isEmpty()) {
|
||||
sort(childList, comparator, getChildren);
|
||||
}
|
||||
}
|
||||
tree.sort(comparator);
|
||||
return tree;
|
||||
}
|
||||
|
||||
private static <E> List<E> makeChildren(E parent, List<E> allData, BiFunction<E, E, Boolean> parentCheck, BiConsumer<E, List<E>> children) {
|
||||
return allData.stream()
|
||||
.filter(x -> parentCheck.apply(parent, x))
|
||||
.peek(x -> children.accept(x, makeChildren(x, allData, parentCheck, children)))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
32
src/main/java/com/zsc/edu/dify/exception/ApiException.java
Normal file
32
src/main/java/com/zsc/edu/dify/exception/ApiException.java
Normal file
@ -0,0 +1,32 @@
|
||||
package com.zsc.edu.dify.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public class ApiException extends RuntimeException {
|
||||
|
||||
public ApiException() {
|
||||
super("发生服务器内部异常,请联系管理员提交故障");
|
||||
}
|
||||
|
||||
public ApiException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ApiException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public ApiException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public ApiException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package com.zsc.edu.dify.exception;
|
||||
|
||||
//import com.zsc.study.module.common.domain.ResponseResult;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.annotation.Resource;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@RestControllerAdvice
|
||||
public class ApiExceptionHandler {
|
||||
|
||||
@Resource
|
||||
private ObjectMapper objectMapper;
|
||||
@ExceptionHandler(value = {ConstraintException.class})
|
||||
public ResponseEntity<Object> handleException(ConstraintException ex) throws JsonProcessingException {
|
||||
log.error("ConstraintException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
|
||||
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = {NotExistException.class})
|
||||
public ResponseEntity<Object> handleException(NotExistException ex) throws JsonProcessingException {
|
||||
log.error("NotExistException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
|
||||
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = {StateException.class})
|
||||
public ResponseEntity<Object> handleException(StateException ex) throws JsonProcessingException {
|
||||
log.error("StateException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
|
||||
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = {StorageException.class})
|
||||
public ResponseEntity<Object> handleException(StorageException ex) throws JsonProcessingException {
|
||||
log.error("StorageException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
|
||||
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = {UserHasNoIdentityException.class})
|
||||
public ResponseEntity<Object> handleException(UserHasNoIdentityException ex) throws JsonProcessingException {
|
||||
log.error("UserHasNoIdentityException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
|
||||
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = {ValidateException.class})
|
||||
public ResponseEntity<Object> handleException(ValidateException ex) throws JsonProcessingException {
|
||||
log.error("ValidateException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
|
||||
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = {ApiException.class})
|
||||
public ResponseEntity<Object> handleException(ApiException ex) throws JsonProcessingException {
|
||||
log.error("ApiException: {}", objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())));
|
||||
return new ResponseEntity<>(objectMapper.writeValueAsString(Map.of("msg", ex.getMessage())), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.zsc.edu.dify.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public class ConstraintException extends ApiException {
|
||||
|
||||
public ConstraintException(String fieldName, Object fieldValue) {
|
||||
super(String.format("字段%s的值:'%s'不符合要求。", fieldName, fieldValue));
|
||||
}
|
||||
|
||||
public ConstraintException(String fieldName, Object fieldValue, String message) {
|
||||
super(String.format("字段%s的值:'%s'不符合要求,%s", fieldName, fieldValue, message));
|
||||
}
|
||||
|
||||
public ConstraintException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.zsc.edu.dify.exception;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
public class ExceptionResult {
|
||||
|
||||
public final String msg;
|
||||
public final Object code;
|
||||
public final LocalDateTime timestamp;
|
||||
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.zsc.edu.dify.exception;
|
||||
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
|
||||
/**
|
||||
* @author Yao
|
||||
*/
|
||||
public class JwtAuthenticationException extends AuthenticationException {
|
||||
public JwtAuthenticationException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.zsc.edu.dify.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||
public class NotExistException extends ApiException {
|
||||
|
||||
public NotExistException(Class<?> entity) {
|
||||
super(String.format("%s对象不存在", entity.getSimpleName()));
|
||||
}
|
||||
|
||||
public NotExistException() {
|
||||
super("对象不存在");
|
||||
}
|
||||
|
||||
public NotExistException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.zsc.edu.dify.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public class OutlineException extends ApiException {
|
||||
|
||||
public OutlineException() {
|
||||
super("设备不在线");
|
||||
}
|
||||
|
||||
public OutlineException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
19
src/main/java/com/zsc/edu/dify/exception/StateException.java
Normal file
19
src/main/java/com/zsc/edu/dify/exception/StateException.java
Normal file
@ -0,0 +1,19 @@
|
||||
package com.zsc.edu.dify.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public class StateException extends ApiException {
|
||||
|
||||
public StateException(Class<?> statusClass, Object currentStatus, Object correctStatus) {
|
||||
super(String.format("%s当前的状态值'%s'不符合要求,正确的状态值可以是:%s。", statusClass.getSimpleName(), currentStatus, correctStatus));
|
||||
}
|
||||
|
||||
public StateException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.zsc.edu.dify.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public class StorageException extends ApiException {
|
||||
|
||||
public StorageException() {
|
||||
super("文件存储失败");
|
||||
}
|
||||
|
||||
public StorageException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.zsc.edu.dify.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.authentication.DisabledException;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||
public class UserHasNoIdentityException extends DisabledException {
|
||||
|
||||
public UserHasNoIdentityException() {
|
||||
super("没有给用户分配身份");
|
||||
}
|
||||
|
||||
public UserHasNoIdentityException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.zsc.edu.dify.exception;
|
||||
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||
public class ValidateException extends ApiException {
|
||||
|
||||
public ValidateException() {
|
||||
super("验证码失效或错误!");
|
||||
}
|
||||
|
||||
public ValidateException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ValidateException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
17
src/main/java/com/zsc/edu/dify/framework/AppConfig.java
Normal file
17
src/main/java/com/zsc/edu/dify/framework/AppConfig.java
Normal file
@ -0,0 +1,17 @@
|
||||
package com.zsc.edu.dify.framework;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Configuration
|
||||
public class AppConfig {
|
||||
|
||||
@Bean
|
||||
public RestClient restClient() {
|
||||
return RestClient.builder().build();
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.zsc.edu.dify.framework;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author harry yao
|
||||
*/
|
||||
public class JsonExceptionUtil {
|
||||
public static Map<String, Object> jsonExceptionResult(HttpStatus code, String message, String path) {
|
||||
Map<String, Object> exceptionMap = new LinkedHashMap<>();
|
||||
exceptionMap.put("timestamp", Calendar.getInstance().getTime());
|
||||
exceptionMap.put("message", message);
|
||||
exceptionMap.put("path", path);
|
||||
exceptionMap.put("code", code.value());
|
||||
return exceptionMap;
|
||||
}
|
||||
}
|
29
src/main/java/com/zsc/edu/dify/framework/SpringBeanUtil.java
Normal file
29
src/main/java/com/zsc/edu/dify/framework/SpringBeanUtil.java
Normal file
@ -0,0 +1,29 @@
|
||||
package com.zsc.edu.dify.framework;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author harry yao
|
||||
*/
|
||||
@Component
|
||||
public class SpringBeanUtil implements ApplicationContextAware {
|
||||
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
public static <T> T getBean(Class<T> beanClass) {
|
||||
return applicationContext.getBean(beanClass);
|
||||
}
|
||||
|
||||
public static Object getBean(String beanName) {
|
||||
return applicationContext.getBean(beanName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
|
||||
SpringBeanUtil.applicationContext = applicationContext;
|
||||
}
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
package com.zsc.edu.dify.framework;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.boot.autoconfigure.web.WebProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.resource.PathResourceResolver;
|
||||
import org.springframework.web.servlet.resource.ResourceResolverChain;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Configuration
|
||||
@AllArgsConstructor
|
||||
public class WebMvcConfiguration implements WebMvcConfigurer {
|
||||
|
||||
private final WebProperties webProperties;
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/**")
|
||||
.addResourceLocations(webProperties.getResources().getStaticLocations())
|
||||
.resourceChain(webProperties.getResources().getChain().isCache())
|
||||
.addResolver(new FallbackPathResourceResolver());
|
||||
}
|
||||
|
||||
private static class FallbackPathResourceResolver extends PathResourceResolver {
|
||||
@Override
|
||||
public Resource resolveResource(
|
||||
HttpServletRequest request,
|
||||
@NonNull String requestPath,
|
||||
@NonNull List<? extends Resource> locations,
|
||||
@NonNull ResourceResolverChain chain) {
|
||||
Resource resource = super.resolveResource(request, requestPath, locations, chain);
|
||||
if (resource == null) {
|
||||
resource = super.resolveResource(request, "/index.html", locations, chain);
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
package com.zsc.edu.dify.framework.async;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.AsyncConfigurer;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
|
||||
@Slf4j
|
||||
@EnableAsync
|
||||
@Configuration
|
||||
//@Profile("!test") // test 环境下不启动异步
|
||||
public class AsyncConfiguration implements AsyncConfigurer {
|
||||
|
||||
// @Bean
|
||||
// public AsyncTaskExecutor taskExecutor() {
|
||||
// ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
// executor.setCorePoolSize(20);
|
||||
// executor.setMaxPoolSize(20);
|
||||
// executor.setQueueCapacity(500);
|
||||
// executor.setThreadNamePrefix("Executor");
|
||||
// executor.initialize();
|
||||
// return executor;
|
||||
// }
|
||||
|
||||
@Override
|
||||
public Executor getAsyncExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(20);
|
||||
executor.setMaxPoolSize(20);
|
||||
executor.setQueueCapacity(500);
|
||||
executor.setThreadNamePrefix("Executor-");
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
|
||||
// return AsyncConfigurer.super.getAsyncUncaughtExceptionHandler();
|
||||
return (Throwable throwable, Method method, Object... obj)->{
|
||||
log.info("Method name -{}, Exception message -{}", method.getName(),throwable);
|
||||
};
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.zsc.edu.dify.framework.json;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* @author veryao
|
||||
*/
|
||||
@Configuration
|
||||
public class JsonConfig {
|
||||
|
||||
@Bean
|
||||
public Jackson2ObjectMapperBuilderCustomizer customizer() {
|
||||
return builder -> builder.serializationInclusion(JsonInclude.Include.NON_NULL)
|
||||
.serializationInclusion(JsonInclude.Include.NON_EMPTY);
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.zsc.edu.dify.framework.json;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
import org.apache.ibatis.type.MappedJdbcTypes;
|
||||
import org.apache.ibatis.type.MappedTypes;
|
||||
import org.postgresql.util.PGobject;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
|
||||
@MappedTypes({Object.class})
|
||||
@MappedJdbcTypes(JdbcType.VARCHAR)
|
||||
public class JsonbTypeHandler<T> extends JacksonTypeHandler {
|
||||
|
||||
private final Class<T> clazz;
|
||||
|
||||
public JsonbTypeHandler(Class<T> clazz) {
|
||||
super(clazz);
|
||||
if (clazz == null) {
|
||||
throw new IllegalArgumentException("Type argument cannot be null");
|
||||
}
|
||||
this.clazz = clazz;
|
||||
}
|
||||
|
||||
// 自3.5.6版本开始支持泛型,需要加上此构造.
|
||||
public JsonbTypeHandler(Class<?> type, Field field, Class<T> clazz) {
|
||||
super(type, field);
|
||||
this.clazz = clazz;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
|
||||
PGobject jsonbObject = new PGobject();
|
||||
jsonbObject.setType("jsonb");
|
||||
jsonbObject.setValue(toJson(parameter));
|
||||
ps.setObject(i, jsonbObject);
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.zsc.edu.dify.framework.message.email;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties("spring.mail")
|
||||
@Configuration
|
||||
public class EmailProperties {
|
||||
public String username;
|
||||
}
|
@ -0,0 +1,106 @@
|
||||
package com.zsc.edu.dify.framework.message.email;
|
||||
|
||||
|
||||
import com.zsc.edu.dify.modules.attachment.service.AttachmentService;
|
||||
import com.zsc.edu.dify.modules.message.entity.Notice;
|
||||
import freemarker.template.Configuration;
|
||||
import freemarker.template.Template;
|
||||
import freemarker.template.TemplateException;
|
||||
import jakarta.annotation.Resource;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.internet.AddressException;
|
||||
import jakarta.mail.internet.InternetAddress;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
|
||||
/**
|
||||
* @author pegnzheng
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
public class EmailSender {
|
||||
|
||||
private final static String TEMPLATE = "message.ftl";
|
||||
|
||||
private final EmailProperties config;
|
||||
private final Configuration freemarkerConfig;
|
||||
@Resource
|
||||
private final JavaMailSender sender;
|
||||
private final AttachmentService attachmentService;
|
||||
|
||||
@Async
|
||||
public void send(String email, Notice notice) {
|
||||
if (StringUtils.hasText(email)) {
|
||||
return;
|
||||
}
|
||||
InternetAddress to;
|
||||
try {
|
||||
to = new InternetAddress(email);
|
||||
to.validate();
|
||||
} catch (AddressException e) {
|
||||
return;
|
||||
}
|
||||
send(new InternetAddress[]{to}, notice);
|
||||
}
|
||||
|
||||
@Async
|
||||
public void send(Set<String> emails, Notice notice) {
|
||||
InternetAddress[] to = emails.stream().filter(Objects::nonNull).map(email ->
|
||||
{
|
||||
try {
|
||||
return new InternetAddress(email);
|
||||
} catch (AddressException e) {
|
||||
return null;
|
||||
}
|
||||
}).filter(Objects::nonNull).filter(internetAddress -> {
|
||||
try {
|
||||
internetAddress.validate();
|
||||
} catch (AddressException e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}).toArray(InternetAddress[]::new);
|
||||
if (to.length == 0) {
|
||||
return;
|
||||
}
|
||||
send(to, notice);
|
||||
}
|
||||
|
||||
private void send(InternetAddress[] to, Notice notice) {
|
||||
try {
|
||||
MimeMessage mimeMessage = sender.createMimeMessage();
|
||||
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
|
||||
helper.setTo(to);
|
||||
helper.setFrom(config.username);
|
||||
helper.setSubject(notice.getTitle());
|
||||
if (notice.html) {
|
||||
StringWriter sw = new StringWriter();
|
||||
Template tp = freemarkerConfig.getTemplate(TEMPLATE, "UTF-8");
|
||||
tp.process(notice, sw);
|
||||
helper.setText(sw.toString(), true);
|
||||
} else {
|
||||
helper.setText(notice.content);
|
||||
}
|
||||
// if (Objects.nonNull(message.attachments)) {
|
||||
// for (Attachment attachment : message.attachments) {
|
||||
// helper.addAttachment(attachment.fileName, attachmentService.loadAsResource(attachment.id), attachment.mimeType);
|
||||
// }
|
||||
// }
|
||||
sender.send(mimeMessage);
|
||||
} catch (MessagingException | IOException | TemplateException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.zsc.edu.dify.framework.message.sms;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties("sms")
|
||||
@Configuration
|
||||
public class SmsProperties {
|
||||
public String apiKey = "4d8de516324886549d0ba3ddc4bf6f47";
|
||||
public String singleSendUrl = "https://sms.yunpian.com/v2/sms/single_send.json";
|
||||
public String batchSendUrl = "https://sms.yunpian.com/v2/sms/batch_send.json";
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package com.zsc.edu.dify.framework.message.sms;
|
||||
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @author pegnzheng
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
public class SmsSender {
|
||||
|
||||
private final SmsProperties properties;
|
||||
@Resource
|
||||
private final RestClient restClient;
|
||||
|
||||
@Async
|
||||
public void send(String mobile, String text) {
|
||||
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
|
||||
params.add("apikey", properties.apiKey);
|
||||
params.add("mobile", mobile);
|
||||
params.add("text", text);
|
||||
restClient.post().uri(properties.singleSendUrl).body(params);
|
||||
}
|
||||
|
||||
@Async
|
||||
public void send(Set<String> mobiles, String text) {
|
||||
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
|
||||
params.add("apikey", properties.apiKey);
|
||||
params.add("mobile", mobiles.stream().filter(StringUtils::hasText).collect(Collectors.joining(",")));
|
||||
params.add("text", text);
|
||||
restClient.post().uri(properties.batchSendUrl).body(params);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.zsc.edu.dify.framework.mybatisplus;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* @author vertoryao
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface DataPermission {
|
||||
/**
|
||||
* 目标表的别名
|
||||
*/
|
||||
String tableAlias() default "";
|
||||
/**
|
||||
* 部门表的别名
|
||||
*/
|
||||
String deptAlias() default "dept_id";
|
||||
|
||||
/**
|
||||
* 用户表的别名
|
||||
*/
|
||||
String userAlias() default "create_id";
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.zsc.edu.dify.framework.mybatisplus;
|
||||
|
||||
public class DataPermissionContext {
|
||||
|
||||
private static final ThreadLocal<DataPermission> contextHolder = new ThreadLocal<>();
|
||||
|
||||
public static void set(DataPermission dataPermission) {
|
||||
contextHolder.set(dataPermission);
|
||||
}
|
||||
|
||||
public static DataPermission get() {
|
||||
return contextHolder.get();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
contextHolder.remove();
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.zsc.edu.dify.framework.mybatisplus;
|
||||
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* 数据权限注解切面
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class DataScopeAspect {
|
||||
|
||||
/**
|
||||
* 环绕通知,拦截带有 @DataPermission 注解的方法
|
||||
* @param joinPoint
|
||||
* @throws Throwable
|
||||
*/
|
||||
@Around("@annotation(DataPermission)()")
|
||||
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
|
||||
// 获取方法上的 @DataPermission 注解
|
||||
DataPermission dataPermission = method.getAnnotation(DataPermission.class);
|
||||
|
||||
if (dataPermission != null) {
|
||||
// 将注解信息存储在上下文中,供 MyBatis 拦截器使用
|
||||
DataPermissionContext.set(dataPermission);
|
||||
}
|
||||
|
||||
try {
|
||||
// 执行目标方法
|
||||
return joinPoint.proceed();
|
||||
} finally {
|
||||
// 方法执行完毕,清除数据权限上下文,避免内存泄露
|
||||
DataPermissionContext.clear();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,127 @@
|
||||
package com.zsc.edu.dify.framework.mybatisplus;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
|
||||
import com.baomidou.mybatisplus.extension.plugins.handler.MultiDataPermissionHandler;
|
||||
import com.zsc.edu.dify.framework.security.SecurityUtil;
|
||||
import com.zsc.edu.dify.framework.security.UserDetailsImpl;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.sf.jsqlparser.expression.Expression;
|
||||
import net.sf.jsqlparser.expression.LongValue;
|
||||
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
|
||||
import net.sf.jsqlparser.expression.operators.relational.InExpression;
|
||||
import net.sf.jsqlparser.expression.operators.relational.ParenthesedExpressionList;
|
||||
import net.sf.jsqlparser.schema.Column;
|
||||
import net.sf.jsqlparser.schema.Table;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 数据权限拼装逻辑处理
|
||||
*
|
||||
*/
|
||||
@Slf4j
|
||||
public class DataScopeHandler implements MultiDataPermissionHandler {
|
||||
|
||||
/**
|
||||
* 获取数据权限 SQL 片段。
|
||||
* <p> {@link MultiDataPermissionHandler#getSqlSegment(Table, Expression, String)} 方法不能覆盖原有的 where 数据,如果 return 了 null 则表示不追加任何 where 条件</p>
|
||||
*
|
||||
* @param table 所执行的数据库表信息,可以通过此参数获取表名和表别名
|
||||
* @param where 原有的 where 条件信息
|
||||
* @param mappedStatementId Mybatis MappedStatementId 根据该参数可以判断具体执行方法
|
||||
* @return JSqlParser 条件表达式,返回的条件表达式会拼接在原有的表达式后面(不会覆盖原有的表达式)
|
||||
*/
|
||||
@Override
|
||||
public Expression getSqlSegment(Table table, Expression where, String mappedStatementId) {
|
||||
// try {
|
||||
// 获取当前线程中的数据权限信息
|
||||
DataPermission dataPermission = DataPermissionContext.get();
|
||||
if (Objects.isNull(dataPermission)) {
|
||||
return null;
|
||||
}
|
||||
return buildDataScopeByAnnotation(dataPermission);
|
||||
|
||||
}
|
||||
/**
|
||||
* DataScope注解方式,拼装数据权限
|
||||
* @param dataScope
|
||||
* @return
|
||||
*/
|
||||
private Expression buildDataScopeByAnnotation(DataPermission dataScope) {
|
||||
UserDetailsImpl userInfo = SecurityUtil.getUserInfo();
|
||||
if (userInfo == null) {
|
||||
return null;
|
||||
}
|
||||
Set<Long> dataScopeDeptIds = userInfo.getDataScopeDeptIds();
|
||||
DataScopeType dataScopeType = userInfo.getRole().getDataScope();
|
||||
// 本人ID
|
||||
Long dataScopeCreateId = userInfo.getId();
|
||||
// 本人部门ID
|
||||
Long deptId = userInfo.getDept().getId();
|
||||
// 表别名
|
||||
String tableAlias = dataScope.tableAlias();
|
||||
// 部门限制范围的字段名称
|
||||
String deptAlias = dataScope.deptAlias();
|
||||
// 本人限制范围的字段名称
|
||||
String userAlias = dataScope.userAlias();
|
||||
|
||||
// 拼装数据权限
|
||||
return switch (dataScopeType) {
|
||||
// 全部数据权限
|
||||
case DATA_SCOPE_ALL -> null;
|
||||
// 本部门数据权限, 构建部门eq表达式
|
||||
case DATA_SCOPE_DEPT -> equalsTo(tableAlias, deptAlias, deptId);
|
||||
// 本部门及以下数据权限,构建部门in表达式
|
||||
case DATA_SCOPE_DEPT_AND_CHILD -> inExpression(tableAlias, deptAlias, dataScopeDeptIds);
|
||||
// 本人数据权限,构建本人eq表达式
|
||||
case DATA_SCOPE_SELF -> equalsTo(tableAlias, userAlias, dataScopeCreateId);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建eq表达式
|
||||
* @param tableAlias 表别名
|
||||
* @param itemAlias 字段别名
|
||||
* @param itemId id
|
||||
* @return
|
||||
*/
|
||||
private EqualsTo equalsTo(String tableAlias, String itemAlias, Long itemId) {
|
||||
if (Objects.nonNull(itemId)) {
|
||||
EqualsTo equalsTo = new EqualsTo();
|
||||
equalsTo.withLeftExpression(buildColumn(tableAlias, itemAlias));
|
||||
equalsTo.setRightExpression(new LongValue(itemId));
|
||||
return equalsTo;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private InExpression inExpression(String tableAlias, String itemAlias, Set<Long> itemIds) {
|
||||
if (!itemIds.isEmpty()) {
|
||||
InExpression deptIdInExpression = new InExpression();
|
||||
ParenthesedExpressionList<LongValue> deptIds = new ParenthesedExpressionList<>(itemIds.stream().map(LongValue::new).collect(Collectors.toList()));
|
||||
deptIdInExpression.withLeftExpression(buildColumn(tableAlias, itemAlias));
|
||||
deptIdInExpression.setRightExpression(deptIds);
|
||||
return deptIdInExpression;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 构建Column
|
||||
*
|
||||
* @param tableAlias 表别名
|
||||
* @param columnName 字段名称
|
||||
* @return 带表别名字段
|
||||
*/
|
||||
public static Column buildColumn(String tableAlias, String columnName) {
|
||||
if (StringUtils.isNotEmpty(tableAlias)) {
|
||||
columnName = tableAlias + "." + columnName;
|
||||
}
|
||||
return new Column(columnName);
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.zsc.edu.dify.framework.mybatisplus;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IEnum;
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
@AllArgsConstructor
|
||||
public enum DataScopeType implements IEnum<Integer> {
|
||||
/**
|
||||
* 全部数据权限
|
||||
*/
|
||||
DATA_SCOPE_ALL(1),
|
||||
/**
|
||||
* 部门数据权限
|
||||
*/
|
||||
DATA_SCOPE_DEPT(2),
|
||||
/**
|
||||
* 部门及以下数据权限
|
||||
*/
|
||||
DATA_SCOPE_DEPT_AND_CHILD(3),
|
||||
/**
|
||||
* 仅个人数据权限
|
||||
*/
|
||||
DATA_SCOPE_SELF(4);
|
||||
/**
|
||||
* 自定义数据权限
|
||||
*/
|
||||
// DATA_SCOPE_CUSTOM(5);
|
||||
|
||||
private final int value;
|
||||
|
||||
@Override
|
||||
public Integer getValue() {
|
||||
return this.value;
|
||||
}
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.zsc.edu.dify.framework.mybatisplus;
|
||||
|
||||
|
||||
import org.apache.ibatis.type.BaseTypeHandler;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
import org.apache.ibatis.type.MappedJdbcTypes;
|
||||
import org.apache.ibatis.type.MappedTypes;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author : wshuo
|
||||
* @date : 2023/1/11 15:59
|
||||
*/
|
||||
@MappedJdbcTypes(JdbcType.VARCHAR)
|
||||
@MappedTypes({ArrayList.class})
|
||||
public class ListTypeHandler extends BaseTypeHandler<ArrayList<String>> {
|
||||
|
||||
private static final String DELIM = ",";
|
||||
|
||||
@Override
|
||||
public void setNonNullParameter(PreparedStatement preparedStatement, int i, ArrayList<String> strings, JdbcType jdbcType) throws SQLException {
|
||||
String value = StringUtils.collectionToDelimitedString(strings, DELIM);
|
||||
preparedStatement.setString(i, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArrayList<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
|
||||
String value = resultSet.getString(s);
|
||||
return new ArrayList(List.of(StringUtils.tokenizeToStringArray(value, DELIM)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArrayList<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
|
||||
String value = resultSet.getString(i);
|
||||
return new ArrayList(List.of(StringUtils.tokenizeToStringArray(value, DELIM)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArrayList<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
|
||||
String value = callableStatement.getString(i);
|
||||
return new ArrayList(List.of(StringUtils.tokenizeToStringArray(value, DELIM)));
|
||||
}
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.zsc.edu.dify.framework.mybatisplus;
|
||||
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import com.zsc.edu.dify.framework.security.SecurityUtil;
|
||||
import com.zsc.edu.dify.framework.security.UserDetailsImpl;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author Yao
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class MyMetaObjectHandler implements MetaObjectHandler {
|
||||
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
|
||||
UserDetailsImpl userInfo = SecurityUtil.getUserInfo();
|
||||
if (userInfo.getUsername() == null) {
|
||||
userInfo.setUsername("system");
|
||||
}
|
||||
if (userInfo.getDeptId() == null) {
|
||||
userInfo.setDeptId(2L);
|
||||
}
|
||||
if (userInfo.getCreateId() == null) {
|
||||
userInfo.setCreateId(1L);
|
||||
}
|
||||
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
|
||||
this.strictInsertFill(metaObject, "createBy", String.class, userInfo.getUsername());
|
||||
this.strictInsertFill(metaObject, "deptId", Long.class, userInfo.getDeptId());
|
||||
this.strictInsertFill(metaObject, "createId", Long.class, userInfo.getCreateId());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
UserDetailsImpl userInfo = SecurityUtil.getUserInfo();
|
||||
if (userInfo.getUsername() == null) {
|
||||
userInfo.setUsername("system");
|
||||
}
|
||||
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
|
||||
this.strictUpdateFill(metaObject, "updateBy", userInfo::getUsername, String.class);
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.zsc.edu.dify.framework.mybatisplus;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* @author Yao
|
||||
*/
|
||||
@MapperScan(basePackages = "com.zsc.edu.dify.modules.**.repo")
|
||||
@Configuration
|
||||
public class MybatisPlusConfig {
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
// 添加数据权限插件
|
||||
DataPermissionInterceptor dataPermissionInterceptor = new DataPermissionInterceptor(new DataScopeHandler());
|
||||
// 添加自定义的数据权限处理器
|
||||
interceptor.addInnerInterceptor(dataPermissionInterceptor);
|
||||
// 添加分页插件
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
|
||||
return interceptor;
|
||||
}
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
package com.zsc.edu.dify.framework.redis;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Component
|
||||
public class RedisUtils {
|
||||
|
||||
@Autowired
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
/**
|
||||
* 设置键值对
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
*/
|
||||
public void set(String key, String value) {
|
||||
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
|
||||
ops.set(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置键值对并设置过期时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param timeout 过期时间
|
||||
* @param unit 时间单位
|
||||
*/
|
||||
public void set(String key, String value, long timeout, TimeUnit unit) {
|
||||
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
|
||||
ops.set(key, value, timeout, unit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取键值对
|
||||
*
|
||||
* @param key 键
|
||||
* @return 值
|
||||
*/
|
||||
public String get(String key) {
|
||||
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
|
||||
return ops.get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查键是否存在
|
||||
*
|
||||
* @param key 键
|
||||
* @return 是否存在
|
||||
*/
|
||||
public boolean hasKey(String key) {
|
||||
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除键
|
||||
*
|
||||
* @param key 键
|
||||
*/
|
||||
public void delete(String key) {
|
||||
stringRedisTemplate.delete(key);
|
||||
}
|
||||
}
|
@ -0,0 +1,71 @@
|
||||
//package com.zsc.edu.dify.framework.response;
|
||||
//
|
||||
//import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
//import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
//import jakarta.annotation.Resource;
|
||||
//import lombok.extern.slf4j.Slf4j;
|
||||
//import org.springframework.core.MethodParameter;
|
||||
//import org.springframework.http.HttpHeaders;
|
||||
//import org.springframework.http.MediaType;
|
||||
//import org.springframework.http.converter.HttpMessageConverter;
|
||||
//import org.springframework.http.server.ServerHttpRequest;
|
||||
//import org.springframework.http.server.ServerHttpResponse;
|
||||
//import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
//import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||
//
|
||||
///**
|
||||
// * 响应统一封装
|
||||
// * <p>
|
||||
// * 将响应数据,封装成统一的数据格式。
|
||||
// * <p>
|
||||
// * 通过本处理器,将接口方法返回的数据,统一封装到 ResponseResult 的 data 字段中,如果接口方法返回为 void,则 data 字段的值为 null。
|
||||
// *
|
||||
// * @author zhuang
|
||||
// */
|
||||
//@Slf4j
|
||||
//@RestControllerAdvice(basePackages = "com.zsc.edu.dify")
|
||||
//public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
|
||||
//
|
||||
// @Resource
|
||||
// private ObjectMapper objectMapper;
|
||||
//
|
||||
// /**
|
||||
// * 此组件是否支持给定的控制器方法返回类型和选定的 {@code HttpMessageConverter} 类型。
|
||||
// *
|
||||
// * @return 如果应该调用 {@link #beforeBodyWrite} ,则为 {@code true};否则为false。
|
||||
// */
|
||||
// @Override
|
||||
// public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
|
||||
// // 返回类型不为ResponseResult,才需要封装
|
||||
// return returnType.getParameterType() != ResponseResult.class;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 统一封装返回响应数据
|
||||
// */
|
||||
// @Override
|
||||
// public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
|
||||
// Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
|
||||
// ServerHttpResponse response) {
|
||||
//
|
||||
// // 数据封装为ResponseResult:将接口方法返回的数据,封装到 ResponseResult.data 字段中。
|
||||
// ResponseResult<Object> responseResult = ResponseResult.success(body);
|
||||
//
|
||||
// // 返回类型不是 String:直接返回
|
||||
// if (returnType.getParameterType() != String.class) {
|
||||
// return responseResult;
|
||||
// }
|
||||
//
|
||||
// // 返回类型是 String:不能直接返回,需要进行额外处理
|
||||
// // 1. 将 Content-Type 设为 application/json ;返回类型是String时,默认 Content-Type = text/plain
|
||||
// HttpHeaders headers = response.getHeaders();
|
||||
// headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
// // 2. 将 ResponseResult 转为 Json字符串 再返回
|
||||
// // (否则会报错 java.lang.ClassCastException: com.example.core.model.ResponseResult cannot be cast to java.lang.String)
|
||||
// try {
|
||||
// return objectMapper.writeValueAsString(responseResult);
|
||||
// } catch (JsonProcessingException e) {
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
// }
|
||||
//}
|
@ -0,0 +1,93 @@
|
||||
//package com.zsc.edu.dify.framework.response;
|
||||
//
|
||||
//import lombok.Getter;
|
||||
//
|
||||
///**
|
||||
// * Http状态返回枚举
|
||||
// *
|
||||
// * @author javadog
|
||||
// **/
|
||||
//@Getter
|
||||
//public enum HttpStatusEnum {
|
||||
//
|
||||
//
|
||||
// /**
|
||||
// * 操作成功
|
||||
// */
|
||||
// SUCCESS(200, "操作成功"),
|
||||
// /**
|
||||
// * 对象创建成功
|
||||
// */
|
||||
// CREATED(201, "对象创建成功"),
|
||||
// /**
|
||||
// * 请求已经被接受
|
||||
// */
|
||||
// ACCEPTED(202, "请求已经被接受"),
|
||||
// /**
|
||||
// * 操作已经执行成功,但是没有返回数据
|
||||
// */
|
||||
// NO_CONTENT(204, "操作已经执行成功,但是没有返回数据"),
|
||||
// /**
|
||||
// * 资源已被移除
|
||||
// */
|
||||
// MOVED_PERM(301, "资源已被移除"),
|
||||
// /**
|
||||
// * 重定向
|
||||
// */
|
||||
// SEE_OTHER(303, "重定向"),
|
||||
// /**
|
||||
// * 资源没有被修改
|
||||
// */
|
||||
// NOT_MODIFIED(304, "资源没有被修改"),
|
||||
// /**
|
||||
// * 参数列表错误(缺少,格式不匹配)
|
||||
// */
|
||||
// BAD_REQUEST(400, "参数列表错误(缺少,格式不匹配)"),
|
||||
// /**
|
||||
// * 未授权
|
||||
// */
|
||||
// UNAUTHORIZED(401, "未授权"),
|
||||
// /**
|
||||
// * 访问受限,授权过期
|
||||
// */
|
||||
// FORBIDDEN(403, "访问受限,授权过期"),
|
||||
// /**
|
||||
// * 资源,服务未找到
|
||||
// */
|
||||
// NOT_FOUND(404, "资源,服务未找!"),
|
||||
// /**
|
||||
// * 不允许的http方法
|
||||
// */
|
||||
// BAD_METHOD(405, "不允许的http方法"),
|
||||
// /**
|
||||
// * 资源冲突,或者资源被锁
|
||||
// */
|
||||
// CONFLICT(409, "资源冲突,或者资源被锁"),
|
||||
// /**
|
||||
// * 不支持的数据,媒体类型
|
||||
// */
|
||||
// UNSUPPORTED_TYPE(415, "不支持的数据,媒体类型"),
|
||||
// /**
|
||||
// * 系统内部错误
|
||||
// */
|
||||
// ERROR(500, "系统内部错误"),
|
||||
// /**
|
||||
// * 接口未实现
|
||||
// */
|
||||
// NOT_IMPLEMENTED(501, "接口未实现"),
|
||||
// /**
|
||||
// * 系统警告消息
|
||||
// */
|
||||
// WARN(601, "系统警告消息");
|
||||
//
|
||||
// private final Integer code;
|
||||
// private final String message;
|
||||
//
|
||||
// HttpStatusEnum(Integer code, String message) {
|
||||
//
|
||||
//
|
||||
// this.code = code;
|
||||
// this.message = message;
|
||||
// }
|
||||
//}
|
||||
//
|
@ -0,0 +1,264 @@
|
||||
//package com.zsc.edu.dify.framework.response;
|
||||
//
|
||||
//import lombok.AllArgsConstructor;
|
||||
//import lombok.Data;
|
||||
//import lombok.NoArgsConstructor;
|
||||
//
|
||||
///**
|
||||
// * 返回结果集
|
||||
// *
|
||||
// * @author javadog
|
||||
// **/
|
||||
//@Data
|
||||
//@AllArgsConstructor
|
||||
//@NoArgsConstructor
|
||||
//public class ResponseResult<T> {
|
||||
//
|
||||
// /**
|
||||
// * 状态码
|
||||
// */
|
||||
// private Integer code;
|
||||
//
|
||||
// /**
|
||||
// * 状态信息
|
||||
// */
|
||||
// private Boolean status;
|
||||
//
|
||||
// /**
|
||||
// * 返回信息
|
||||
// */
|
||||
// private String message;
|
||||
//
|
||||
// /**
|
||||
// * 数据
|
||||
// */
|
||||
// private T data;
|
||||
//
|
||||
// /**
|
||||
// * 全参数方法
|
||||
// *
|
||||
// * @param code 状态码
|
||||
// * @param status 状态
|
||||
// * @param message 返回信息
|
||||
// * @param data 返回数据
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// private static <T> ResponseResult<T> response(Integer code, Boolean status, String message, T data) {
|
||||
//
|
||||
//
|
||||
// ResponseResult<T> responseResult = new ResponseResult<>();
|
||||
// responseResult.setCode(code);
|
||||
// responseResult.setStatus(status);
|
||||
// responseResult.setMessage(message);
|
||||
// responseResult.setData(data);
|
||||
// return responseResult;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 全参数方法
|
||||
// *
|
||||
// * @param code 状态码
|
||||
// * @param status 状态
|
||||
// * @param message 返回信息
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// private static <T> ResponseResult<T> response(Integer code, Boolean status, String message) {
|
||||
//
|
||||
//
|
||||
// ResponseResult<T> responseResult = new ResponseResult<>();
|
||||
// responseResult.setCode(code);
|
||||
// responseResult.setStatus(status);
|
||||
// responseResult.setMessage(message);
|
||||
// return responseResult;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 成功返回(无参)
|
||||
// *
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> success() {
|
||||
//
|
||||
//// return response(HttpStatus.OK.value(), true, HttpStatus.OK.getReasonPhrase(), null);
|
||||
// return response(HttpStatusEnum.SUCCESS.getCode(), true, HttpStatusEnum.SUCCESS.getMessage(), null);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 成功返回(枚举参数)
|
||||
// *
|
||||
// * @param httpResponseEnum 枚举参数
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> success(HttpStatusEnum httpResponseEnum) {
|
||||
//
|
||||
//
|
||||
// return response(httpResponseEnum.getCode(), true, httpResponseEnum.getMessage());
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 成功返回(状态码+返回信息)
|
||||
// *
|
||||
// * @param code 状态码
|
||||
// * @param message 返回信息
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> success(Integer code, String message) {
|
||||
//
|
||||
//
|
||||
// return response(code, true, message);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 成功返回(返回信息 + 数据)
|
||||
// *
|
||||
// * @param message 返回信息
|
||||
// * @param data 数据
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> success(String message, T data) {
|
||||
//
|
||||
//
|
||||
// return response(HttpStatusEnum.SUCCESS.getCode(), true, message, data);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 成功返回(状态码+返回信息+数据)
|
||||
// *
|
||||
// * @param code 状态码
|
||||
// * @param message 返回信息
|
||||
// * @param data 数据
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> success(Integer code, String message, T data) {
|
||||
//
|
||||
//
|
||||
// return response(code, true, message, data);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 成功返回(数据)
|
||||
// *
|
||||
// * @param data 数据
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> success(T data) {
|
||||
//
|
||||
//
|
||||
// return response(HttpStatusEnum.SUCCESS.getCode(), true, HttpStatusEnum.SUCCESS.getMessage(), data);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 成功返回(返回信息)
|
||||
// *
|
||||
// * @param message 返回信息
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> success(String message) {
|
||||
//
|
||||
//
|
||||
// return response(HttpStatusEnum.SUCCESS.getCode(), true, message, null);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 失败返回(无参)
|
||||
// *
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> fail() {
|
||||
//
|
||||
//
|
||||
// return response(HttpStatusEnum.ERROR.getCode(), false, HttpStatusEnum.ERROR.getMessage(), null);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 失败返回(枚举)
|
||||
// *
|
||||
// * @param httpResponseEnum 枚举
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> fail(HttpStatusEnum httpResponseEnum) {
|
||||
//
|
||||
//
|
||||
// return response(httpResponseEnum.getCode(), false, httpResponseEnum.getMessage());
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 失败返回(状态码+返回信息)
|
||||
// *
|
||||
// * @param code 状态码
|
||||
// * @param message 返回信息
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> fail(Integer code, String message) {
|
||||
//
|
||||
//
|
||||
// return response(code, false, message);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 失败返回(返回信息+数据)
|
||||
// *
|
||||
// * @param message 返回信息
|
||||
// * @param data 数据
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> fail(String message, T data) {
|
||||
//
|
||||
//
|
||||
// return response(HttpStatusEnum.ERROR.getCode(), false, message, data);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 失败返回(状态码+返回信息+数据)
|
||||
// *
|
||||
// * @param code 状态码
|
||||
// * @param message 返回消息
|
||||
// * @param data 数据
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> fail(Integer code, String message, T data) {
|
||||
//
|
||||
//
|
||||
// return response(code, false, message, data);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 失败返回(数据)
|
||||
// *
|
||||
// * @param data 数据
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> fail(T data) {
|
||||
//
|
||||
//
|
||||
// return response(HttpStatusEnum.ERROR.getCode(), false, HttpStatusEnum.ERROR.getMessage(), data);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 失败返回(返回信息)
|
||||
// *
|
||||
// * @param message 返回信息
|
||||
// * @param <T> 泛型
|
||||
// * @return {@link ResponseResult<T>}
|
||||
// */
|
||||
// public static <T> ResponseResult<T> fail(String message) {
|
||||
//
|
||||
//
|
||||
// return response(HttpStatusEnum.ERROR.getCode(), false, message, null);
|
||||
// }
|
||||
//}
|
@ -0,0 +1,51 @@
|
||||
//package com.zsc.edu.dify.framework.response;
|
||||
//
|
||||
//import lombok.*;
|
||||
//
|
||||
///**
|
||||
// * 返回响应,统一封装实体
|
||||
// *
|
||||
// * @param <T> 数据实体泛型
|
||||
// * @author zhuang
|
||||
// */
|
||||
//@Getter
|
||||
//@ToString
|
||||
//@EqualsAndHashCode
|
||||
//@AllArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
//public class Result<T> {
|
||||
//
|
||||
// private String userMessage;
|
||||
//
|
||||
// /**
|
||||
// * 错误码<br>
|
||||
// * 调用成功时,为 null。<br>
|
||||
// * 示例:A0211
|
||||
// */
|
||||
// private String errorCode;
|
||||
//
|
||||
// /**
|
||||
// * 错误信息<br>
|
||||
// * 调用成功时,为 null。<br>
|
||||
// * 示例:"用户输入密码错误次数超限"
|
||||
// */
|
||||
// private String errorMessage;
|
||||
//
|
||||
// /**
|
||||
// * 数据实体(泛型)<br>
|
||||
// * 当接口没有返回数据时,为 null。
|
||||
// */
|
||||
// private T data;
|
||||
//
|
||||
//
|
||||
// public static <T> Result<T> success(T data) {
|
||||
// return new Result<>("操作成功!", null, null, data);
|
||||
// }
|
||||
//
|
||||
//
|
||||
// public static <T> Result<T> fail(String userMessage, String errorCode, String errorMessage) {
|
||||
// return new Result<>(userMessage, errorCode, errorMessage, null);
|
||||
// }
|
||||
//
|
||||
//}
|
||||
//
|
||||
//
|
@ -0,0 +1,47 @@
|
||||
package com.zsc.edu.dify.framework.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.zsc.edu.dify.exception.ExceptionResult;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.security.web.csrf.MissingCsrfTokenException;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response,
|
||||
AccessDeniedException ex) throws IOException, ServletException {
|
||||
response.setContentType("application/json;charset=utf-8");
|
||||
ExceptionResult result;
|
||||
if (ex instanceof MissingCsrfTokenException) {
|
||||
System.out.println("MissingCsrfTokenException");
|
||||
// 会话已注销,返回401
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
result = new ExceptionResult("凭证已过期,请重新登录", HttpStatus.UNAUTHORIZED.value(),
|
||||
LocalDateTime.now());
|
||||
} else {
|
||||
// 403
|
||||
response.setStatus(HttpStatus.FORBIDDEN.value());
|
||||
result = new ExceptionResult("禁止操作", HttpStatus.FORBIDDEN.value(),
|
||||
LocalDateTime.now());
|
||||
}
|
||||
response.getWriter().print(objectMapper.writeValueAsString(result));
|
||||
response.flushBuffer();
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.zsc.edu.dify.framework.security;///*
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.annotation.Resource;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 认证处理
|
||||
* 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
|
||||
* @author Yao
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
|
||||
@Resource
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("application/json");
|
||||
response.getWriter().println(objectMapper.writeValueAsString(Map.of("msg", "认证失败: " + authException.getMessage())));
|
||||
response.flushBuffer();
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.zsc.edu.dify.framework.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.zsc.edu.dify.exception.ExceptionResult;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
|
||||
AuthenticationException exception) throws IOException {
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
response.setContentType("application/json;charset=utf-8");
|
||||
ExceptionResult result = new ExceptionResult(exception.getMessage(), HttpStatus.UNAUTHORIZED.value(),
|
||||
LocalDateTime.now());
|
||||
response.getWriter().print(objectMapper.writeValueAsString(result));
|
||||
response.flushBuffer();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,45 @@
|
||||
package com.zsc.edu.dify.framework.security;
|
||||
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
|
||||
|
||||
@Override
|
||||
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
|
||||
// response.sendRedirect("/api/rest/user/me");
|
||||
request.getRequestDispatcher("/api/rest/user/me").forward(request, response);
|
||||
// Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
// String sessionId = request.getRequestedSessionId();
|
||||
// String remoteAddr = request.getRemoteAddr();
|
||||
// User user = userService.getOne(((UserDetailsImpl) principal).getId());
|
||||
// String agent = request.getHeader("User-Agent");
|
||||
// UserAgent userAgent = new UserAgent(agent);
|
||||
// OnlineUser onlineUser = onlineUserService.create(
|
||||
// sessionId,
|
||||
// user.username,
|
||||
// user.name,
|
||||
// null,//user.identity.dept.name,
|
||||
// remoteAddr,
|
||||
// userAgent.getBrowser().getName(),
|
||||
// userAgent.getOperatingSystem().getName(),
|
||||
// LocalDateTime.now()
|
||||
// );
|
||||
// loginLogService.create(onlineUser.username, onlineUser.name, onlineUser.deptName,
|
||||
// onlineUser.ip, onlineUser.browser, onlineUser.os,
|
||||
// onlineUser.loginTime, LoginLog.Result.登陆成功);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.zsc.edu.dify.framework.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.web.session.SessionInformationExpiredEvent;
|
||||
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Component
|
||||
public class CustomSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
|
||||
@Override
|
||||
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
|
||||
|
||||
HttpServletResponse response = event.getResponse();
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
response.setContentType("application/json;charset=utf-8");
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
response.getWriter().print(objectMapper.writeValueAsString(Map.of(
|
||||
"msg", "会话已过期(有可能是您同时登录了太多的太多的客户端)",
|
||||
"code", HttpStatus.UNAUTHORIZED.value(),
|
||||
"timestamp", LocalDateTime.now()
|
||||
)));
|
||||
response.flushBuffer();
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package com.zsc.edu.dify.framework.security;
|
||||
|
||||
import com.zsc.edu.dify.common.util.TreeUtil;
|
||||
import com.zsc.edu.dify.exception.StateException;
|
||||
import com.zsc.edu.dify.modules.system.entity.*;
|
||||
import com.zsc.edu.dify.modules.system.repo.*;
|
||||
import com.zsc.edu.dify.modules.system.service.DeptService;
|
||||
import com.zsc.edu.dify.modules.system.service.RoleService;
|
||||
import lombok.AllArgsConstructor;
|
||||
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 org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class JpaUserDetailsServiceImpl implements UserDetailsService {
|
||||
|
||||
private final UserRepository userRepo;
|
||||
private final AuthorityRepository authorityRepository;
|
||||
private final MenuRepository menuRepository;
|
||||
private final DeptService deptService;
|
||||
private final RoleRepository roleRepository;
|
||||
private final RoleService roleService;
|
||||
private final UserRolesRepository userRolesRepository;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
User user = userRepo.selectByUsername(username);
|
||||
if (!user.getEnableState()) {
|
||||
throw new StateException("用户 '" + username + "' 已被禁用!请联系管理员");
|
||||
}
|
||||
List<Long> roleIds = userRolesRepository.selectByUserId(user.getId());
|
||||
List<Role> roles = roleRepository.selectByIds(roleIds);
|
||||
user.setRoles(roles);
|
||||
List<Dept> depts = deptService.listTree(user.deptId);
|
||||
List<Dept> flat = TreeUtil.flat(depts, Dept::getChildren, d -> d.setChildren(null));
|
||||
Set<Long> dataScopeDeptIds = flat.stream().map(Dept::getId).collect(Collectors.toSet());
|
||||
user.setDataScopeDeptIds(dataScopeDeptIds);
|
||||
// List<RoleAuthority> roleAuthorities= roleAuthoritiesRepository.selectByRoleId(user.getRoleId());
|
||||
// user.role.authorities = authorityRepository.selectAuthoritiesByRoleId(user.getRoleId());
|
||||
List<Menu> menus = menuRepository.selectByRoleId(user.getRoleId());
|
||||
Set<String> permissions = menus.stream().map(Menu::getPermissions).collect(Collectors.toSet());
|
||||
return UserDetailsImpl.from(user, permissions);
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.zsc.edu.dify.framework.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.AuthenticationServiceException;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
public class JsonAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
|
||||
|
||||
@Override
|
||||
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
|
||||
throws AuthenticationException {
|
||||
if (!request.getMethod().equals("POST")) {
|
||||
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
|
||||
}
|
||||
if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
|
||||
try {
|
||||
Map map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
|
||||
String username = map.get("username").toString();
|
||||
String password = map.get("password").toString();
|
||||
username = (username != null) ? username : "";
|
||||
username = username.trim();
|
||||
password = (password != null) ? password : "";
|
||||
password = password.trim();
|
||||
UsernamePasswordAuthenticationToken authRequest =
|
||||
UsernamePasswordAuthenticationToken.unauthenticated(username, password);
|
||||
// Allow subclasses to set the "details" property
|
||||
setDetails(request, authRequest);
|
||||
return this.getAuthenticationManager().authenticate(authRequest);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return super.attemptAuthentication(request, response);
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.zsc.edu.dify.framework.security;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.core.session.SessionRegistry;
|
||||
import org.springframework.security.core.session.SessionRegistryImpl;
|
||||
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.session.HttpSessionEventPublisher;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Configuration
|
||||
public class SecurityBeanConfig {
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SessionRegistry sessionRegistry() {
|
||||
return new SessionRegistryImpl();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public HttpSessionEventPublisher httpSessionEventPublisher() {
|
||||
return new HttpSessionEventPublisher();
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.zsc.edu.dify.framework.security;
|
||||
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* @author Yao
|
||||
*/
|
||||
public class SecurityUtil {
|
||||
|
||||
public static UserDetailsImpl getUserInfo() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (Objects.isNull(authentication)) {
|
||||
return new UserDetailsImpl();
|
||||
}
|
||||
return (UserDetailsImpl) authentication.getPrincipal();
|
||||
}
|
||||
|
||||
public static void setUserInfo(UserDetailsImpl user) {
|
||||
// 重新加载用户信息并更新SecurityContext
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities())
|
||||
);
|
||||
}
|
||||
|
||||
public static Optional<String> getCurrentAuditor() {
|
||||
try {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication instanceof AnonymousAuthenticationToken) {
|
||||
return Optional.of("system");
|
||||
} else {
|
||||
if (authentication == null) {
|
||||
return Optional.of("system");
|
||||
}
|
||||
UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
|
||||
return Optional.of(user.getUsername());
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
// log.error("get user Authentication failed: " + ex.getMessage(), ex);
|
||||
return Optional.of("system");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,148 @@
|
||||
package com.zsc.edu.dify.framework.security;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.ProviderManager;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.core.session.SessionRegistry;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
|
||||
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@EnableMethodSecurity
|
||||
@Configuration
|
||||
public class SpringSecurityConfig {
|
||||
|
||||
private final UserDetailsService userDetailsService;
|
||||
private final CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
|
||||
private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
|
||||
private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
|
||||
private final CustomAccessDeniedHandler customAccessDeniedHandler;
|
||||
private final SessionRegistry sessionRegistry;
|
||||
private final SecurityBeanConfig securityBeanConfig;
|
||||
private final CustomSessionInformationExpiredStrategy customSessionInformationExpiredStrategy;
|
||||
|
||||
@Resource
|
||||
private final DataSource dataSource;
|
||||
|
||||
// @Bean
|
||||
// public BCryptPasswordEncoder bCryptPasswordEncoder() {
|
||||
// return new BCryptPasswordEncoder();
|
||||
// };
|
||||
|
||||
@Bean
|
||||
public PersistentTokenRepository persistentTokenRepository() {
|
||||
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
|
||||
tokenRepository.setDataSource(dataSource);
|
||||
return tokenRepository;
|
||||
|
||||
}
|
||||
|
||||
@Bean
|
||||
AuthenticationManager authenticationManager() {
|
||||
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
|
||||
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
|
||||
daoAuthenticationProvider.setPasswordEncoder(securityBeanConfig.passwordEncoder());
|
||||
return new ProviderManager(daoAuthenticationProvider);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JsonAuthenticationFilter jsonAuthenticationFilter() throws Exception {
|
||||
JsonAuthenticationFilter filter = new JsonAuthenticationFilter();
|
||||
filter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
|
||||
filter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);
|
||||
filter.setFilterProcessesUrl("/api/rest/user/login");
|
||||
filter.setAuthenticationManager(authenticationManager());
|
||||
// 将登录后的请求信息保存到Session中,不然会报null
|
||||
filter.setSecurityContextRepository(new HttpSessionSecurityContextRepository());
|
||||
return filter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
|
||||
return http
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers(HttpMethod.GET, "/api/rest/user/menu","/api/rest/user/register","/api/rest/user/send-email").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/rest/user/login","/api/rest/user/register").permitAll()
|
||||
.requestMatchers("/api/rest/user/me").permitAll()
|
||||
.requestMatchers("/api/**").authenticated()
|
||||
)
|
||||
// 不用注解,直接通过判断路径实现动态访问权限
|
||||
// .requestMatchers("/api/**").access((authentication, object) -> {
|
||||
// //表示请求的 URL 地址和数据库的地址是否匹配上了
|
||||
// boolean isMatch = false;
|
||||
// //获取当前请求的 URL 地址
|
||||
// String requestURI = object.getRequest().getRequestURI();
|
||||
// List<MenuWithRoleVO> menuWithRole = menuService.getMenuWithRole();
|
||||
// for (MenuWithRoleVO m : menuWithRole) {
|
||||
// AntPathMatcher antPathMatcher = new AntPathMatcher();
|
||||
// if (antPathMatcher.match(m.getUrl(), requestURI)) {
|
||||
// isMatch = true;
|
||||
// //说明找到了请求的地址了
|
||||
// //这就是当前请求需要的角色
|
||||
// List<Role> roles = m.getRoles();
|
||||
// //获取当前登录用户的角色
|
||||
// Collection<? extends GrantedAuthority> authorities = authentication.get().getAuthorities();
|
||||
// for (GrantedAuthority authority : authorities) {
|
||||
// for (Role role : roles) {
|
||||
// if (authority.getAuthority().equals(role.getName())) {
|
||||
// //说明当前登录用户具备当前请求所需要的角色
|
||||
// return new AuthorizationDecision(true);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// if (!isMatch) {
|
||||
// //说明请求的 URL 地址和数据库的地址没有匹配上,对于这种请求,统一只要登录就能访问
|
||||
// if (authentication.get() instanceof AnonymousAuthenticationToken) {
|
||||
// return new AuthorizationDecision(false);
|
||||
// } else {
|
||||
// //说明用户已经认证了
|
||||
// return new AuthorizationDecision(true);
|
||||
// }
|
||||
// }
|
||||
// return new AuthorizationDecision(false);
|
||||
// }))
|
||||
.addFilterAt(jsonAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
|
||||
.formLogin(form -> form
|
||||
.loginPage("/user/login")
|
||||
.loginProcessingUrl("/api/rest/user/login")
|
||||
.successHandler(customAuthenticationSuccessHandler)
|
||||
.failureHandler(customAuthenticationFailureHandler))
|
||||
.logout(logout -> logout
|
||||
.logoutUrl("/api/user/logout")
|
||||
.logoutSuccessHandler((request, response, authentication) -> {}))
|
||||
// 添加自定义未授权和未登录结果返回
|
||||
.exceptionHandling(exception -> exception
|
||||
.authenticationEntryPoint(customAuthenticationEntryPoint)
|
||||
.accessDeniedHandler(customAccessDeniedHandler)
|
||||
)
|
||||
.rememberMe(rememberMe -> rememberMe
|
||||
.userDetailsService(userDetailsService)
|
||||
.tokenRepository(persistentTokenRepository()))
|
||||
.csrf(csrf -> csrf.ignoringRequestMatchers("/api/internal/**", "/api/rest/user/logout","/api/rest/user/register"))
|
||||
.sessionManagement(session -> session
|
||||
.maximumSessions(3)
|
||||
.sessionRegistry(sessionRegistry)
|
||||
.expiredSessionStrategy(customSessionInformationExpiredStrategy))
|
||||
.build();
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,101 @@
|
||||
package com.zsc.edu.dify.framework.security;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.zsc.edu.dify.modules.system.entity.Authority;
|
||||
import com.zsc.edu.dify.modules.system.entity.Dept;
|
||||
import com.zsc.edu.dify.modules.system.entity.Role;
|
||||
import com.zsc.edu.dify.modules.system.entity.User;
|
||||
import lombok.*;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @author harry yao
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@JsonIgnoreProperties("password")
|
||||
public class UserDetailsImpl implements UserDetails {
|
||||
|
||||
public Long id;
|
||||
public String username;
|
||||
public String password;
|
||||
public Boolean enableState;
|
||||
public String name;
|
||||
public Dept dept;
|
||||
public Role role;
|
||||
public List<Role> roles;
|
||||
public Set<Authority> authorities;
|
||||
public Set<String> permissions;
|
||||
public Set<Long> dataScopeDeptIds;
|
||||
public Long deptId;
|
||||
public Long createId;
|
||||
|
||||
public UserDetailsImpl(Long id, String username, String password, String name, Boolean enableState, Dept dept, Set<Long> dataScopeDeptIds, Role role, Set<Authority> authorities, Set<String> permissions, List<Role> roles, Long deptId, Long createId) {
|
||||
this.id = id;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.enableState = enableState;
|
||||
this.name = name;
|
||||
this.dept = dept;
|
||||
this.dataScopeDeptIds = dataScopeDeptIds;
|
||||
this.role = role;
|
||||
this.authorities = authorities;
|
||||
this.permissions = permissions;
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public static UserDetailsImpl from(User user, Set<String> permissions) {
|
||||
return new UserDetailsImpl(
|
||||
user.id,
|
||||
user.username,
|
||||
user.password,
|
||||
user.name,
|
||||
user.enableState,
|
||||
user.dept,
|
||||
user.dataScopeDeptIds,
|
||||
user.role,
|
||||
user.role.authorities,
|
||||
permissions,
|
||||
user.roles,
|
||||
user.deptId,
|
||||
user.createId
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
// return authorities.stream().map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toSet());
|
||||
return permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return enableState;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.zsc.edu.dify.framework.storage;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@ConfigurationProperties("storage")
|
||||
@Component
|
||||
public class StorageProperties {
|
||||
|
||||
/**
|
||||
* 附件存储路径
|
||||
*/
|
||||
@Value("${storage.attachment}")
|
||||
public String attachment;
|
||||
|
||||
/**
|
||||
* 临时文件存储路径
|
||||
*/
|
||||
@Value("${storage.temp}")
|
||||
public String temp;
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.zsc.edu.dify.framework.storage.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public class StorageException extends RuntimeException {
|
||||
|
||||
public StorageException() {
|
||||
super("文件存储出错");
|
||||
}
|
||||
|
||||
public StorageException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public StorageException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.zsc.edu.dify.framework.storage.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public class StorageFileEmptyException extends StorageException {
|
||||
|
||||
public StorageFileEmptyException() {
|
||||
super("存储的是空文件!");
|
||||
}
|
||||
|
||||
public StorageFileEmptyException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public StorageFileEmptyException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.zsc.edu.dify.framework.storage.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||
public class StorageFileNotFoundException extends StorageException {
|
||||
|
||||
public StorageFileNotFoundException() {
|
||||
super("文件不存在!");
|
||||
}
|
||||
|
||||
public StorageFileNotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public StorageFileNotFoundException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
@ -0,0 +1,107 @@
|
||||
package com.zsc.edu.dify.modules.attachment.controller;
|
||||
|
||||
import com.zsc.edu.dify.exception.StorageException;
|
||||
import com.zsc.edu.dify.modules.attachment.entity.Attachment;
|
||||
import com.zsc.edu.dify.modules.attachment.service.AttachmentService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.ContentDisposition;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 附件Controller
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("api/rest/attachment")
|
||||
public class AttachmentController {
|
||||
|
||||
private final AttachmentService service;
|
||||
|
||||
/**
|
||||
* 上传附件
|
||||
*
|
||||
* @param type 附件功能类型
|
||||
* @param file 文件
|
||||
* @return 附件信息
|
||||
*/
|
||||
@PostMapping()
|
||||
public Attachment upload(
|
||||
@RequestParam(required = false, defaultValue = "其他") Attachment.Type type,
|
||||
@RequestParam("file") MultipartFile file
|
||||
) {
|
||||
try {
|
||||
if (type == null) {
|
||||
type = Attachment.Type.其他;
|
||||
}
|
||||
return service.store(type, file);
|
||||
} catch (IOException e) {
|
||||
throw new StorageException("文件上传出错");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载附件
|
||||
*
|
||||
* @param id 附件ID
|
||||
* @return 附件文件内容
|
||||
*/
|
||||
@GetMapping("{id}")
|
||||
public ResponseEntity<Resource> download(
|
||||
@PathVariable("id") String id
|
||||
) {
|
||||
Attachment.Wrapper wrapper = service.loadAsWrapper(id);
|
||||
if (wrapper.attachment.fileName != null) {
|
||||
ContentDisposition contentDisposition = ContentDisposition.builder("attachment").filename(wrapper.attachment.fileName, StandardCharsets.UTF_8).build();
|
||||
return ResponseEntity.ok().
|
||||
header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString()).
|
||||
header(HttpHeaders.CONTENT_TYPE, wrapper.attachment.mimeType).
|
||||
body(wrapper.resource);
|
||||
}
|
||||
return ResponseEntity.ok(wrapper.resource);
|
||||
}
|
||||
/**
|
||||
* 根据附件ID获取附件信息
|
||||
* */
|
||||
@GetMapping("find/{id}")
|
||||
public Attachment getAttachmentInfo(@PathVariable("id") String id) {
|
||||
return service.getById(id);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 批量上传附件
|
||||
*/
|
||||
@PostMapping("multipartFile")
|
||||
public List<Attachment> uploadMultipleFiles(
|
||||
@RequestParam(defaultValue = "其他") Attachment.Type type,
|
||||
@RequestParam("files") List<MultipartFile> files
|
||||
) throws IOException {
|
||||
List<Attachment> attachments = new ArrayList<>();
|
||||
for (MultipartFile file : files) {
|
||||
if (!file.isEmpty()) {
|
||||
attachments.add(service.stores(type, file));
|
||||
}
|
||||
}
|
||||
return attachments;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据附件ID删除附件信息
|
||||
*/
|
||||
@DeleteMapping("delete/{id}")
|
||||
public Boolean delete(@PathVariable("id") String id) {
|
||||
return service.delete(id);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
package com.zsc.edu.dify.modules.attachment.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author ftz
|
||||
* 创建时间:29/1/2024 上午10:00
|
||||
* 描述: 附件Dto
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AttachmentDto {
|
||||
/**
|
||||
* 文件名 文件名详细说明
|
||||
*/
|
||||
|
||||
private String saveFilename;
|
||||
|
||||
/**
|
||||
* 文件UUID 返回给前端的文件UUID
|
||||
*/
|
||||
|
||||
private String uuid;
|
||||
|
||||
/**
|
||||
* 上传时的文件名 原文件名
|
||||
*/
|
||||
|
||||
private String originFilename;
|
||||
|
||||
/**
|
||||
* 文件大小
|
||||
*/
|
||||
|
||||
private Long fileSize;
|
||||
|
||||
/**
|
||||
* 文件类型
|
||||
*/
|
||||
|
||||
private String fileType;
|
||||
|
||||
/**
|
||||
* 文件扩展名
|
||||
*/
|
||||
|
||||
private String extendName;
|
||||
|
||||
/**
|
||||
* 票据id 附件对应的票据id
|
||||
*/
|
||||
|
||||
private Long ticketId;
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
*文件url
|
||||
*/
|
||||
|
||||
private String fileUrl;
|
||||
}
|
@ -0,0 +1,98 @@
|
||||
package com.zsc.edu.dify.modules.attachment.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import lombok.*;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 附件
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@TableName(value ="attachment")
|
||||
public class Attachment implements Serializable {
|
||||
|
||||
/**
|
||||
* ID,用文件和文件名的SHA-1值生成
|
||||
*/
|
||||
@TableId
|
||||
public String id;
|
||||
|
||||
/**
|
||||
* 文件名
|
||||
*/
|
||||
|
||||
public String fileName;
|
||||
|
||||
/**
|
||||
* 附件作用类型
|
||||
*/
|
||||
|
||||
public String mimeType;
|
||||
|
||||
/**
|
||||
* 附件功能类型
|
||||
*/
|
||||
// @Column(nullable = false)
|
||||
// @Enumerated(EnumType.STRING)
|
||||
// public Type type = Type.其他;
|
||||
|
||||
/**
|
||||
* 文件上传时间
|
||||
*/
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
public LocalDateTime uploadTime;
|
||||
|
||||
/**
|
||||
* 文件下载链接
|
||||
*/
|
||||
@JsonSerialize
|
||||
@TableField(exist = false)
|
||||
public String url;
|
||||
|
||||
public Attachment(String id, String fileName, String mimeType, Type type, LocalDateTime uploadTime) {
|
||||
this.id = id;
|
||||
this.fileName = fileName;
|
||||
this.mimeType = mimeType;
|
||||
// this.type = type;
|
||||
this.uploadTime = uploadTime;
|
||||
this.url = "/api/rest/attachment/" + id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
this.url = "/api/rest/attachment/" + id;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return "/api/rest/attachment/" + id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 枚举类:附件功能类型
|
||||
*/
|
||||
public enum Type {
|
||||
其他,
|
||||
头像
|
||||
}
|
||||
|
||||
@AllArgsConstructor
|
||||
public static final class Wrapper {
|
||||
|
||||
public Attachment attachment;
|
||||
|
||||
public FileSystemResource resource;
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.zsc.edu.dify.modules.attachment.repo;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.zsc.edu.dify.modules.attachment.entity.Attachment;
|
||||
|
||||
/**
|
||||
* @author ftz
|
||||
* 创建时间:29/1/2024 上午9:55
|
||||
*/
|
||||
public interface AttachmentRepository extends BaseMapper<Attachment>{
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.zsc.edu.dify.modules.attachment.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.zsc.edu.dify.modules.attachment.entity.Attachment;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author fantianzhi
|
||||
* @description 针对表【attach_file(票据附件表)】的数据库操作Service
|
||||
* @createDate 2024-01-28 19:48:22
|
||||
*/
|
||||
public interface AttachmentService extends IService<Attachment> {
|
||||
|
||||
Attachment store(Attachment.Type type, MultipartFile file) throws IOException;
|
||||
Attachment stores(Attachment.Type type, MultipartFile file)throws IOException;
|
||||
|
||||
Resource loadAsResource(String id);
|
||||
|
||||
Attachment.Wrapper loadAsWrapper(String id);
|
||||
|
||||
List<Attachment> selectList(List<String> dis);
|
||||
|
||||
Boolean delete(String id);
|
||||
}
|
@ -0,0 +1,223 @@
|
||||
package com.zsc.edu.dify.modules.attachment.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.zsc.edu.dify.framework.storage.StorageProperties;
|
||||
import com.zsc.edu.dify.framework.storage.exception.StorageFileEmptyException;
|
||||
import com.zsc.edu.dify.framework.storage.exception.StorageFileNotFoundException;
|
||||
import com.zsc.edu.dify.modules.attachment.entity.Attachment;
|
||||
import com.zsc.edu.dify.modules.attachment.repo.AttachmentRepository;
|
||||
import com.zsc.edu.dify.modules.attachment.service.AttachmentService;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.apache.tika.Tika;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 附件Service
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Service
|
||||
public class AttachmentServiceImpl extends ServiceImpl<AttachmentRepository, Attachment> implements AttachmentService {
|
||||
|
||||
final static int[] illegalChars = {34, 60, 62, 124, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 58, 42, 63, 92, 47};
|
||||
|
||||
private final AttachmentRepository repo;
|
||||
private final Path attachmentPath;
|
||||
private final Path tempPath;
|
||||
|
||||
public AttachmentServiceImpl(AttachmentRepository repo, StorageProperties storageProperties) {
|
||||
this.repo = repo;
|
||||
this.attachmentPath = Paths.get(storageProperties.attachment);
|
||||
this.tempPath = Paths.get(storageProperties.temp);
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void init() throws IOException {
|
||||
if (Files.notExists(attachmentPath)) {
|
||||
Files.createDirectories(attachmentPath);
|
||||
}
|
||||
if (Files.notExists(tempPath)) {
|
||||
Files.createDirectories(tempPath);
|
||||
}
|
||||
}
|
||||
|
||||
public Attachment store(Attachment.Type type, MultipartFile file) throws IOException {
|
||||
if (file.isEmpty()) {
|
||||
throw new StorageFileEmptyException();
|
||||
}
|
||||
MessageDigest digest = DigestUtils.getSha1Digest();
|
||||
String filename = file.getOriginalFilename();
|
||||
if (filename != null) {
|
||||
digest.update(filename.getBytes());
|
||||
}
|
||||
Path temp = tempPath.resolve(String.valueOf(System.nanoTime()));
|
||||
byte[] fileContent = file.getBytes();
|
||||
ByteArrayInputStream input = new ByteArrayInputStream(fileContent);
|
||||
Tika tika = new Tika();
|
||||
String mimeType = tika.detect(input, filename);
|
||||
OutputStream output = Files.newOutputStream(temp);
|
||||
digest.update(fileContent);
|
||||
output.write(fileContent);
|
||||
input.close();
|
||||
output.flush();
|
||||
output.close();
|
||||
String sha1 = Hex.encodeHexString(digest.digest());
|
||||
return save(temp, sha1, filename, mimeType, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Attachment stores(Attachment.Type type, MultipartFile file) throws IOException{
|
||||
if (file.isEmpty()) {
|
||||
throw new StorageFileEmptyException("上传的文件不能为空");
|
||||
}
|
||||
|
||||
String filename = file.getOriginalFilename();
|
||||
if (filename == null || filename.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("文件名不能为空");
|
||||
}
|
||||
|
||||
MessageDigest digest = DigestUtils.getSha1Digest();
|
||||
digest.update(filename.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
Path temp = tempPath.resolve(String.valueOf(System.nanoTime()));
|
||||
byte[] fileContent = file.getBytes();
|
||||
|
||||
// 使用try-with-resources自动关闭流
|
||||
try (ByteArrayInputStream input = new ByteArrayInputStream(fileContent);
|
||||
OutputStream output = Files.newOutputStream(temp)) {
|
||||
Tika tika = new Tika();
|
||||
String mimeType = tika.detect(input, filename);
|
||||
digest.update(fileContent);
|
||||
output.write(fileContent);
|
||||
String sha1 = Hex.encodeHexString(digest.digest());
|
||||
return save(temp, sha1, filename, mimeType, type);
|
||||
}
|
||||
|
||||
}
|
||||
public Attachment store(Attachment.Type type, File file) throws IOException {
|
||||
MessageDigest digest = DigestUtils.getSha1Digest();
|
||||
String filename = file.getName();
|
||||
if (filename != null) {
|
||||
digest.update(filename.getBytes());
|
||||
}
|
||||
Tika tika = new Tika();
|
||||
String mimeType = tika.detect(file);
|
||||
String sha1 = Hex.encodeHexString(digest.digest());
|
||||
return save(file.toPath(), sha1, filename, mimeType, type);
|
||||
}
|
||||
|
||||
public Attachment store(Attachment.Type type, Path file) throws IOException {
|
||||
String filename = file.getFileName().toString();
|
||||
MessageDigest digest = DigestUtils.getSha1Digest();
|
||||
if (StringUtils.hasText(filename)) {
|
||||
digest.update(filename.getBytes());
|
||||
}
|
||||
Tika tika = new Tika();
|
||||
String mimeType = tika.detect(file);
|
||||
InputStream input = Files.newInputStream(file);
|
||||
byte[] buf = new byte[8192];
|
||||
int n;
|
||||
while ((n = input.read(buf)) > 0) {
|
||||
digest.update(buf, 0, n);
|
||||
}
|
||||
String sha1 = Hex.encodeHexString(digest.digest());
|
||||
return save(file, sha1, filename, mimeType, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Resource loadAsResource(String id) {
|
||||
Path file = attachmentPath.resolve(id);
|
||||
FileSystemResource resource = new FileSystemResource(file);
|
||||
if (resource.exists() || resource.isReadable()) {
|
||||
return resource;
|
||||
} else {
|
||||
throw new StorageFileNotFoundException();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Attachment.Wrapper loadAsWrapper(String id) {
|
||||
Path file = attachmentPath.resolve(id);
|
||||
FileSystemResource resource = new FileSystemResource(file);
|
||||
if (!resource.exists() || !resource.isReadable()) {
|
||||
throw new StorageFileNotFoundException();
|
||||
}
|
||||
Attachment attachment = repo.selectById(id); //.orElseThrow(NotExistException::new);
|
||||
return new Attachment.Wrapper(attachment, resource);
|
||||
}
|
||||
|
||||
public Attachment findById(String id) {
|
||||
return repo.selectById(id); //.orElseThrow(NotExistException::new);
|
||||
}
|
||||
|
||||
public List<Attachment> findAllById(Collection<String> ids) {
|
||||
return (ids != null && !ids.isEmpty()) ? repo.selectList(new LambdaQueryWrapper<Attachment>().in(Attachment::getId, ids)) : new ArrayList<>();
|
||||
}
|
||||
|
||||
public Path convertToTempPath(String fileName) {
|
||||
fileName = fileName.replace("/", "");
|
||||
Path path;
|
||||
try {
|
||||
path = tempPath.resolve(fileName);
|
||||
} catch (Exception e) {
|
||||
StringBuilder cleanName = new StringBuilder();
|
||||
for (int i = 0; i < fileName.length(); i++) {
|
||||
int c = fileName.charAt(i);
|
||||
if (Arrays.binarySearch(illegalChars, c) < 0) {
|
||||
cleanName.append((char) c);
|
||||
}
|
||||
}
|
||||
path = tempPath.resolve(cleanName.toString());
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private Attachment save(Path temp, String id, String filename, String mimeType, Attachment.Type type) throws IOException {
|
||||
Path dest = attachmentPath.resolve(id);
|
||||
if (Files.exists(dest)) {
|
||||
return findById(id);
|
||||
}
|
||||
Files.move(temp, dest);
|
||||
Attachment attachment = new Attachment(id, filename, mimeType, type, LocalDateTime.now());
|
||||
repo.insert(attachment);
|
||||
return attachment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Attachment> selectList(List<String> dis) {
|
||||
return repo.selectList(new LambdaQueryWrapper<Attachment>().in(Attachment::getId, dis));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean delete(String id) {
|
||||
if (Files.exists(attachmentPath.resolve(id))) {
|
||||
try {
|
||||
repo.deleteById(id);
|
||||
Files.delete(attachmentPath.resolve(id));
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
log.error("删除文件失败", e);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
@ -0,0 +1,155 @@
|
||||
package com.zsc.edu.dify.modules.message.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.zsc.edu.dify.framework.mybatisplus.DataPermission;
|
||||
import com.zsc.edu.dify.framework.security.UserDetailsImpl;
|
||||
import com.zsc.edu.dify.modules.message.dto.BulletinDto;
|
||||
import com.zsc.edu.dify.modules.message.entity.Bulletin;
|
||||
import com.zsc.edu.dify.modules.message.query.BulletinQuery;
|
||||
import com.zsc.edu.dify.modules.message.service.BulletinService;
|
||||
import com.zsc.edu.dify.modules.message.vo.BulletinVo;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 公告Controller
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/rest/bulletin")
|
||||
public class BulletinController {
|
||||
|
||||
private final BulletinService service;
|
||||
/**
|
||||
* 普通用户查看公告详情
|
||||
*
|
||||
* @param id ID
|
||||
* @return 公告
|
||||
*/
|
||||
@GetMapping("/self/{id}")
|
||||
public BulletinVo selfDetail(@AuthenticationPrincipal UserDetailsImpl userDetails, @PathVariable("id") Long id) {
|
||||
return service.detail(userDetails,id, Bulletin.State.publish);
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通用户分页查询公告
|
||||
*
|
||||
* @param query 查询表单
|
||||
* @return 分页数据
|
||||
*/
|
||||
@DataPermission
|
||||
@GetMapping("/self")
|
||||
public Page<Bulletin> getBulletins(Page<Bulletin> page, BulletinQuery query) {
|
||||
query.setState(Bulletin.State.publish);
|
||||
return service.page(page, query.wrapper());
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理查询公告详情
|
||||
*
|
||||
* @param id ID
|
||||
* @return 公告
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
@PreAuthorize("hasAuthority('message:bulletin:query')")
|
||||
public BulletinVo detail(@AuthenticationPrincipal UserDetailsImpl userDetails, @PathVariable("id") Long id) {
|
||||
return service.detail(userDetails,id, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员分页查询公告
|
||||
*
|
||||
* @param query 查询参数
|
||||
* @return 分页数据
|
||||
*/
|
||||
@DataPermission
|
||||
@GetMapping
|
||||
@PreAuthorize("hasAuthority('message:bulletin:query')")
|
||||
public Page<Bulletin> query(Page<Bulletin> page, BulletinQuery query) {
|
||||
return service.page(page, query.wrapper());
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建公告
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param dto 表单数据
|
||||
* @return 公告
|
||||
*/
|
||||
@PostMapping
|
||||
@PreAuthorize("hasAuthority('message:bulletin:create')")
|
||||
public Bulletin create(@AuthenticationPrincipal UserDetailsImpl userDetails, @RequestBody BulletinDto dto) {
|
||||
return service.create(userDetails, dto);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新公告,只能修改"编辑中"或"已发布"的公告,"已发布"的公告修改后会改为"编辑中"
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param dto 表单数据
|
||||
* @param id ID
|
||||
* @return 公告
|
||||
*/
|
||||
@PatchMapping("/{id}")
|
||||
@PreAuthorize("hasAuthority('message:bulletin:update')")
|
||||
public Boolean update(@AuthenticationPrincipal UserDetailsImpl userDetails, @RequestBody BulletinDto dto, @PathVariable("id") Long id) {
|
||||
return service.update(userDetails, dto, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换公告置顶状态
|
||||
*
|
||||
* @param id ID
|
||||
* @return 公告
|
||||
*/
|
||||
@PatchMapping("/{id}/toggle-top")
|
||||
@PreAuthorize("hasAuthority('message:bulletin:update')")
|
||||
public Boolean toggleTop(@PathVariable("id") Long id) {
|
||||
return service.toggleTop(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布公告,只能发布"编辑中"的公告
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param ids IDs
|
||||
* @return 公告
|
||||
*/
|
||||
@PatchMapping("/publish")
|
||||
@PreAuthorize("hasAuthority('message:bulletin:update')")
|
||||
public Boolean publish(@AuthenticationPrincipal UserDetailsImpl userDetails, @RequestBody List<Long> ids) {
|
||||
return service.publish(userDetails, ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭公告,只能关闭"已发布"的公告
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param id ID
|
||||
* @return 公告
|
||||
*/
|
||||
@PatchMapping("/{id}/toggleClose")
|
||||
@PreAuthorize("hasAuthority('message:bulletin:update')")
|
||||
public Boolean toggleClose(@AuthenticationPrincipal UserDetailsImpl userDetails, @PathVariable("id") Long id) {
|
||||
return service.close(userDetails, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除公告,只能删除"编辑中"的公告
|
||||
*
|
||||
* @param id ID
|
||||
* @return 公
|
||||
*/
|
||||
@DeleteMapping("/{id}")
|
||||
@PreAuthorize("hasAuthority('message:bulletin:delete')")
|
||||
public Boolean delete(@PathVariable("id") Long id) {
|
||||
return service.delete(id);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,128 @@
|
||||
package com.zsc.edu.dify.modules.message.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.zsc.edu.dify.framework.mybatisplus.DataPermission;
|
||||
import com.zsc.edu.dify.framework.security.UserDetailsImpl;
|
||||
import com.zsc.edu.dify.modules.message.dto.UserNoticeDto;
|
||||
import com.zsc.edu.dify.modules.message.query.AdminNoticeQuery;
|
||||
import com.zsc.edu.dify.modules.message.query.UserNoticeQuery;
|
||||
import com.zsc.edu.dify.modules.message.service.UserNoticeService;
|
||||
import com.zsc.edu.dify.modules.message.vo.AdminNoticeVo;
|
||||
import com.zsc.edu.dify.modules.message.vo.UserNoticeVo;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户消息Controller
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("api/rest/notice")
|
||||
public class UserNoticeController {
|
||||
|
||||
private final UserNoticeService service;
|
||||
|
||||
/**
|
||||
* 普通用户查看消息详情
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param noticeId 消息ID
|
||||
* @return 用户消息详情
|
||||
*/
|
||||
@GetMapping("/self/{noticeId}")
|
||||
public UserNoticeVo selfDetail(@AuthenticationPrincipal UserDetailsImpl userDetails, @PathVariable("noticeId") Long noticeId) {
|
||||
return service.detail(noticeId, userDetails.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通用户分页查询消息,不能设置查询参数userId和username
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param query 查询参数
|
||||
* @return 分页数据
|
||||
*/
|
||||
@GetMapping("/self")
|
||||
public IPage<UserNoticeVo> selfPage(Page<UserNoticeVo> pageParam, @AuthenticationPrincipal UserDetailsImpl userDetails, UserNoticeQuery query) {
|
||||
query.userId = userDetails.id;
|
||||
query.name = null;
|
||||
return service.page(pageParam, query);
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通用户统计自己未读消息数量
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @return 数据
|
||||
*/
|
||||
@GetMapping("/countUnread")
|
||||
public int countUnread(@AuthenticationPrincipal UserDetailsImpl userDetails) {
|
||||
return service.countUnread(userDetails);
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通用户确认消息已读,如果提交的已读消息ID集合为空,则将所有未读消息设为已读
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param noticeIds 已读消息ID集合
|
||||
* @return 确认已读数量
|
||||
*/
|
||||
@PatchMapping("/read")
|
||||
public Boolean acknowledge(@AuthenticationPrincipal UserDetailsImpl userDetails, @RequestBody List<Long> noticeIds) {
|
||||
return service.markAsRead(userDetails, noticeIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通用户确认消息已读,如果提交的已读消息ID集合为空,则将所有未读消息设为已读
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @return 确认已读数量
|
||||
*/
|
||||
@PatchMapping("/readAll")
|
||||
public Boolean readAll(@AuthenticationPrincipal UserDetailsImpl userDetails) {
|
||||
return service.markAllAsRead(userDetails);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理查询消息详情
|
||||
*
|
||||
* @param noticeId 消息ID
|
||||
* @return 用户消息详情
|
||||
*/
|
||||
@GetMapping("/{userId}/{noticeId}")
|
||||
@PreAuthorize("hasAuthority('message:notice:query')")
|
||||
public UserNoticeVo detail(@PathVariable("userId") Long userId, @PathVariable("noticeId") Long noticeId) {
|
||||
return service.detail(noticeId, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员分页查询消息
|
||||
*
|
||||
* @param query 查询参数
|
||||
* @return 分页数据
|
||||
*/
|
||||
@DataPermission(tableAlias = "su")
|
||||
@GetMapping
|
||||
@PreAuthorize("hasAuthority('message:notice:query')")
|
||||
public IPage<AdminNoticeVo> page(Page<AdminNoticeVo> page, AdminNoticeQuery query) {
|
||||
return service.getAdminNoticePage(page, query);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员手动创建消息
|
||||
*
|
||||
* @param dto 表单数据
|
||||
* @return 消息列表
|
||||
*/
|
||||
@PostMapping
|
||||
@PreAuthorize("hasAuthority('message:notice:create')")
|
||||
public Boolean create(@RequestBody UserNoticeDto dto) {
|
||||
return service.createByAdmin(dto);
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.zsc.edu.dify.modules.message.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class BulletinAttachmentDto {
|
||||
|
||||
private Long bulletinId;
|
||||
|
||||
private String attachmentId;
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.zsc.edu.dify.modules.message.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class BulletinDto {
|
||||
|
||||
/**
|
||||
* 标题
|
||||
*/
|
||||
@NotBlank(message = "接收用户不能为空")
|
||||
public String title;
|
||||
|
||||
/**
|
||||
* 是否置顶
|
||||
*/
|
||||
public Boolean top;
|
||||
|
||||
/**
|
||||
* 内容
|
||||
*/
|
||||
@NotBlank(message = "消息内容不能为空")
|
||||
public String content;
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
public String remark;
|
||||
|
||||
/**
|
||||
* 附件ID集合
|
||||
*/
|
||||
private List<String> attachmentIds;
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.zsc.edu.dify.modules.message.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
public class PageDto<T> {
|
||||
/**
|
||||
* 总条数
|
||||
*/
|
||||
private Long total;
|
||||
/**
|
||||
* 总页数
|
||||
*/
|
||||
private Integer pages;
|
||||
/**
|
||||
* 集合
|
||||
*/
|
||||
private List<T> list;
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package com.zsc.edu.dify.modules.message.dto;
|
||||
|
||||
import com.zsc.edu.dify.modules.message.entity.NoticeType;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class UserNoticeDto {
|
||||
|
||||
/**
|
||||
* 用户ID集合
|
||||
*/
|
||||
@NotEmpty(message = "接收用户不能为空")
|
||||
public Set<Long> userIds;
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
*/
|
||||
@NotNull(message = "消息类型不能为空")
|
||||
public NoticeType type;
|
||||
|
||||
/**
|
||||
* 是否需要发送邮件
|
||||
*/
|
||||
public Boolean email;
|
||||
|
||||
/**
|
||||
* 是否需要发送短信
|
||||
*/
|
||||
public Boolean sms;
|
||||
|
||||
/**
|
||||
* 消息内容是否富文本,True则以富文本形式发送
|
||||
*/
|
||||
public Boolean html;
|
||||
|
||||
/**
|
||||
* 消息标题
|
||||
*/
|
||||
@NotBlank(message = "消息标题不能为空")
|
||||
public String title;
|
||||
|
||||
/**
|
||||
* 消息内容
|
||||
*/
|
||||
@NotBlank(message = "消息内容不能为空")
|
||||
public String content;
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,135 @@
|
||||
package com.zsc.edu.dify.modules.message.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IEnum;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.zsc.edu.dify.common.enums.IState;
|
||||
import com.zsc.edu.dify.modules.system.entity.BaseEntity;
|
||||
import com.zsc.edu.dify.modules.attachment.entity.Attachment;
|
||||
import lombok.*;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 系统公告Domain
|
||||
*
|
||||
* @author zhuang
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@TableName("sys_bulletin")
|
||||
public class Bulletin extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 标题
|
||||
*/
|
||||
public String title;
|
||||
|
||||
/**
|
||||
* 状态
|
||||
*/
|
||||
public State state = State.edit;
|
||||
|
||||
/**
|
||||
* 部门ID(权限)
|
||||
*/
|
||||
public Long deptId;
|
||||
|
||||
/**
|
||||
* 是否置顶
|
||||
*/
|
||||
public Boolean top;
|
||||
|
||||
/**
|
||||
* 编辑者ID
|
||||
*/
|
||||
public Long editUserId;
|
||||
|
||||
/**
|
||||
* 编辑者
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
public String editUsername;
|
||||
|
||||
/**
|
||||
* 编辑时间
|
||||
*/
|
||||
public LocalDateTime editTime;
|
||||
|
||||
/**
|
||||
* 审核发布者ID
|
||||
*/
|
||||
public Long publishUserId;
|
||||
|
||||
/**
|
||||
* 审核发布者
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
public String publishUsername;
|
||||
|
||||
/**
|
||||
* 审核发布时间
|
||||
*/
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
public LocalDateTime publishTime;
|
||||
|
||||
/**
|
||||
* 关闭者ID
|
||||
*/
|
||||
public Long closeUserId;
|
||||
|
||||
/**
|
||||
* 关闭者
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
public String closeUsername;
|
||||
|
||||
/**
|
||||
* 关闭时间
|
||||
*/
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
public LocalDateTime closeTime;
|
||||
|
||||
/**
|
||||
* 内容
|
||||
*/
|
||||
public String content;
|
||||
|
||||
/**
|
||||
* 已读状态
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
public Boolean isRead;
|
||||
|
||||
/**
|
||||
* 附件列表
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
public List<Attachment> attachments;
|
||||
|
||||
public enum State implements IEnum<Integer>, IState<State> {
|
||||
edit(1,"编辑中"),
|
||||
publish(2,"已发布"),
|
||||
close(3,"已关闭");
|
||||
|
||||
private final Integer value;
|
||||
private final String name;
|
||||
|
||||
State(int value, String name) {
|
||||
this.value=value;
|
||||
this.name = name;
|
||||
}
|
||||
@Override
|
||||
public Integer getValue() {
|
||||
return this.value;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.name;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.zsc.edu.dify.modules.message.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@TableName("sys_bulletin_attach")
|
||||
public class BulletinAttachment {
|
||||
|
||||
private Long bulletinId;
|
||||
|
||||
private String attachmentId;
|
||||
|
||||
}
|
@ -0,0 +1,62 @@
|
||||
package com.zsc.edu.dify.modules.message.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.zsc.edu.dify.modules.system.entity.BaseEntity;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 消息
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@TableName("sys_notice")
|
||||
public class Notice extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
*/
|
||||
public NoticeType type = NoticeType.MESSAGE;
|
||||
|
||||
/**
|
||||
* 是否系统生成
|
||||
*/
|
||||
public Boolean system = false;
|
||||
|
||||
/**
|
||||
* 是否需要发送邮件
|
||||
*/
|
||||
public Boolean email;
|
||||
|
||||
|
||||
/**
|
||||
* 是否需要发送短信
|
||||
*/
|
||||
public Boolean sms;
|
||||
|
||||
/**
|
||||
* 消息内容是否富文本,True则以富文本形式发送
|
||||
*/
|
||||
public Boolean html;
|
||||
|
||||
/**
|
||||
* 标题
|
||||
*/
|
||||
public String title;
|
||||
|
||||
/**
|
||||
* 消息内容
|
||||
*/
|
||||
public String content;
|
||||
|
||||
/**
|
||||
* 部门ID(权限)
|
||||
*/
|
||||
public Long deptId;
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.zsc.edu.dify.modules.message.entity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* 消息内容
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
public abstract class NoticePayload {
|
||||
|
||||
public NoticeType type;
|
||||
public String content;
|
||||
public Boolean html;
|
||||
|
||||
public static class Other extends NoticePayload {
|
||||
public Other(String content) {
|
||||
this.content = content;
|
||||
this.type = NoticeType.MESSAGE;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ResetPassword extends NoticePayload {
|
||||
public String username;
|
||||
public String password;
|
||||
public LocalDateTime resetTime;
|
||||
|
||||
public ResetPassword(String username, String password, LocalDateTime resetTime) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.resetTime = resetTime;
|
||||
this.type = NoticeType.NOTICE;
|
||||
this.content = String.format("尊敬的用户%s,您的密码已于%s被管理员重置,新密码为%s," +
|
||||
"请及时登录系统修改密码!", username, resetTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), password);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package com.zsc.edu.dify.modules.message.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IEnum;
|
||||
import com.zsc.edu.dify.common.enums.IState;
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
*
|
||||
* @author zhuang
|
||||
*/
|
||||
public enum NoticeType implements IEnum<Integer>, IState<NoticeType> {
|
||||
MESSAGE(1, "消息"),
|
||||
NOTICE(2, "通知");
|
||||
|
||||
private final Integer value;
|
||||
private final String name;
|
||||
|
||||
NoticeType(Integer value, String name) {
|
||||
this.value = value;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return name;
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.zsc.edu.dify.modules.message.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.*;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 用户消息
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@TableName("sys_user_notice")
|
||||
public class UserNotice implements Serializable {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 用户ID
|
||||
*/
|
||||
public Long userId;
|
||||
|
||||
|
||||
/**
|
||||
* 消息ID
|
||||
*/
|
||||
public Long noticeId;
|
||||
|
||||
|
||||
/**
|
||||
* 是否已读
|
||||
*/
|
||||
public Boolean isRead;
|
||||
|
||||
/**
|
||||
* 阅读时间
|
||||
*/
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
public LocalDateTime readTime;
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.zsc.edu.dify.modules.message.mapper;
|
||||
|
||||
import com.zsc.edu.dify.common.mapstruct.BaseMapper;
|
||||
import com.zsc.edu.dify.modules.message.dto.BulletinAttachmentDto;
|
||||
import com.zsc.edu.dify.modules.message.entity.BulletinAttachment;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface BulletinAttachmentMapper extends BaseMapper<BulletinAttachmentDto, BulletinAttachment> {
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.zsc.edu.dify.modules.message.mapper;
|
||||
|
||||
import com.zsc.edu.dify.common.mapstruct.BaseMapper;
|
||||
import com.zsc.edu.dify.modules.message.dto.BulletinDto;
|
||||
import com.zsc.edu.dify.modules.message.entity.Bulletin;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface BulletinMapper extends BaseMapper<BulletinDto, Bulletin> {
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.zsc.edu.dify.modules.message.mapper;
|
||||
|
||||
import com.zsc.edu.dify.common.mapstruct.BaseMapper;
|
||||
import com.zsc.edu.dify.modules.message.dto.UserNoticeDto;
|
||||
import com.zsc.edu.dify.modules.message.entity.Notice;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface NoticeMapper extends BaseMapper<UserNoticeDto, Notice> {
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package com.zsc.edu.dify.modules.message.query;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AdminNoticeQuery {
|
||||
/**
|
||||
* 用户ID
|
||||
*/
|
||||
public Long userId;
|
||||
|
||||
/**
|
||||
* 标题,模糊查询
|
||||
*/
|
||||
public String title;
|
||||
|
||||
/**
|
||||
* 消息创建时间区间起始
|
||||
*/
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
public LocalDateTime createAtBegin;
|
||||
|
||||
/**
|
||||
* 消息创建时间区间终止
|
||||
*/
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
public LocalDateTime createAtEnd;
|
||||
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.zsc.edu.dify.modules.message.query;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.zsc.edu.dify.modules.message.entity.Bulletin;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 系统公告Query
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
|
||||
public class BulletinQuery {
|
||||
|
||||
private String title;
|
||||
private Bulletin.State state;
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime publishTimeBegin;
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime publishTimeEnd;
|
||||
|
||||
public LambdaQueryWrapper<Bulletin> wrapper() {
|
||||
LambdaQueryWrapper<Bulletin> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.like(StringUtils.hasText(this.title), Bulletin::getTitle, this.title);
|
||||
queryWrapper.eq(Objects.nonNull(this.state), Bulletin::getState, this.state);
|
||||
if (publishTimeBegin != null && publishTimeEnd != null) {
|
||||
queryWrapper.between(Bulletin::getPublishTime, this.publishTimeBegin, this.publishTimeEnd);
|
||||
}
|
||||
return queryWrapper;
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.zsc.edu.dify.modules.message.query;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.zsc.edu.dify.modules.message.entity.Notice;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class NoticeQuery {
|
||||
Set<Long> noticeIds;
|
||||
|
||||
public LambdaQueryWrapper<Notice> wrapper() {
|
||||
LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(StringUtils.hasText((CharSequence) this.noticeIds), Notice::getId, this.noticeIds);
|
||||
return queryWrapper;
|
||||
}
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
package com.zsc.edu.dify.modules.message.query;
|
||||
|
||||
import com.zsc.edu.dify.modules.message.entity.NoticeType;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 用户消息Query
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class UserNoticeQuery {
|
||||
|
||||
/**
|
||||
* 用户ID
|
||||
*/
|
||||
public Long userId;
|
||||
|
||||
/**
|
||||
* 标题,模糊查询
|
||||
*/
|
||||
public String title;
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
*/
|
||||
public NoticeType type;
|
||||
|
||||
/**
|
||||
* 用户名或真实姓名,用户名准确查询,姓名模糊查询
|
||||
*/
|
||||
public String name;
|
||||
|
||||
/**
|
||||
* 是否系统自动生成
|
||||
*/
|
||||
public Boolean system;
|
||||
|
||||
/**
|
||||
* 是否已读
|
||||
*/
|
||||
public Boolean isRead;
|
||||
|
||||
/**
|
||||
* 消息创建时间区间起始
|
||||
*/
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
public LocalDateTime createAtBegin;
|
||||
|
||||
/**
|
||||
* 消息创建时间区间终止
|
||||
*/
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
public LocalDateTime createAtEnd;
|
||||
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.zsc.edu.dify.modules.message.repo;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.zsc.edu.dify.modules.message.entity.BulletinAttachment;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
public interface BulletinAttachmentRepository extends BaseMapper<BulletinAttachment> {
|
||||
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.zsc.edu.dify.modules.message.repo;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.zsc.edu.dify.modules.message.entity.Bulletin;
|
||||
import com.zsc.edu.dify.modules.message.query.BulletinQuery;
|
||||
import com.zsc.edu.dify.modules.message.vo.BulletinVo;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
|
||||
/**
|
||||
* 公告Repo
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
public interface BulletinRepository extends BaseMapper<Bulletin> {
|
||||
|
||||
|
||||
BulletinVo selectByBulletinId(@Param("bulletinId") Long bulletinId);
|
||||
|
||||
IPage<BulletinVo> selectPageByConditions(Page<BulletinVo> page, @Param("query") BulletinQuery query);
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.zsc.edu.dify.modules.message.repo;
|
||||
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.zsc.edu.dify.modules.message.entity.Notice;
|
||||
|
||||
/**
|
||||
* 消息Repo
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
public interface NoticeRepository extends BaseMapper<Notice> {
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.zsc.edu.dify.modules.message.repo;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.zsc.edu.dify.modules.message.entity.UserNotice;
|
||||
import com.zsc.edu.dify.modules.message.query.AdminNoticeQuery;
|
||||
import com.zsc.edu.dify.modules.message.query.UserNoticeQuery;
|
||||
import com.zsc.edu.dify.modules.message.vo.AdminNoticeVo;
|
||||
import com.zsc.edu.dify.modules.message.vo.UserNoticeVo;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
/**
|
||||
* 用户消息Repo
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
public interface UserNoticeRepository extends BaseMapper<UserNotice> {
|
||||
|
||||
UserNoticeVo selectByNoticeIdAndUserId(@Param("noticeId") Long noticeId, @Param("userId") Long userId);
|
||||
|
||||
IPage<UserNoticeVo> page(Page<UserNoticeVo> page, @Param("query") UserNoticeQuery query);
|
||||
|
||||
IPage<AdminNoticeVo> pageAdmin(Page<AdminNoticeVo> page, @Param("query") AdminNoticeQuery query);
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.zsc.edu.dify.modules.message.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.zsc.edu.dify.framework.security.UserDetailsImpl;
|
||||
import com.zsc.edu.dify.modules.message.dto.BulletinDto;
|
||||
import com.zsc.edu.dify.modules.message.entity.Bulletin;
|
||||
import com.zsc.edu.dify.modules.message.query.BulletinQuery;
|
||||
import com.zsc.edu.dify.modules.message.vo.BulletinVo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 系统公告Service
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
|
||||
public interface BulletinService extends IService<Bulletin> {
|
||||
|
||||
BulletinVo detail(UserDetailsImpl userDetails, Long id, Bulletin.State state);
|
||||
|
||||
Bulletin create(UserDetailsImpl userDetails, BulletinDto dto);
|
||||
|
||||
Boolean update(UserDetailsImpl userDetails, BulletinDto dto, Long id);
|
||||
|
||||
Boolean toggleTop(Long id);
|
||||
|
||||
boolean publish(UserDetailsImpl userDetails, List<Long> id);
|
||||
|
||||
Boolean close(UserDetailsImpl userDetails,Long id);
|
||||
|
||||
IPage<BulletinVo> selectPageByConditions(Page<BulletinVo> page, BulletinQuery query);
|
||||
|
||||
Boolean delete(Long id);
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package com.zsc.edu.dify.modules.message.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.zsc.edu.dify.framework.security.UserDetailsImpl;
|
||||
import com.zsc.edu.dify.modules.message.dto.UserNoticeDto;
|
||||
import com.zsc.edu.dify.modules.message.entity.UserNotice;
|
||||
import com.zsc.edu.dify.modules.message.query.AdminNoticeQuery;
|
||||
import com.zsc.edu.dify.modules.message.query.UserNoticeQuery;
|
||||
import com.zsc.edu.dify.modules.message.vo.AdminNoticeVo;
|
||||
import com.zsc.edu.dify.modules.message.vo.UserNoticeVo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户消息Service
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
public interface UserNoticeService extends IService<UserNotice> {
|
||||
|
||||
Boolean createByAdmin(UserNoticeDto dto);
|
||||
|
||||
UserNoticeVo detail(Long noticeId, Long userId);
|
||||
|
||||
IPage<UserNoticeVo> page(Page<UserNoticeVo> page, UserNoticeQuery query);
|
||||
|
||||
Integer countUnread(UserDetailsImpl userDetails);
|
||||
|
||||
boolean markAsRead(UserDetailsImpl userDetails, List<Long> noticeIds);
|
||||
|
||||
|
||||
boolean markAllAsRead(UserDetailsImpl userDetails);
|
||||
|
||||
IPage<AdminNoticeVo> getAdminNoticePage(Page<AdminNoticeVo> page, AdminNoticeQuery query);
|
||||
}
|
@ -0,0 +1,201 @@
|
||||
package com.zsc.edu.dify.modules.message.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.zsc.edu.dify.exception.ConstraintException;
|
||||
import com.zsc.edu.dify.framework.security.UserDetailsImpl;
|
||||
import com.zsc.edu.dify.modules.message.dto.BulletinDto;
|
||||
import com.zsc.edu.dify.modules.message.entity.Bulletin;
|
||||
import com.zsc.edu.dify.modules.message.entity.BulletinAttachment;
|
||||
import com.zsc.edu.dify.modules.message.mapper.BulletinMapper;
|
||||
import com.zsc.edu.dify.modules.message.query.BulletinQuery;
|
||||
import com.zsc.edu.dify.modules.message.repo.BulletinAttachmentRepository;
|
||||
import com.zsc.edu.dify.modules.message.repo.BulletinRepository;
|
||||
import com.zsc.edu.dify.modules.message.service.BulletinService;
|
||||
import com.zsc.edu.dify.modules.message.vo.BulletinVo;
|
||||
import com.zsc.edu.dify.modules.system.repo.UserRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.zsc.edu.dify.modules.message.entity.Bulletin.State.*;
|
||||
|
||||
/**
|
||||
* 系统公告Service
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class BulletinServiceImpl extends ServiceImpl<BulletinRepository, Bulletin> implements BulletinService {
|
||||
|
||||
private final BulletinMapper mapper;
|
||||
private final BulletinRepository repo;
|
||||
private final UserRepository userRepository;
|
||||
private final BulletinAttachmentRepository bulletinAttachmentRepository;
|
||||
/**
|
||||
* 查询公告详情
|
||||
*
|
||||
* @param id ID
|
||||
* @param state 公告状态
|
||||
* @return 公告详情
|
||||
*/
|
||||
@Override
|
||||
public BulletinVo detail(UserDetailsImpl userDetails, Long id, Bulletin.State state) {
|
||||
BulletinVo bulletinVo = repo.selectByBulletinId(id);
|
||||
if (state != null) {
|
||||
bulletinVo.getState().checkStatus(state);
|
||||
}
|
||||
bulletinVo.setEditUsername(UserRepository.selectNameById(bulletinVo.getEditUserId()));
|
||||
bulletinVo.setPublishUsername(UserRepository.selectNameById(bulletinVo.getPublishUserId()));
|
||||
bulletinVo.setCloseUsername(UserRepository.selectNameById(bulletinVo.getCloseUserId()));
|
||||
return bulletinVo;
|
||||
}
|
||||
/**
|
||||
* 新建公告
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param dto 表单数据
|
||||
* @return 新建的公告
|
||||
*/
|
||||
@Override
|
||||
public Bulletin create(UserDetailsImpl userDetails, BulletinDto dto) {
|
||||
boolean existsByName=count(new LambdaQueryWrapper<Bulletin>().eq(Bulletin::getTitle,dto.getTitle())) > 0;
|
||||
if(existsByName){
|
||||
throw new ConstraintException("title", dto.title, "标题已存在");
|
||||
}
|
||||
Bulletin bulletin = mapper.toEntity(dto);
|
||||
bulletin.setEditUserId(userDetails.getId());
|
||||
save(bulletin);
|
||||
if (dto.getAttachmentIds() != null) {
|
||||
insertInto(bulletin.getId(), dto.getAttachmentIds());
|
||||
}
|
||||
return bulletin;
|
||||
}
|
||||
/**
|
||||
* 修改公告,只能修改"编辑中"或"已发布"的公告
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param dto 表单数据
|
||||
* @return 已修改的公告
|
||||
*/
|
||||
@Override
|
||||
public Boolean update(UserDetailsImpl userDetails,BulletinDto dto, Long id) {
|
||||
Bulletin bulletin = getById(id);
|
||||
bulletin.state.checkStatus(EnumSet.of(edit, publish));
|
||||
mapper.convert(dto, bulletin);
|
||||
bulletin.setCreateBy(userDetails.getName());
|
||||
bulletin.setCreateTime(LocalDateTime.now());
|
||||
bulletin.state = edit;
|
||||
if (dto.getAttachmentIds() != null) {
|
||||
LambdaQueryWrapper<BulletinAttachment> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(BulletinAttachment::getBulletinId, bulletin.getId());
|
||||
bulletinAttachmentRepository.delete(queryWrapper);
|
||||
insertInto(bulletin.getId(), dto.getAttachmentIds());
|
||||
}
|
||||
return updateById(bulletin);
|
||||
}
|
||||
/**
|
||||
* 批量发布公告,只能发布"编辑中"的公告
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param ids ids
|
||||
* @return 已发布的公告
|
||||
*/
|
||||
@Override
|
||||
public boolean publish(UserDetailsImpl userDetails, List<Long> ids) {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
throw new RuntimeException("您输入的集合为空");
|
||||
}
|
||||
LambdaQueryWrapper<Bulletin> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.in(Bulletin::getId, ids);
|
||||
List<Bulletin> bulletins = repo.selectList(queryWrapper);
|
||||
boolean allEditable = true;
|
||||
for (Bulletin bulletin : bulletins) {
|
||||
try {
|
||||
bulletin.state.checkStatus(EnumSet.of(edit));
|
||||
} catch (Exception e) {
|
||||
allEditable = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!allEditable) {
|
||||
throw new RuntimeException("存在公告状态不是编辑中的,无法发布");
|
||||
}
|
||||
return this.lambdaUpdate().in(Bulletin::getId, ids)
|
||||
.eq(Bulletin::getState, edit)
|
||||
.set(Bulletin::getState, publish)
|
||||
.set(Bulletin::getPublishTime, LocalDateTime.now())
|
||||
.set(Bulletin::getPublishUserId, userDetails.getId())
|
||||
.update();
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换关闭状态,只能关闭"已发布"的公告,只能开启“已关闭”的公告
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param id ID
|
||||
* @return 已关闭的公告
|
||||
*/
|
||||
@Override
|
||||
public Boolean close(UserDetailsImpl userDetails, Long id) {
|
||||
Bulletin bulletin = getById(id);
|
||||
bulletin.top = false;
|
||||
if(bulletin.state==close){
|
||||
bulletin.state = edit;
|
||||
return updateById(bulletin);
|
||||
}
|
||||
bulletin.state.checkStatus(publish);
|
||||
bulletin.state = close;
|
||||
bulletin.setCloseUserId(userDetails.getId());
|
||||
bulletin.setCloseTime(LocalDateTime.now());
|
||||
return updateById(bulletin);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换公告置顶状态
|
||||
*
|
||||
* @param id ID
|
||||
* @return 被更新的公告
|
||||
*/
|
||||
@Override
|
||||
public Boolean toggleTop(Long id) {
|
||||
Bulletin bulletin = getById(id);
|
||||
bulletin.top = !bulletin.top;
|
||||
return updateById(bulletin);
|
||||
}
|
||||
|
||||
/**
|
||||
*为公告添加附件
|
||||
*
|
||||
* @param bulletinId bulletinId
|
||||
* @param attachmentIds attachments
|
||||
*/
|
||||
public void insertInto(Long bulletinId, List<String> attachmentIds) {
|
||||
List<BulletinAttachment> bulletinAttachments = attachmentIds.stream()
|
||||
.map(attachmentId -> new BulletinAttachment(bulletinId, attachmentId))
|
||||
.collect(Collectors.toList());
|
||||
bulletinAttachmentRepository.insert(bulletinAttachments);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPage<BulletinVo> selectPageByConditions(Page<BulletinVo> page, BulletinQuery query) {
|
||||
return baseMapper.selectPageByConditions(page, query);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean delete(Long id) {
|
||||
LambdaQueryWrapper<BulletinAttachment> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(BulletinAttachment::getBulletinId, id);
|
||||
List<BulletinAttachment> bulletinAttachments = bulletinAttachmentRepository.selectList(queryWrapper);
|
||||
if (!bulletinAttachments.isEmpty()) {
|
||||
bulletinAttachmentRepository.delete(queryWrapper);
|
||||
}
|
||||
return removeById(id);
|
||||
}
|
||||
}
|
@ -0,0 +1,195 @@
|
||||
package com.zsc.edu.dify.modules.message.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.zsc.edu.dify.framework.message.email.EmailSender;
|
||||
import com.zsc.edu.dify.framework.message.sms.SmsSender;
|
||||
import com.zsc.edu.dify.framework.security.UserDetailsImpl;
|
||||
import com.zsc.edu.dify.modules.message.dto.UserNoticeDto;
|
||||
import com.zsc.edu.dify.modules.message.entity.*;
|
||||
import com.zsc.edu.dify.modules.message.mapper.NoticeMapper;
|
||||
import com.zsc.edu.dify.modules.message.query.AdminNoticeQuery;
|
||||
import com.zsc.edu.dify.modules.message.query.UserNoticeQuery;
|
||||
import com.zsc.edu.dify.modules.message.repo.NoticeRepository;
|
||||
import com.zsc.edu.dify.modules.message.repo.UserNoticeRepository;
|
||||
import com.zsc.edu.dify.modules.message.service.UserNoticeService;
|
||||
import com.zsc.edu.dify.modules.message.vo.AdminNoticeVo;
|
||||
import com.zsc.edu.dify.modules.message.vo.UserNoticeVo;
|
||||
import com.zsc.edu.dify.modules.system.entity.User;
|
||||
import com.zsc.edu.dify.modules.system.repo.UserRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
/**
|
||||
* 用户消息Service
|
||||
*
|
||||
* @author harry_yao
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class UserNoticeServiceImpl extends ServiceImpl<UserNoticeRepository, UserNotice> implements UserNoticeService {
|
||||
|
||||
private final NoticeRepository noticeRepo;
|
||||
private final EmailSender emailSender;
|
||||
private final SmsSender smsSender;
|
||||
private final UserRepository userRepository;
|
||||
private final NoticeMapper noticeMapper;
|
||||
|
||||
|
||||
/**
|
||||
* 查询消息详情
|
||||
*
|
||||
* @param noticeId 消息ID
|
||||
* @param userId 用户ID
|
||||
* @return 查询详情
|
||||
*/
|
||||
|
||||
@Override
|
||||
public UserNoticeVo detail(Long noticeId, Long userId) {
|
||||
UserNoticeVo userNoticeVo = baseMapper.selectByNoticeIdAndUserId(noticeId, userId);
|
||||
if (userNoticeVo == null) {
|
||||
throw new RuntimeException("您输入的信息有误,请检查输入ID信息是否正确");
|
||||
}
|
||||
return userNoticeVo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询用户消息
|
||||
*
|
||||
* @param query 查询表单
|
||||
* @param page 分页参数
|
||||
* @return 页面数据
|
||||
*/
|
||||
@Override
|
||||
public IPage<UserNoticeVo> page(Page<UserNoticeVo> page, UserNoticeQuery query) {
|
||||
return baseMapper.page(page, query);
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计用户未读消息数量
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @return 未读消息数量
|
||||
*/
|
||||
@Override
|
||||
public Integer countUnread(UserDetailsImpl userDetails) {
|
||||
LambdaQueryWrapper<UserNotice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
|
||||
lambdaQueryWrapper.eq(UserNotice::getUserId, userDetails.getId())
|
||||
.eq(UserNotice::getIsRead, true);
|
||||
return Math.toIntExact(baseMapper.selectCount(lambdaQueryWrapper));
|
||||
}
|
||||
|
||||
/**
|
||||
* 设为已读
|
||||
*
|
||||
* @param userDetails 操作用户
|
||||
* @param messageIds 消息ID集合,如为空,则将该用户的所有未读消息设为已读
|
||||
* @return 修改记录数量
|
||||
*/
|
||||
@Override
|
||||
public boolean markAsRead(UserDetailsImpl userDetails, List<Long> messageIds) {
|
||||
if (CollectionUtils.isEmpty(messageIds)) {
|
||||
throw new RuntimeException("您输入的集合为空");
|
||||
}
|
||||
return this.lambdaUpdate().eq(UserNotice::getUserId, userDetails.getId())
|
||||
.in(UserNotice::getNoticeId, messageIds)
|
||||
.set(UserNotice::getIsRead, true)
|
||||
.set(UserNotice::getReadTime, LocalDateTime.now())
|
||||
.update();
|
||||
}
|
||||
|
||||
/**
|
||||
* 全部已读
|
||||
*/
|
||||
@Override
|
||||
public boolean markAllAsRead(UserDetailsImpl userDetails) {
|
||||
return this.lambdaUpdate().eq(UserNotice::getUserId, userDetails.getId())
|
||||
.set(UserNotice::getIsRead, true)
|
||||
.set(UserNotice::getReadTime, LocalDateTime.now())
|
||||
.update();
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员查询消息分页
|
||||
*
|
||||
* @return 消息设置列表
|
||||
*/
|
||||
@Override
|
||||
public IPage<AdminNoticeVo> getAdminNoticePage(Page<AdminNoticeVo> page, AdminNoticeQuery query) {
|
||||
return baseMapper.pageAdmin(page, query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* 管理员手动创建用户消息并发送
|
||||
*
|
||||
* @param dto 表单数据
|
||||
* @return 创建的用户消息列表
|
||||
*/
|
||||
@Transactional
|
||||
@Override
|
||||
public Boolean createByAdmin(UserNoticeDto dto) {
|
||||
Set<User> users = new HashSet<>(userRepository.selectList(new LambdaQueryWrapper<User>().in(User::getId, dto.userIds)));
|
||||
Notice notice = noticeMapper.toEntity(dto);
|
||||
noticeRepo.insert(notice);
|
||||
Set<UserNotice> userNotices = users.stream()
|
||||
.map(user -> new UserNotice(null, user.getId(), notice.getId(), true, null))
|
||||
.collect(Collectors.toSet());
|
||||
send(users, notice);
|
||||
return saveBatch(userNotices);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 以邮件、短信等形式发送消息,只有非html格式的消息才能以短信方式发送
|
||||
*
|
||||
* @param users 接收者
|
||||
* @param notice 消息
|
||||
*/
|
||||
@Async
|
||||
void send(Set<User> users, Notice notice) {
|
||||
if (notice.email) {
|
||||
emailSender.send(users.stream().map(User::getEmail).collect(Collectors.toSet()), notice);
|
||||
}
|
||||
if (notice.sms && !notice.html) {
|
||||
smsSender.send(users.stream().map(User::getPhone).collect(Collectors.toSet()), notice.content);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 系统自动创建用户消息并发送
|
||||
*
|
||||
* @param receivers 接收者
|
||||
* @param payload 消息内容
|
||||
*/
|
||||
@Transactional
|
||||
public Boolean createBySystem(Set<User> receivers, NoticePayload payload) {
|
||||
AtomicBoolean email = new AtomicBoolean(false);
|
||||
AtomicBoolean sms = new AtomicBoolean(false);
|
||||
Optional.of(noticeRepo.selectById(payload.type)).ifPresent(message -> {
|
||||
email.set(message.email);
|
||||
sms.set(message.sms);
|
||||
});
|
||||
Notice notice = new Notice(payload.type, true, email.get(), sms.get(),
|
||||
payload.html, payload.type.name(), payload.content, null);
|
||||
noticeRepo.insert(notice);
|
||||
Set<UserNotice> userNotices = receivers.stream().map(user ->
|
||||
new UserNotice(null, user.getId(), notice.getId(), true, null)).collect(Collectors.toSet());
|
||||
send(receivers, notice);
|
||||
return saveBatch(userNotices);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package com.zsc.edu.dify.modules.message.vo;
|
||||
|
||||
import com.zsc.edu.dify.modules.message.entity.NoticeType;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
public class AdminNoticeVo {
|
||||
/**
|
||||
* 用户消息id
|
||||
*/
|
||||
private Long id;
|
||||
/**
|
||||
* 接收用户数
|
||||
*/
|
||||
private Long userCount;
|
||||
/**
|
||||
* 已读用户数
|
||||
*/
|
||||
private Long readCount;
|
||||
/**
|
||||
* 消息类型
|
||||
*/
|
||||
public NoticeType type = NoticeType.MESSAGE;
|
||||
/**
|
||||
* 是否系统消息
|
||||
*/
|
||||
public Boolean system;
|
||||
/**
|
||||
* 是否邮件
|
||||
*/
|
||||
public Boolean email;
|
||||
/**
|
||||
* 是否短信
|
||||
*/
|
||||
public Boolean sms;
|
||||
/**
|
||||
* 是否html
|
||||
*/
|
||||
public Boolean html;
|
||||
/**
|
||||
* 标题
|
||||
*/
|
||||
public String title;
|
||||
/**
|
||||
* 内容
|
||||
*/
|
||||
public String content;
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
}
|
@ -0,0 +1,98 @@
|
||||
package com.zsc.edu.dify.modules.message.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.zsc.edu.dify.modules.attachment.entity.Attachment;
|
||||
import com.zsc.edu.dify.modules.message.entity.Bulletin;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
@JsonInclude
|
||||
public class BulletinVo {
|
||||
/**
|
||||
* 公告id
|
||||
*/
|
||||
private Long id;
|
||||
/**
|
||||
* 公告标题
|
||||
*/
|
||||
private String title;
|
||||
/**
|
||||
* 公告属性
|
||||
*/
|
||||
private Bulletin.State state = Bulletin.State.edit;
|
||||
/**
|
||||
* 公告置顶状态
|
||||
*/
|
||||
private Boolean top;
|
||||
/**
|
||||
* 公告编辑者ID
|
||||
*/
|
||||
private Long editUserId;
|
||||
/**
|
||||
* 公告编辑者名称
|
||||
*/
|
||||
private String editUsername;
|
||||
/**
|
||||
* 公告编辑时间
|
||||
*/
|
||||
private LocalDateTime editTime;
|
||||
/**
|
||||
* 公告发布者ID
|
||||
*/
|
||||
private Long publishUserId;
|
||||
/**
|
||||
* 公告发布者名称
|
||||
*/
|
||||
private String publishUsername;
|
||||
/**
|
||||
* 公告发布时间
|
||||
*/
|
||||
private LocalDateTime publishTime;
|
||||
/**
|
||||
* 公告关闭者ID
|
||||
*/
|
||||
private Long closeUserId;
|
||||
/**
|
||||
* 公告关闭者名称
|
||||
*/
|
||||
private String closeUsername;
|
||||
/**
|
||||
* 公告关闭时间
|
||||
*/
|
||||
private LocalDateTime closeTime;
|
||||
/**
|
||||
* 公告内容
|
||||
*/
|
||||
private String content;
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private LocalDateTime createTime;
|
||||
/**
|
||||
* 创建者
|
||||
*/
|
||||
private String createBy;
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
private LocalDateTime updateTime;
|
||||
/**
|
||||
* 更新者
|
||||
*/
|
||||
private String updateBy;
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
/**
|
||||
* 附件
|
||||
*/
|
||||
List<Attachment> attachments;
|
||||
|
||||
}
|
@ -0,0 +1,80 @@
|
||||
package com.zsc.edu.dify.modules.message.vo;
|
||||
|
||||
import com.zsc.edu.dify.modules.message.entity.NoticeType;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Data
|
||||
public class UserNoticeVo {
|
||||
/**
|
||||
* 用户消息id
|
||||
*/
|
||||
private Long noticeId;
|
||||
/**
|
||||
* 是否已读
|
||||
*/
|
||||
public Boolean isRead;
|
||||
/**
|
||||
* 阅读时间
|
||||
*/
|
||||
public LocalDateTime readTime;
|
||||
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
public String username;
|
||||
|
||||
/**
|
||||
* 消息类型
|
||||
*/
|
||||
public NoticeType type = NoticeType.MESSAGE;
|
||||
/**
|
||||
* 是否系统消息
|
||||
*/
|
||||
public Boolean system;
|
||||
/**
|
||||
* 是否邮件
|
||||
*/
|
||||
public Boolean email;
|
||||
/**
|
||||
* 是否短信
|
||||
*/
|
||||
public Boolean sms;
|
||||
/**
|
||||
* 是否html
|
||||
*/
|
||||
public Boolean html;
|
||||
/**
|
||||
* 标题
|
||||
*/
|
||||
public String title;
|
||||
/**
|
||||
* 内容
|
||||
*/
|
||||
public String content;
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private LocalDateTime createTime;
|
||||
/**
|
||||
* 创建人
|
||||
*/
|
||||
private String createBy;
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
private LocalDateTime updateTime;
|
||||
/**
|
||||
* 更新人
|
||||
*/
|
||||
private String updateBy;
|
||||
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
package com.zsc.edu.dify.modules.operationLog.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.zsc.edu.dify.modules.operationLog.entity.OperationLog;
|
||||
import com.zsc.edu.dify.modules.operationLog.query.OperationLogQuery;
|
||||
import com.zsc.edu.dify.modules.operationLog.repo.OperationLogRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/rest/log")
|
||||
public class OperationController {
|
||||
private OperationLogRepository repo;
|
||||
|
||||
/**
|
||||
* 获取操作日志详情
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
@PreAuthorize("hasAuthority('operationLog:query')")
|
||||
public OperationLog crate(@PathVariable("id") Long id) {
|
||||
return repo.selectById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取操作日志分页
|
||||
*/
|
||||
@GetMapping("")
|
||||
@PreAuthorize("hasAuthority('operationLog:query')")
|
||||
public Page<OperationLog> query(Page<OperationLog> page, OperationLogQuery query) {
|
||||
return repo.selectPage(page, query.wrapper());
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除操作日志
|
||||
*/
|
||||
@DeleteMapping("/batch")
|
||||
@PreAuthorize("hasAuthority('operationLog:delete')")
|
||||
public int deleteBatch(@RequestBody List<Long> ids) {
|
||||
LambdaQueryWrapper<OperationLog> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.in(OperationLog::getId, ids);
|
||||
return repo.delete(wrapper);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.zsc.edu.dify.modules.operationLog.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class ExpressionRootObject {
|
||||
private final Object object;
|
||||
private final Object[] args;
|
||||
|
||||
public ExpressionRootObject(Object object, Object[] args) {
|
||||
this.object = object;
|
||||
this.args = args;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.zsc.edu.dify.modules.operationLog.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IEnum;
|
||||
import com.zsc.edu.dify.common.enums.IState;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* @author lenovo
|
||||
*/
|
||||
|
||||
@Getter
|
||||
public enum FunctionTypeEnum implements IEnum<String>, IState<FunctionTypeEnum> {
|
||||
create("create", "create"),
|
||||
update("update", "update"),
|
||||
delete("delete", "delete"),
|
||||
other("other", "other");
|
||||
|
||||
private final String code;
|
||||
private final String message;
|
||||
|
||||
FunctionTypeEnum(String code, String message) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getValue() {
|
||||
return code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据代码获取消息
|
||||
*
|
||||
* @param code 代码
|
||||
* @return 消息
|
||||
*/
|
||||
public static String getMessageByCode(String code) {
|
||||
for (FunctionTypeEnum type : FunctionTypeEnum.values()) {
|
||||
if (type.getCode().equalsIgnoreCase(code)) {
|
||||
return type.getMessage();
|
||||
}
|
||||
}
|
||||
return other.getMessage();
|
||||
}
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
package com.zsc.edu.dify.modules.operationLog.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IEnum;
|
||||
import com.zsc.edu.dify.common.enums.IState;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* @author lenovo
|
||||
*/
|
||||
@Getter
|
||||
public enum ModuleTypeEnum implements IEnum<String>, IState<ModuleTypeEnum> {
|
||||
user("user", "user"),
|
||||
role("role", "role"),
|
||||
menu("menu", "menu"),
|
||||
dept("dept", "dept"),
|
||||
device("device", "device"),
|
||||
product("product", "product"),
|
||||
serve("serve", "serve"),
|
||||
event("event", "event"),
|
||||
property("property", "property"),
|
||||
notice("notice", "notice"),
|
||||
bulletin("bulletin", "bulletin"),
|
||||
attachment("attachment", "attachment"),
|
||||
other("other", "other");
|
||||
|
||||
private final String code;
|
||||
private final String messageCode;
|
||||
|
||||
private static final Map<String, ModuleTypeEnum> CODE_MAP = Arrays.stream(values())
|
||||
.collect(Collectors.toMap(
|
||||
type -> type.getCode().toLowerCase(),
|
||||
type -> type
|
||||
));
|
||||
|
||||
ModuleTypeEnum(String code, String message) {
|
||||
this.code = code;
|
||||
this.messageCode = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getValue() {
|
||||
return code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return this.messageCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据代码获取消息
|
||||
*
|
||||
* @param code 代码
|
||||
* @return 消息
|
||||
*/
|
||||
public static String getMessageByCode(String code) {
|
||||
ModuleTypeEnum type = CODE_MAP.get(code.toLowerCase());
|
||||
return Objects.requireNonNullElse(type, other).getMessageCode();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.zsc.edu.dify.modules.operationLog.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@TableName("operation_log")
|
||||
public class OperationLog {
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 模块类型
|
||||
*/
|
||||
private ModuleTypeEnum moduleType;
|
||||
|
||||
/**
|
||||
* 操作类型
|
||||
*/
|
||||
private FunctionTypeEnum functionType;
|
||||
|
||||
/**
|
||||
* 操作内容
|
||||
*/
|
||||
private String content;
|
||||
|
||||
/**
|
||||
* 操作时间
|
||||
*/
|
||||
private LocalDateTime makeTime;
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.zsc.edu.dify.modules.operationLog.entity;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* @author zhuang
|
||||
*/
|
||||
@Target({ElementType.PARAMETER, ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface OperationLogAnnotation {
|
||||
/**
|
||||
* 日志内容,支持SpEL表达式
|
||||
*/
|
||||
String content() default "";
|
||||
|
||||
/**
|
||||
* 操作类型,例如:SAVE, UPDATE, DELETE
|
||||
*/
|
||||
String operationType() default "";
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user