第一次提交
This commit is contained in:
93
src/main/java/com/gxwebsoft/common/core/Constants.java
Normal file
93
src/main/java/com/gxwebsoft/common/core/Constants.java
Normal file
@@ -0,0 +1,93 @@
|
||||
package com.gxwebsoft.common.core;
|
||||
|
||||
/**
|
||||
* 系统常量
|
||||
* Created by WebSoft on 2019-10-29 15:55
|
||||
*/
|
||||
public class Constants {
|
||||
/**
|
||||
* 默认成功码
|
||||
*/
|
||||
public static final int RESULT_OK_CODE = 0;
|
||||
|
||||
/**
|
||||
* 默认失败码
|
||||
*/
|
||||
public static final int RESULT_ERROR_CODE = 1;
|
||||
|
||||
/**
|
||||
* 默认成功信息
|
||||
*/
|
||||
public static final String RESULT_OK_MSG = "操作成功";
|
||||
|
||||
/**
|
||||
* 默认失败信息
|
||||
*/
|
||||
public static final String RESULT_ERROR_MSG = "操作失败";
|
||||
|
||||
/**
|
||||
* 无权限错误码
|
||||
*/
|
||||
public static final int UNAUTHORIZED_CODE = 403;
|
||||
|
||||
/**
|
||||
* 无权限提示信息
|
||||
*/
|
||||
public static final String UNAUTHORIZED_MSG = "没有访问权限";
|
||||
|
||||
/**
|
||||
* 未认证错误码
|
||||
*/
|
||||
public static final int UNAUTHENTICATED_CODE = 401;
|
||||
|
||||
/**
|
||||
* 未认证提示信息
|
||||
*/
|
||||
public static final String UNAUTHENTICATED_MSG = "请先登录";
|
||||
|
||||
/**
|
||||
* 登录过期错误码
|
||||
*/
|
||||
public static final int TOKEN_EXPIRED_CODE = 401;
|
||||
|
||||
/**
|
||||
* 登录过期提示信息
|
||||
*/
|
||||
public static final String TOKEN_EXPIRED_MSG = "登录已过期";
|
||||
|
||||
/**
|
||||
* 非法token错误码
|
||||
*/
|
||||
public static final int BAD_CREDENTIALS_CODE = 401;
|
||||
|
||||
/**
|
||||
* 非法token提示信息
|
||||
*/
|
||||
public static final String BAD_CREDENTIALS_MSG = "请退出重新登录";
|
||||
|
||||
/**
|
||||
* 表示升序的值
|
||||
*/
|
||||
public static final String ORDER_ASC_VALUE = "asc";
|
||||
|
||||
/**
|
||||
* 表示降序的值
|
||||
*/
|
||||
public static final String ORDER_DESC_VALUE = "desc";
|
||||
|
||||
/**
|
||||
* token通过header传递的名称
|
||||
*/
|
||||
public static final String TOKEN_HEADER_NAME = "Authorization";
|
||||
|
||||
/**
|
||||
* token通过参数传递的名称
|
||||
*/
|
||||
public static final String TOKEN_PARAM_NAME = "access_token";
|
||||
|
||||
/**
|
||||
* token认证类型
|
||||
*/
|
||||
public static final String TOKEN_TYPE = "Bearer";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.gxwebsoft.common.core.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 操作日志记录注解
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-21 17:03:08
|
||||
*/
|
||||
@Documented
|
||||
@Target({ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface OperationLog {
|
||||
|
||||
/**
|
||||
* 操作功能
|
||||
*/
|
||||
String value() default "";
|
||||
|
||||
/**
|
||||
* 操作模块
|
||||
*/
|
||||
String module() default "";
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
String comments() default "";
|
||||
|
||||
/**
|
||||
* 是否记录请求参数
|
||||
*/
|
||||
boolean param() default true;
|
||||
|
||||
/**
|
||||
* 是否记录返回结果
|
||||
*/
|
||||
boolean result() default true;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.gxwebsoft.common.core.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 操作日志模块注解
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-01 20:48:16
|
||||
*/
|
||||
@Documented
|
||||
@Target({ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface OperationModule {
|
||||
|
||||
/**
|
||||
* 模块名称
|
||||
*/
|
||||
String value();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.gxwebsoft.common.core.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 查询条件注解
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-01 20:48:16
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
|
||||
public @interface QueryField {
|
||||
|
||||
// 字段名称
|
||||
String value() default "";
|
||||
|
||||
// 查询方式
|
||||
QueryType type() default QueryType.LIKE;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.gxwebsoft.common.core.annotation;
|
||||
|
||||
/**
|
||||
* 查询方式
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-01 20:48:16
|
||||
*/
|
||||
public enum QueryType {
|
||||
// 等于
|
||||
EQ,
|
||||
// 不等于
|
||||
NE,
|
||||
// 大于
|
||||
GT,
|
||||
// 大于等于
|
||||
GE,
|
||||
// 小于
|
||||
LT,
|
||||
// 小于等于
|
||||
LE,
|
||||
// 包含
|
||||
LIKE,
|
||||
// 不包含
|
||||
NOT_LIKE,
|
||||
// 结尾等于
|
||||
LIKE_LEFT,
|
||||
// 开头等于
|
||||
LIKE_RIGHT,
|
||||
// 为NULL
|
||||
IS_NULL,
|
||||
// 不为空
|
||||
IS_NOT_NULL,
|
||||
// IN
|
||||
IN,
|
||||
// NOT IN
|
||||
NOT_IN,
|
||||
// IN条件解析逗号分割
|
||||
IN_STR,
|
||||
// NOT IN条件解析逗号分割
|
||||
NOT_IN_STR
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package com.gxwebsoft.common.core.aspect;
|
||||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.extra.servlet.ServletUtil;
|
||||
import cn.hutool.http.useragent.UserAgent;
|
||||
import cn.hutool.http.useragent.UserAgentUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.annotation.OperationModule;
|
||||
import com.gxwebsoft.common.core.utils.JSONUtil;
|
||||
import com.gxwebsoft.common.system.entity.OperationRecord;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.service.OperationRecordService;
|
||||
import com.gxwebsoft.shop.entity.UserLook;
|
||||
import com.gxwebsoft.shop.service.UserLookService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.*;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 操作日志记录
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-21 16:58:16:05
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class OperationLogAspect {
|
||||
@Resource
|
||||
private OperationRecordService operationRecordService;
|
||||
@Resource
|
||||
private UserLookService userLookService;
|
||||
|
||||
// 参数、返回结果、错误信息等最大保存长度
|
||||
private static final int MAX_LENGTH = 1000;
|
||||
// 用于记录请求耗时
|
||||
private final ThreadLocal<Long> startTime = new ThreadLocal<>();
|
||||
|
||||
@Pointcut("@annotation(com.gxwebsoft.common.core.annotation.OperationLog)")
|
||||
public void operationLog() {
|
||||
}
|
||||
|
||||
@Before("operationLog()")
|
||||
public void doBefore(JoinPoint joinPoint) throws Throwable {
|
||||
startTime.set(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@AfterReturning(pointcut = "operationLog()", returning = "result")
|
||||
public void doAfterReturning(JoinPoint joinPoint, Object result) {
|
||||
saveLog(joinPoint, result, null);
|
||||
}
|
||||
|
||||
@AfterThrowing(value = "operationLog()", throwing = "e")
|
||||
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
|
||||
saveLog(joinPoint, null, e);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存操作记录
|
||||
*/
|
||||
private void saveLog(JoinPoint joinPoint, Object result, Exception e) {
|
||||
OperationRecord record = new OperationRecord();
|
||||
// 记录操作耗时
|
||||
if (startTime.get() != null) {
|
||||
record.setSpendTime(System.currentTimeMillis() - startTime.get());
|
||||
}
|
||||
// 记录当前登录用户id、租户id
|
||||
User user = getLoginUser();
|
||||
if (user != null) {
|
||||
record.setUserId(user.getUserId());
|
||||
record.setTenantId(user.getTenantId());
|
||||
}
|
||||
// 记录请求地址、请求方式、ip
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
HttpServletRequest request = (attributes == null ? null : attributes.getRequest());
|
||||
if (request != null) {
|
||||
record.setUrl(request.getRequestURI());
|
||||
record.setRequestMethod(request.getMethod());
|
||||
UserAgent ua = UserAgentUtil.parse(ServletUtil.getHeaderIgnoreCase(request, "User-Agent"));
|
||||
record.setOs(ua.getPlatform().toString());
|
||||
record.setDevice(ua.getOs().toString());
|
||||
record.setBrowser(ua.getBrowser().toString());
|
||||
record.setIp(ServletUtil.getClientIP(request));
|
||||
}
|
||||
// 记录异常信息
|
||||
if (e != null) {
|
||||
record.setStatus(1);
|
||||
record.setError(StrUtil.sub(e.toString(), 0, MAX_LENGTH));
|
||||
}
|
||||
// 记录模块名、操作功能、请求方法、请求参数、返回结果
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
record.setMethod(joinPoint.getTarget().getClass().getName() + "." + signature.getName());
|
||||
Method method = signature.getMethod();
|
||||
if (method != null) {
|
||||
OperationLog ol = method.getAnnotation(OperationLog.class);
|
||||
if (ol != null) {
|
||||
// 记录操作功能
|
||||
record.setDescription(getDescription(method, ol));
|
||||
// 记录操作模块
|
||||
record.setModule(getModule(joinPoint, ol));
|
||||
// 记录备注
|
||||
if (StrUtil.isNotEmpty(ol.comments())) {
|
||||
record.setComments(ol.comments());
|
||||
}
|
||||
// 记录请求参数
|
||||
if (ol.param() && request != null) {
|
||||
record.setParams(StrUtil.sub(getParams(joinPoint, request), 0, MAX_LENGTH));
|
||||
}
|
||||
// 记录请求结果
|
||||
if (ol.result() && result != null) {
|
||||
record.setResult(StrUtil.sub(JSONUtil.toJSONString(result), 0, MAX_LENGTH));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 记录访客日志
|
||||
// System.out.println("record = " + record);
|
||||
// if (record.getMethod().equals("com.gxwebsoft.love.controller.UserProfileController.detail")) {
|
||||
// final Integer toUserId = Integer.valueOf(StrUtil.removeSuffix(record.getParams()," "));
|
||||
// if (userLookService.count(new LambdaQueryWrapper<UserLook>().eq(UserLook::getUserId,record.getUserId()).eq(UserLook::getToUserId,toUserId)) == 0) {
|
||||
// final UserLook userLook = new UserLook();
|
||||
// userLook.setUserId(record.getUserId());
|
||||
// userLook.setToUserId(toUserId);
|
||||
// userLookService.save(userLook);
|
||||
// }
|
||||
// }
|
||||
|
||||
operationRecordService.saveAsync(record);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录用户
|
||||
*/
|
||||
private User getLoginUser() {
|
||||
Authentication subject = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (subject != null) {
|
||||
Object object = subject.getPrincipal();
|
||||
if (object instanceof User) {
|
||||
return (User) object;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取请求参数
|
||||
*
|
||||
* @param joinPoint JoinPoint
|
||||
* @param request HttpServletRequest
|
||||
* @return String
|
||||
*/
|
||||
private String getParams(JoinPoint joinPoint, HttpServletRequest request) {
|
||||
String params;
|
||||
Map<String, String> paramsMap = ServletUtil.getParamMap(request);
|
||||
if (paramsMap.keySet().size() > 0) {
|
||||
params = JSONUtil.toJSONString(paramsMap);
|
||||
} else {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object arg : joinPoint.getArgs()) {
|
||||
if (ObjectUtil.isNull(arg)
|
||||
|| arg instanceof MultipartFile
|
||||
|| arg instanceof HttpServletRequest
|
||||
|| arg instanceof HttpServletResponse) {
|
||||
continue;
|
||||
}
|
||||
sb.append(JSONUtil.toJSONString(arg)).append(" ");
|
||||
}
|
||||
params = sb.toString();
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取操作模块
|
||||
*
|
||||
* @param joinPoint JoinPoint
|
||||
* @param ol OperationLog
|
||||
* @return String
|
||||
*/
|
||||
private String getModule(JoinPoint joinPoint, OperationLog ol) {
|
||||
if (StrUtil.isNotEmpty(ol.module())) {
|
||||
return ol.module();
|
||||
}
|
||||
OperationModule om = joinPoint.getTarget().getClass().getAnnotation(OperationModule.class);
|
||||
if (om != null && StrUtil.isNotEmpty(om.value())) {
|
||||
return om.value();
|
||||
}
|
||||
Api api = joinPoint.getTarget().getClass().getAnnotation(Api.class);
|
||||
if (api != null && api.tags() != null) {
|
||||
return ArrayUtil.join(api.tags(), ",");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取操作功能
|
||||
*
|
||||
* @param method Method
|
||||
* @param ol OperationLog
|
||||
* @return String
|
||||
*/
|
||||
private String getDescription(Method method, OperationLog ol) {
|
||||
if (StrUtil.isNotEmpty(ol.value())) {
|
||||
return ol.value();
|
||||
}
|
||||
ApiOperation ao = method.getAnnotation(ApiOperation.class);
|
||||
if (ao != null && StrUtil.isNotEmpty(ao.value())) {
|
||||
return ao.value();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* 系统配置属性
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-08-30 17:58:16
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "config")
|
||||
public class ConfigProperties {
|
||||
/**
|
||||
* 文件上传磁盘位置
|
||||
*/
|
||||
private Integer uploadLocation = 0;
|
||||
|
||||
/**
|
||||
* 文件上传是否使用uuid命名
|
||||
*/
|
||||
private Boolean uploadUuidName = true;
|
||||
|
||||
/**
|
||||
* 文件上传生成缩略图的大小(kb)
|
||||
*/
|
||||
private Integer thumbnailSize = 60;
|
||||
|
||||
/**
|
||||
* OpenOffice的安装目录
|
||||
*/
|
||||
private String openOfficeHome;
|
||||
|
||||
/**
|
||||
* swagger扫描包
|
||||
*/
|
||||
private String swaggerBasePackage;
|
||||
|
||||
/**
|
||||
* swagger文档标题
|
||||
*/
|
||||
private String swaggerTitle;
|
||||
|
||||
/**
|
||||
* swagger文档描述
|
||||
*/
|
||||
private String swaggerDescription;
|
||||
|
||||
/**
|
||||
* swagger文档版本号
|
||||
*/
|
||||
private String swaggerVersion;
|
||||
|
||||
/**
|
||||
* swagger地址
|
||||
*/
|
||||
private String swaggerHost;
|
||||
|
||||
/**
|
||||
* token过期时间, 单位秒
|
||||
*/
|
||||
private Long tokenExpireTime = 60 * 60 * 30 * 24L;
|
||||
|
||||
/**
|
||||
* token快要过期自动刷新时间, 单位分钟
|
||||
*/
|
||||
private int tokenRefreshTime = 30;
|
||||
|
||||
/**
|
||||
* 生成token的密钥Key的base64字符
|
||||
*/
|
||||
private String tokenKey;
|
||||
|
||||
/**
|
||||
* 文件上传目录
|
||||
*/
|
||||
private String uploadPath;
|
||||
|
||||
/**
|
||||
* 本地文件上传目录(开发环境)
|
||||
*/
|
||||
private String localUploadPath;
|
||||
|
||||
/**
|
||||
* 文件服务器
|
||||
*/
|
||||
private String fileServer;
|
||||
|
||||
/**
|
||||
* 网关地址
|
||||
*/
|
||||
private String serverUrl;
|
||||
|
||||
/**
|
||||
* 阿里云存储 OSS
|
||||
* Endpoint
|
||||
*/
|
||||
private String endpoint;
|
||||
private String accessKeyId;
|
||||
private String accessKeySecret;
|
||||
private String bucketName;
|
||||
private String bucketDomain;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class HttpMessageConverter extends MappingJackson2HttpMessageConverter {
|
||||
public HttpMessageConverter(){
|
||||
List<MediaType> mediaTypes = new ArrayList<>();
|
||||
mediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
setSupportedMediaTypes(mediaTypes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import net.sf.jsqlparser.expression.Expression;
|
||||
import net.sf.jsqlparser.expression.LongValue;
|
||||
import net.sf.jsqlparser.expression.NullValue;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* MybatisPlus配置
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-02-22 11:29:28
|
||||
*/
|
||||
@Configuration
|
||||
public class MybatisPlusConfig {
|
||||
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor(HttpServletRequest request) {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
|
||||
// 多租户插件配置
|
||||
TenantLineHandler tenantLineHandler = new TenantLineHandler() {
|
||||
@Override
|
||||
public Expression getTenantId() {
|
||||
// String device_id = request.getHeader("device-id");
|
||||
// System.out.println("device_id = " + device_id);
|
||||
// 从设备请求头拿ID
|
||||
String DeviceID = request.getHeader("Device-ID");
|
||||
if (StrUtil.isNotBlank(DeviceID)) {
|
||||
return new LongValue(10048);
|
||||
}
|
||||
// 从请求头拿ID
|
||||
final String tenantId = request.getHeader("tenantId");
|
||||
if(tenantId != null){
|
||||
return new LongValue(tenantId);
|
||||
}
|
||||
return getLoginUserTenantId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean ignoreTable(String tableName) {
|
||||
return Arrays.asList(
|
||||
"sys_dictionary",
|
||||
"sys_dictionary_data",
|
||||
"oa_app",
|
||||
"apps_test_data"
|
||||
).contains(tableName);
|
||||
}
|
||||
};
|
||||
TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor(tenantLineHandler);
|
||||
interceptor.addInnerInterceptor(tenantLineInnerInterceptor);
|
||||
|
||||
// 分页插件配置
|
||||
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
|
||||
interceptor.addInnerInterceptor(paginationInnerInterceptor);
|
||||
|
||||
return interceptor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录用户的租户id
|
||||
*
|
||||
* @return Integer
|
||||
*/
|
||||
public Expression getLoginUserTenantId() {
|
||||
try {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null) {
|
||||
Object object = authentication.getPrincipal();
|
||||
if (object instanceof User) {
|
||||
return new LongValue(((User) object).getTenantId());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
return new NullValue();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
|
||||
@Configuration
|
||||
public class RestTemplateConfig {
|
||||
|
||||
@Bean
|
||||
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
|
||||
RestTemplate restTemplate = new RestTemplate(factory);
|
||||
restTemplate.getMessageConverters().add(new HttpMessageConverter());
|
||||
return restTemplate;
|
||||
}
|
||||
@Bean
|
||||
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
|
||||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
// ms
|
||||
factory.setReadTimeout(60000);
|
||||
// ms
|
||||
factory.setConnectTimeout(60000);
|
||||
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @Author ds
|
||||
* @Date 2022-05-05
|
||||
*/
|
||||
@Component
|
||||
public class SpringContextUtil implements ApplicationContextAware {
|
||||
/**
|
||||
* spring的应用上下文
|
||||
*/
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
/**
|
||||
* 初始化时将应用上下文设置进applicationContext
|
||||
* @param applicationContext
|
||||
* @throws BeansException
|
||||
*/
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
SpringContextUtil.applicationContext=applicationContext;
|
||||
}
|
||||
|
||||
public static ApplicationContext getApplicationContext(){
|
||||
return applicationContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据bean名称获取某个bean对象
|
||||
*
|
||||
* @param name bean名称
|
||||
* @return Object
|
||||
* @throws BeansException
|
||||
*/
|
||||
public static Object getBean(String name) throws BeansException {
|
||||
return applicationContext.getBean(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据bean的class获取某个bean对象
|
||||
* @param beanClass
|
||||
* @param <T>
|
||||
* @return
|
||||
* @throws BeansException
|
||||
*/
|
||||
public static <T> T getBean(Class<T> beanClass) throws BeansException {
|
||||
return applicationContext.getBean(beanClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取spring.profiles.active
|
||||
* @return
|
||||
*/
|
||||
public static String getProfile(){
|
||||
return getApplicationContext().getEnvironment().getActiveProfiles()[0];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import springfox.documentation.builders.ApiInfoBuilder;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.oas.annotations.EnableOpenApi;
|
||||
import springfox.documentation.service.*;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spi.service.contexts.SecurityContext;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Swagger配置
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-02-22 11:29:05
|
||||
*/
|
||||
@EnableOpenApi
|
||||
@Configuration
|
||||
public class SwaggerConfig {
|
||||
@Resource
|
||||
private ConfigProperties config;
|
||||
|
||||
@Bean
|
||||
public Docket createRestApi() {
|
||||
Docket docket = new Docket(DocumentationType.OAS_30);
|
||||
if (StrUtil.isNotBlank(config.getSwaggerHost())) {
|
||||
docket.host(config.getSwaggerHost());
|
||||
}
|
||||
return docket
|
||||
.apiInfo(apiInfo())
|
||||
.select()
|
||||
.apis(RequestHandlerSelectors.basePackage(config.getSwaggerBasePackage()))
|
||||
.paths(PathSelectors.any())
|
||||
.build()
|
||||
.securitySchemes(securitySchemes())
|
||||
.securityContexts(securityContexts());
|
||||
}
|
||||
|
||||
private ApiInfo apiInfo() {
|
||||
return new ApiInfoBuilder()
|
||||
.title(config.getSwaggerTitle())
|
||||
.description(config.getSwaggerDescription())
|
||||
.version(config.getSwaggerVersion())
|
||||
.termsOfServiceUrl("")
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<SecurityScheme> securitySchemes() {
|
||||
return Collections.singletonList(
|
||||
new ApiKey("Authorization", "Authorization", "header")
|
||||
);
|
||||
}
|
||||
|
||||
private List<SecurityContext> securityContexts() {
|
||||
AuthorizationScope[] scopes = {new AuthorizationScope("global", "accessEverything")};
|
||||
List<SecurityReference> references = Collections.singletonList(
|
||||
new SecurityReference("Authorization", scopes)
|
||||
);
|
||||
return Collections.singletonList(SecurityContext.builder()
|
||||
.securityReferences(references)
|
||||
.build());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* WebMvc配置, 拦截器、资源映射等都在此配置
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2019-06-12 10:11:16
|
||||
*/
|
||||
@Configuration
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
/**
|
||||
* 支持跨域访问
|
||||
*/
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedOriginPatterns("*")
|
||||
.allowedHeaders("*")
|
||||
.exposedHeaders(Constants.TOKEN_HEADER_NAME)
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")
|
||||
.allowCredentials(true)
|
||||
.maxAge(3600);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.gxwebsoft.common.core.constants;
|
||||
|
||||
public class BalanceConstants {
|
||||
// 余额变动场景
|
||||
public static final Integer BALANCE_RECHARGE = 10; // 用户充值
|
||||
public static final Integer BALANCE_USE = 20; // 用户消费
|
||||
public static final Integer BALANCE_RE_LET = 21; // 续租
|
||||
public static final Integer BALANCE_ADMIN = 30; // 管理员操作
|
||||
public static final Integer BALANCE_REFUND = 40; // 订单退款
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.gxwebsoft.common.core.constants;
|
||||
|
||||
public class OrderConstants {
|
||||
// 支付方式
|
||||
public static final String PAY_METHOD_BALANCE = "10"; // 余额支付
|
||||
public static final String PAY_METHOD_WX = "20"; // 微信支付
|
||||
public static final String PAY_METHOD_ALIPAY = "30"; // 支付宝支付
|
||||
public static final String PAY_METHOD_OTHER = "40"; // 其他支付
|
||||
|
||||
// 付款状态
|
||||
public static final Integer PAY_STATUS_NO_PAY = 10; // 未付款
|
||||
public static final Integer PAY_STATUS_SUCCESS = 20; // 已付款
|
||||
|
||||
// 发货状态
|
||||
public static final Integer DELIVERY_STATUS_NO = 10; // 未发货
|
||||
public static final Integer DELIVERY_STATUS_YES = 20; // 已发货
|
||||
public static final Integer DELIVERY_STATUS_30 = 30; // 部分发货
|
||||
|
||||
// 收货状态
|
||||
public static final Integer RECEIPT_STATUS_NO = 10; // 未收货
|
||||
public static final Integer RECEIPT_STATUS_YES = 20; // 已收货
|
||||
public static final Integer RECEIPT_STATUS_RETURN = 30; // 已退货
|
||||
|
||||
// 订单状态
|
||||
public static final Integer ORDER_STATUS_DOING = 10; // 进行中
|
||||
public static final Integer ORDER_STATUS_CANCEL = 20; // 已取消
|
||||
public static final Integer ORDER_STATUS_TO_CANCEL = 21; // 待取消
|
||||
public static final Integer ORDER_STATUS_COMPLETED = 30; // 已完成
|
||||
|
||||
// 订单结算状态
|
||||
public static final Integer ORDER_SETTLED_YES = 1; // 已结算
|
||||
public static final Integer ORDER_SETTLED_NO = 0; // 未结算
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.gxwebsoft.common.core.constants;
|
||||
|
||||
public class ProfitConstants {
|
||||
// 收益类型
|
||||
public static final Integer PROFIT_TYPE10 = 10; // 推广收益
|
||||
public static final Integer PROFIT_TYPE20 = 20; // 团队收益
|
||||
public static final Integer PROFIT_TYPE30 = 30; // 门店收益
|
||||
public static final Integer PROFIT_TYPE40 = 30; // 区域收益
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.gxwebsoft.common.core.constants;
|
||||
|
||||
public class RedisConstants {
|
||||
// 短信验证码Key
|
||||
public static final String SMS_CODE_KEY = "sms";
|
||||
// 验证码过期时间
|
||||
public static final Long SMS_CODE_TTL = 5L;
|
||||
// 微信凭证access-token
|
||||
public static final String ACCESS_TOKEN_KEY = "access-token";
|
||||
// 空值防止击穿数据库
|
||||
public static final Long CACHE_NULL_TTL = 2L;
|
||||
// 商户信息
|
||||
public static final String MERCHANT_KEY = "merchant";
|
||||
// 添加商户定位点
|
||||
public static final String MERCHANT_GEO_KEY = "merchant-geo";
|
||||
|
||||
// token
|
||||
public static final String TOKEN_USER_ID = "cache:token:";
|
||||
// 排行榜
|
||||
public static final String USER_RANKING_BY_APPS = "userRankingByApps";
|
||||
// 搜索历史
|
||||
public static final String SEARCH_HISTORY = "searchHistory";
|
||||
// 租户系统设置信息
|
||||
public static final String TEN_ANT_SETTING_KEY = "setting";
|
||||
// 排行榜Key
|
||||
public static final String USER_RANKING_BY_APPS_5 = "cache5:userRankingByApps";
|
||||
|
||||
|
||||
|
||||
// 哗啦啦key
|
||||
public static final String getAllShop = "allShop";
|
||||
public static final String getBaseInfo = "baseInfo";
|
||||
public static final String getFoodClassCategory = "foodCategory";
|
||||
public static final String getOpenFood = "openFood";
|
||||
public static final String haulalaGeoKey = "cache10:hualala-geo";
|
||||
public static final String HLL_CART_KEY = "hll-cart"; // hll-cart[shopId]:[userId]
|
||||
public static final String HLL_CART_FOOD_KEY = "hll-cart-list"; // hll-cart-list[shopId]:[userId]
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.gxwebsoft.common.core.constants;
|
||||
|
||||
public class WxOfficialConstants {
|
||||
// 获取 Access token
|
||||
public static final String GET_ACCESS_TOKEN_API = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.gxwebsoft.common.core.exception;
|
||||
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
|
||||
/**
|
||||
* 自定义业务异常
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-02-22 11:29:28
|
||||
*/
|
||||
public class BusinessException extends RuntimeException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Integer code;
|
||||
|
||||
public BusinessException() {
|
||||
this(Constants.RESULT_ERROR_MSG);
|
||||
}
|
||||
|
||||
public BusinessException(String message) {
|
||||
this(Constants.RESULT_ERROR_CODE, message);
|
||||
}
|
||||
|
||||
public BusinessException(Integer code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public BusinessException(Integer code, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public BusinessException(Integer code, String message, Throwable cause,
|
||||
boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(Integer code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.gxwebsoft.common.core.exception;
|
||||
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-02-22 11:29:30
|
||||
*/
|
||||
@ControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
@ResponseBody
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
public ApiResult<?> methodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e,
|
||||
HttpServletResponse response) {
|
||||
CommonUtil.addCrossHeaders(response);
|
||||
return new ApiResult<>(Constants.RESULT_ERROR_CODE, "请求方式不正确").setError(e.toString());
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public ApiResult<?> accessDeniedExceptionHandler(AccessDeniedException e, HttpServletResponse response) {
|
||||
CommonUtil.addCrossHeaders(response);
|
||||
return new ApiResult<>(Constants.UNAUTHORIZED_CODE, Constants.UNAUTHORIZED_MSG).setError(e.toString());
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ApiResult<?> businessExceptionHandler(BusinessException e, HttpServletResponse response) {
|
||||
CommonUtil.addCrossHeaders(response);
|
||||
return new ApiResult<>(e.getCode(), e.getMessage());
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ExceptionHandler(Throwable.class)
|
||||
public ApiResult<?> exceptionHandler(Throwable e, HttpServletResponse response) {
|
||||
logger.error(e.getMessage(), e);
|
||||
CommonUtil.addCrossHeaders(response);
|
||||
return new ApiResult<>(Constants.RESULT_ERROR_CODE, Constants.RESULT_ERROR_MSG).setError(e.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 没有访问权限异常处理
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-25 00:35:03
|
||||
*/
|
||||
@Component
|
||||
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
|
||||
|
||||
@Override
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
|
||||
throws IOException, ServletException {
|
||||
CommonUtil.responseError(response, Constants.UNAUTHORIZED_CODE, Constants.UNAUTHORIZED_MSG, e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 没有登录异常处理
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-25 00:35:03
|
||||
*/
|
||||
@Component
|
||||
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
|
||||
throws IOException, ServletException {
|
||||
CommonUtil.responseError(response, Constants.UNAUTHENTICATED_CODE, Constants.UNAUTHENTICATED_MSG,
|
||||
e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.system.entity.LoginRecord;
|
||||
import com.gxwebsoft.common.system.entity.Menu;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.service.LoginRecordService;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.ExpiredJwtException;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 处理携带token的请求过滤器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-30 20:48:05
|
||||
*/
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
@Resource
|
||||
private ConfigProperties configProperties;
|
||||
@Resource
|
||||
private UserService userService;
|
||||
@Resource
|
||||
private LoginRecordService loginRecordService;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
String access_token = JwtUtil.getAccessToken(request);
|
||||
if (StrUtil.isNotBlank(access_token)) {
|
||||
try {
|
||||
// 解析token
|
||||
Claims claims = JwtUtil.parseToken(access_token, configProperties.getTokenKey());
|
||||
JwtSubject jwtSubject = JwtUtil.getJwtSubject(claims);
|
||||
User user = userService.getByUsername(jwtSubject.getUsername(), jwtSubject.getTenantId());
|
||||
if (user == null) {
|
||||
throw new UsernameNotFoundException("Username not found");
|
||||
}
|
||||
List<Menu> authorities = user.getAuthorities().stream()
|
||||
.filter(m -> StrUtil.isNotBlank(m.getAuthority())).collect(Collectors.toList());
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
||||
user, null, authorities);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
// token将要过期签发新token, 防止突然退出登录
|
||||
long expiration = (claims.getExpiration().getTime() - new Date().getTime()) / 1000 / 60;
|
||||
if (expiration < configProperties.getTokenRefreshTime()) {
|
||||
String token = JwtUtil.buildToken(jwtSubject, configProperties.getTokenExpireTime(),
|
||||
configProperties.getTokenKey());
|
||||
response.addHeader(Constants.TOKEN_HEADER_NAME, token);
|
||||
loginRecordService.saveAsync(user.getUsername(), LoginRecord.TYPE_REFRESH, null,
|
||||
user.getTenantId(), request);
|
||||
}
|
||||
} catch (ExpiredJwtException e) {
|
||||
CommonUtil.responseError(response, Constants.TOKEN_EXPIRED_CODE, Constants.TOKEN_EXPIRED_MSG,
|
||||
e.getMessage());
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
CommonUtil.responseError(response, Constants.BAD_CREDENTIALS_CODE, Constants.BAD_CREDENTIALS_MSG,
|
||||
e.toString());
|
||||
return;
|
||||
}
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Jwt载体
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-03 00:11:12
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class JwtSubject implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 账号
|
||||
*/
|
||||
private String username;
|
||||
|
||||
/**
|
||||
* 租户id
|
||||
*/
|
||||
private Integer tenantId;
|
||||
|
||||
}
|
||||
152
src/main/java/com/gxwebsoft/common/core/security/JwtUtil.java
Normal file
152
src/main/java/com/gxwebsoft/common/core/security/JwtUtil.java
Normal file
@@ -0,0 +1,152 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.extra.servlet.ServletUtil;
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.utils.JSONUtil;
|
||||
import com.gxwebsoft.shop.entity.Payment;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.io.Encoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.security.Key;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* JWT工具类
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-01-21 16:30:59
|
||||
*/
|
||||
public class JwtUtil {
|
||||
|
||||
/**
|
||||
* 获取请求中的access_token
|
||||
*
|
||||
* @param request HttpServletRequest
|
||||
* @return String
|
||||
*/
|
||||
public static String getAccessToken(HttpServletRequest request) {
|
||||
String access_token = ServletUtil.getHeaderIgnoreCase(request, Constants.TOKEN_HEADER_NAME);
|
||||
if (StrUtil.isNotBlank(access_token)) {
|
||||
if (access_token.startsWith(Constants.TOKEN_TYPE)) {
|
||||
access_token = StrUtil.removePrefix(access_token, Constants.TOKEN_TYPE).trim();
|
||||
}
|
||||
} else {
|
||||
access_token = request.getParameter(Constants.TOKEN_PARAM_NAME);
|
||||
}
|
||||
return access_token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成token
|
||||
*
|
||||
* @param subject 载体
|
||||
* @param expire 过期时间
|
||||
* @param base64EncodedKey base64编码的Key
|
||||
* @return token
|
||||
*/
|
||||
public static String buildToken(JwtSubject subject, Long expire, String base64EncodedKey) {
|
||||
return buildToken(JSONUtil.toJSONString(subject), expire, decodeKey(base64EncodedKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成token
|
||||
*
|
||||
* @param subject 载体
|
||||
* @param expire 过期时间
|
||||
* @param key 密钥
|
||||
* @return token
|
||||
*/
|
||||
public static String buildToken(String subject, Long expire, Key key) {
|
||||
Date expireDate = new Date(new Date().getTime() + 1000 * expire);
|
||||
return Jwts.builder()
|
||||
.setSubject(subject)
|
||||
.setExpiration(expireDate)
|
||||
.setIssuedAt(new Date())
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析token
|
||||
*
|
||||
* @param token token
|
||||
* @param base64EncodedKey base64编码的Key
|
||||
* @return Claims
|
||||
*/
|
||||
public static Claims parseToken(String token, String base64EncodedKey) {
|
||||
return parseToken(token, decodeKey(base64EncodedKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析token
|
||||
*
|
||||
* @param token token
|
||||
* @param key 密钥
|
||||
* @return Claims
|
||||
*/
|
||||
public static Claims parseToken(String token, Key key) {
|
||||
return Jwts.parserBuilder()
|
||||
.setSigningKey(key)
|
||||
.build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取JwtSubject
|
||||
*
|
||||
* @param claims Claims
|
||||
* @return JwtSubject
|
||||
*/
|
||||
public static JwtSubject getJwtSubject(Claims claims) {
|
||||
return JSONUtil.parseObject(claims.getSubject(), JwtSubject.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析支付方式里的json数据
|
||||
*
|
||||
* @param payment Payment
|
||||
* @return Payment
|
||||
*/
|
||||
public static Payment getPaymentConfig(Payment payment){
|
||||
return JSONUtil.parseObject(payment.getConfig(), Payment.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成Key
|
||||
*
|
||||
* @return Key
|
||||
*/
|
||||
public static Key randomKey() {
|
||||
return Keys.secretKeyFor(SignatureAlgorithm.HS256);
|
||||
}
|
||||
|
||||
/**
|
||||
* base64编码key
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String encodeKey(Key key) {
|
||||
return Encoders.BASE64.encode(key.getEncoded());
|
||||
}
|
||||
|
||||
/**
|
||||
* base64编码Key
|
||||
*
|
||||
* @param base64EncodedKey base64编码的key
|
||||
* @return Key
|
||||
*/
|
||||
public static Key decodeKey(String base64EncodedKey) {
|
||||
if (StrUtil.isBlank(base64EncodedKey)) {
|
||||
return null;
|
||||
}
|
||||
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(base64EncodedKey));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* Spring Security配置
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-23 18:04:52
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Resource
|
||||
private JwtAccessDeniedHandler jwtAccessDeniedHandler;
|
||||
@Resource
|
||||
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||
@Resource
|
||||
private JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.antMatchers(HttpMethod.OPTIONS, "/**")
|
||||
.permitAll()
|
||||
.antMatchers(HttpMethod.GET, "/api/file/**","/**", "/api/captcha", "/")
|
||||
.permitAll()
|
||||
.antMatchers(
|
||||
"/api/login",
|
||||
"/api/register",
|
||||
"/druid/**",
|
||||
"/swagger-ui.html",
|
||||
"/swagger-resources/**",
|
||||
"/webjars/**",
|
||||
"/v2/api-docs",
|
||||
"/v3/api-docs",
|
||||
"/swagger-ui/**",
|
||||
"/api/open/**",
|
||||
"/hxz/v1/**",
|
||||
"/api/sendSmsCaptcha",
|
||||
"/api/login-alipay/*",
|
||||
"/api/wx-login/loginByMpWxPhone",
|
||||
"/api/shop/payment/mp-alipay/notify",
|
||||
"/api/shop/payment/mp-alipay/test/**",
|
||||
"/api/shop/payment/mp-alipay/getPhoneNumber",
|
||||
"/api/shop/test/**",
|
||||
"/api/shop/wx-login/**",
|
||||
"/api/apps/hualala/**",
|
||||
"/api/apps/hualala-cart/**",
|
||||
"/api/apps/test-data/**",
|
||||
"/api/wxWorkQrConnect",
|
||||
"/WW_verify_QMv7HoblYU6z63bb.txt",
|
||||
"/5zbYEPkyV4.txt",
|
||||
"/api/love/user-plan-log/wx-pay/**"
|
||||
)
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.sessionManagement()
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
.and()
|
||||
.csrf()
|
||||
.disable()
|
||||
.cors()
|
||||
.and()
|
||||
.logout()
|
||||
.disable()
|
||||
.headers()
|
||||
.frameOptions()
|
||||
.disable()
|
||||
.and()
|
||||
.exceptionHandling()
|
||||
.accessDeniedHandler(jwtAccessDeniedHandler)
|
||||
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
|
||||
.and()
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public BCryptPasswordEncoder bCryptPasswordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alipay.api.AlipayApiException;
|
||||
import com.alipay.api.AlipayConstants;
|
||||
import com.alipay.api.CertAlipayRequest;
|
||||
import com.alipay.api.DefaultAlipayClient;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* 支付宝工具类
|
||||
* @author leng
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class AlipayConfigUtil {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
public Integer tenantId;
|
||||
public String gateway;
|
||||
public JSONObject config;
|
||||
public String appId;
|
||||
public String privateKey;
|
||||
public String appCertPublicKey;
|
||||
public String alipayCertPublicKey;
|
||||
public String alipayRootCert;
|
||||
|
||||
@Resource
|
||||
private ConfigProperties pathConfig;
|
||||
|
||||
public AlipayConfigUtil(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
// 实例化客户端
|
||||
public DefaultAlipayClient alipayClient(Integer tenantId) throws AlipayApiException {
|
||||
this.gateway = "https://openapi.alipay.com/gateway.do";
|
||||
this.tenantId = tenantId;
|
||||
this.payment(tenantId);
|
||||
CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
|
||||
certAlipayRequest.setServerUrl(this.gateway);
|
||||
certAlipayRequest.setAppId(this.appId);
|
||||
certAlipayRequest.setPrivateKey(this.privateKey);
|
||||
certAlipayRequest.setFormat(AlipayConstants.FORMAT_JSON);
|
||||
certAlipayRequest.setCharset(AlipayConstants.CHARSET_UTF8);
|
||||
certAlipayRequest.setSignType(AlipayConstants.SIGN_TYPE_RSA2);
|
||||
certAlipayRequest.setCertPath(this.appCertPublicKey);
|
||||
certAlipayRequest.setAlipayPublicCertPath(this.alipayCertPublicKey);
|
||||
certAlipayRequest.setRootCertPath(this.alipayRootCert);
|
||||
// System.out.println("this.appId = " + this.appId);
|
||||
// System.out.println("this.appId = " + this.gateway);
|
||||
// System.out.println("this.appId = " + this.privateKey);
|
||||
// System.out.println("this.appId = " + this.appCertPublicKey);
|
||||
// System.out.println("this.appId = " + this.alipayCertPublicKey);
|
||||
// System.out.println("this.appId = " + this.alipayRootCert);
|
||||
// System.out.println("this.config = " + this.config);
|
||||
return new DefaultAlipayClient(certAlipayRequest);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取支付宝秘钥
|
||||
*/
|
||||
public JSONObject payment(Integer tenantId) {
|
||||
System.out.println("tenantId = " + tenantId);
|
||||
String key = "cache".concat(tenantId.toString()).concat(":setting:payment");
|
||||
System.out.println("key = " + key);
|
||||
String cache = stringRedisTemplate.opsForValue().get(key);
|
||||
if (cache == null) {
|
||||
throw new BusinessException("支付方式未配置");
|
||||
}
|
||||
// 解析json数据
|
||||
JSONObject payment = JSON.parseObject(cache.getBytes());
|
||||
this.config = payment;
|
||||
this.appId = payment.getString("alipayAppId");
|
||||
this.privateKey = payment.getString("privateKey");
|
||||
this.appCertPublicKey = pathConfig.getUploadPath() + "file" + payment.getString("appCertPublicKey");
|
||||
this.alipayCertPublicKey = pathConfig.getUploadPath() + "file" + payment.getString("alipayCertPublicKey");
|
||||
this.alipayRootCert = pathConfig.getUploadPath() + "file" + payment.getString("alipayRootCert");
|
||||
return payment;
|
||||
}
|
||||
|
||||
public String appId(){
|
||||
return this.appId;
|
||||
}
|
||||
|
||||
public String privateKey(){
|
||||
return this.privateKey;
|
||||
}
|
||||
|
||||
public String appCertPublicKey(){
|
||||
return this.appCertPublicKey;
|
||||
}
|
||||
|
||||
public String alipayCertPublicKey(){
|
||||
return this.alipayCertPublicKey;
|
||||
}
|
||||
|
||||
public String alipayRootCert(){
|
||||
return this.alipayRootCert;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
149
src/main/java/com/gxwebsoft/common/core/utils/BtUtil.java
Normal file
149
src/main/java/com/gxwebsoft/common/core/utils/BtUtil.java
Normal file
@@ -0,0 +1,149 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import com.gxwebsoft.oa.entity.Assets;
|
||||
import com.gxwebsoft.oa.service.AssetsService;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintWriter;
|
||||
import java.math.BigInteger;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 宝塔工具类
|
||||
* @author 科技小王子
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class BtUtil {
|
||||
public static Integer tenantId;
|
||||
public static String server;
|
||||
public static String token;
|
||||
private static String timestamp;
|
||||
@Resource
|
||||
private AssetsService assetsService;
|
||||
|
||||
// 实例化客户端
|
||||
public BtUtil client(Integer id) {
|
||||
Assets assets = assetsService.getByIdRel(id);
|
||||
try {
|
||||
String btSign = assets.getBtSign();
|
||||
server = "http://".concat(assets.getCode()).concat(":9003");
|
||||
String url = "http://".concat(assets.getCode()) + ":9003/system?action=GetSystemTotal";
|
||||
timestamp = (new Date().getTime()+"");
|
||||
String md5Sign = getMd5(btSign);
|
||||
String temp = timestamp+md5Sign;
|
||||
token = getMd5(temp);
|
||||
|
||||
String json = "request_time="+timestamp+"&request_token="+token;
|
||||
String responseText = sendPost(url,json);
|
||||
System.out.println("responseText = " + responseText);
|
||||
System.out.println(responseText);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getSystemTotal(){
|
||||
String url = server.concat("/system?action=GetSystemTotal");
|
||||
String json = "request_time="+timestamp+"&request_token="+token;
|
||||
String responseText = sendPost(url,json);
|
||||
System.out.println("responseText = " + responseText);
|
||||
return responseText;
|
||||
}
|
||||
|
||||
public String getDiskInfo(){
|
||||
String url = server.concat("/system?action=GetDiskInfo");
|
||||
String json = "request_time="+timestamp+"&request_token="+token;
|
||||
return sendPost(url,json);
|
||||
}
|
||||
|
||||
// public void config()
|
||||
// {
|
||||
// try {
|
||||
// System.out.println("tenantId = " + tenantId);
|
||||
// String btSign = "XXXXXXXXXXXXXXXXXXXXXXXX";
|
||||
// String url = "http://XXX.XXX.XXX.XXX:8888/system?action=GetSystemTotal";
|
||||
// String timestamp = (new Date().getTime()+"");
|
||||
// String md5Sign = getMd5(btSign);
|
||||
// String temp = timestamp+md5Sign;
|
||||
// String token = getMd5(temp);
|
||||
//
|
||||
// String json = "request_time="+timestamp+"&request_token="+token;
|
||||
// String responseText = sendPost(url,json);
|
||||
// System.out.println(responseText);
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
|
||||
public static String getMd5(String str) throws Exception
|
||||
{
|
||||
try {
|
||||
// 生成一个MD5加密计算摘要
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
// 计算md5函数
|
||||
md.update(str.getBytes());
|
||||
// digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
|
||||
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
|
||||
return new BigInteger(1, md.digest()).toString(16);
|
||||
} catch (Exception e) {
|
||||
throw new Exception("MD5加密出现错误,"+e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public static String sendPost(String url, String param) {
|
||||
PrintWriter out = null;
|
||||
BufferedReader in = null;
|
||||
StringBuffer result = new StringBuffer();
|
||||
try {
|
||||
URL realUrl = new URL(url);
|
||||
// 打开和URL之间的连接
|
||||
URLConnection conn = realUrl.openConnection();
|
||||
// 设置通用的请求属性
|
||||
conn.setRequestProperty("accept", "text/xml,text/javascript,text/html,application/json");
|
||||
conn.setRequestProperty("connection", "Keep-Alive");
|
||||
// 发送POST请求必须设置如下两行
|
||||
conn.setDoOutput(true);
|
||||
conn.setDoInput(true);
|
||||
// 获取URLConnection对象对应的输出流
|
||||
out = new PrintWriter(conn.getOutputStream());
|
||||
// 发送请求参数
|
||||
out.print(param);
|
||||
// flush输出流的缓冲
|
||||
out.flush();
|
||||
// 定义BufferedReader输入流来读取URL的响应
|
||||
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
result.append(line);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("发送 POST 请求出现异常!"+e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
//使用finally块来关闭输出流、输入流
|
||||
finally{
|
||||
try{
|
||||
if(out!=null){
|
||||
out.close();
|
||||
}
|
||||
if(in!=null){
|
||||
in.close();
|
||||
}
|
||||
}
|
||||
catch(IOException ex){
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
}
|
||||
264
src/main/java/com/gxwebsoft/common/core/utils/CacheClient.java
Normal file
264
src/main/java/com/gxwebsoft/common/core/utils/CacheClient.java
Normal file
@@ -0,0 +1,264 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.result.RedisResult;
|
||||
import org.springframework.data.geo.Point;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static com.gxwebsoft.common.core.constants.RedisConstants.CACHE_NULL_TTL;
|
||||
|
||||
@Component
|
||||
public class CacheClient {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
public static Integer tenantId;
|
||||
|
||||
public CacheClient(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param entity 实体类对象
|
||||
* 示例 cacheClient.set("merchant:"+id,merchant)
|
||||
*/
|
||||
public <T> void set(String key, T entity){
|
||||
stringRedisTemplate.opsForValue().set(prefix(key), JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param entity 实体类对象
|
||||
* 示例 cacheClient.set("merchant:"+id,merchant,1L,TimeUnit.DAYS)
|
||||
*/
|
||||
public <T> void set(String key, T entity, Long time, TimeUnit unit){
|
||||
stringRedisTemplate.opsForValue().set(prefix(key), JSONUtil.toJSONString(entity),time,unit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存
|
||||
* @param key [表名]:id
|
||||
* 示例 cacheClient.get(key)
|
||||
* @return merchant
|
||||
*/
|
||||
public String get(String key) {
|
||||
return stringRedisTemplate.opsForValue().get(prefix(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param clazz Merchant.class
|
||||
* @param <T>
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
* @return merchant
|
||||
*/
|
||||
public <T> T get(String key, Class<T> clazz) {
|
||||
String json = stringRedisTemplate.opsForValue().get(prefix(key));
|
||||
if(StrUtil.isNotBlank(json)){
|
||||
return JSONUtil.parseObject(json, clazz);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写redis缓存(哈希类型)
|
||||
* @param key [表名]:id
|
||||
* @param field 字段
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
*/
|
||||
public <T> void hPut(String key, String field, T entity) {
|
||||
stringRedisTemplate.opsForHash().put(prefix(key),field,JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
/**
|
||||
* 写redis缓存(哈希类型)
|
||||
* @param key [表名]:id
|
||||
* @param map 字段
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
*/
|
||||
public void hPutAll(String key, Map<String,String> map) {
|
||||
stringRedisTemplate.opsForHash().putAll(prefix(key),map);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存(哈希类型)
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
* @param key [表名]:id
|
||||
* @param field 字段
|
||||
* @return merchant
|
||||
*/
|
||||
public <T> T hGet(String key, String field, Class<T> clazz) {
|
||||
Object obj = stringRedisTemplate.opsForHash().get(prefix(key), field);
|
||||
return JSONUtil.parseObject(JSONUtil.toJSONString(obj),clazz);
|
||||
}
|
||||
|
||||
public List<Object> hValues(String key){
|
||||
return stringRedisTemplate.opsForHash().values(prefix(key));
|
||||
}
|
||||
|
||||
public Long hSize(String key){
|
||||
return stringRedisTemplate.opsForHash().size(prefix(key));
|
||||
}
|
||||
|
||||
// 逻辑过期方式写入redis
|
||||
public <T> void setWithLogicalExpire(String key, T value, Long time, TimeUnit unit){
|
||||
// 设置逻辑过期时间
|
||||
final RedisResult<T> redisResult = new RedisResult<>();
|
||||
redisResult.setData(value);
|
||||
redisResult.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
|
||||
stringRedisTemplate.opsForValue().set(prefix(key),JSONUtil.toJSONString(redisResult));
|
||||
}
|
||||
|
||||
// 读取redis
|
||||
public <R,ID> R query(String keyPrefix, ID id, Class<R> clazz, Function<ID,R> dbFallback, Long time, TimeUnit unit){
|
||||
String key = keyPrefix + id;
|
||||
// 1.从redis查询缓存
|
||||
final String json = stringRedisTemplate.opsForValue().get(prefix(key));
|
||||
// 2.判断是否存在
|
||||
if (StrUtil.isNotBlank(json)) {
|
||||
// 3.存在,直接返回
|
||||
return JSONUtil.parseObject(json,clazz);
|
||||
}
|
||||
// 判断命中的是否为空值
|
||||
if (json != null) {
|
||||
return null;
|
||||
}
|
||||
// 4. 不存在,跟进ID查询数据库
|
||||
R r = dbFallback.apply(id);
|
||||
// 5. 数据库不存在,返回错误
|
||||
if(r == null){
|
||||
// 空值写入数据库
|
||||
this.set(prefix(key),"",CACHE_NULL_TTL,TimeUnit.MINUTES);
|
||||
return null;
|
||||
}
|
||||
// 写入redis
|
||||
this.set(prefix(key),r,time,unit);
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加商户定位点
|
||||
* @param key geo
|
||||
* @param id
|
||||
* 示例 cacheClient.geoAdd("merchant-geo",merchant)
|
||||
*/
|
||||
public <T> void geoAdd(String key, Double x, Double y, String id){
|
||||
stringRedisTemplate.opsForGeo().add(prefix(key),new Point(x,y),id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除定位
|
||||
* @param key geo
|
||||
* @param id
|
||||
* 示例 cacheClient.geoRemove("merchant-geo",id)
|
||||
*/
|
||||
public void geoRemove(String key, Integer id){
|
||||
stringRedisTemplate.opsForGeo().remove(prefix(key),id.toString());
|
||||
}
|
||||
|
||||
|
||||
|
||||
public <T> void sAdd(String key, T entity){
|
||||
stringRedisTemplate.opsForSet().add(prefix(key),JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
public <T> Set<String> sMembers(String key){
|
||||
return stringRedisTemplate.opsForSet().members(prefix(key));
|
||||
}
|
||||
|
||||
// 更新排行榜
|
||||
public void zAdd(String key, Integer userId, Double value) {
|
||||
stringRedisTemplate.opsForZSet().add(prefix(key),userId.toString(),value);
|
||||
}
|
||||
// 增加元素的score值,并返回增加后的值
|
||||
public Double zIncrementScore(String key,Integer userId, Double delta){
|
||||
return stringRedisTemplate.opsForZSet().incrementScore(key, userId.toString(), delta);
|
||||
}
|
||||
// 获取排名榜
|
||||
public Set<String> range(String key, Integer start, Integer end) {
|
||||
return stringRedisTemplate.opsForZSet().range(prefix(key), start, end);
|
||||
}
|
||||
// 获取排名榜
|
||||
public Set<String> reverseRange(String key, Integer start, Integer end){
|
||||
return stringRedisTemplate.opsForZSet().reverseRange(prefix(key), start, end);
|
||||
}
|
||||
// 获取分数
|
||||
public Double score(String key, Object value){
|
||||
return stringRedisTemplate.opsForZSet().score(prefix(key), value);
|
||||
}
|
||||
|
||||
public void delete(String key){
|
||||
stringRedisTemplate.delete(prefix(key));
|
||||
}
|
||||
|
||||
// 存储在list头部
|
||||
public void leftPush(String key, String keyword){
|
||||
stringRedisTemplate.opsForList().leftPush(prefix(key),keyword);
|
||||
}
|
||||
|
||||
// 获取列表指定范围内的元素
|
||||
public List<String> listRange(String key,Long start, Long end){
|
||||
return stringRedisTemplate.opsForList().range(prefix(key), start, end);
|
||||
}
|
||||
|
||||
// 获取列表长度
|
||||
public Long listSize(String key){
|
||||
return stringRedisTemplate.opsForList().size(prefix(key));
|
||||
}
|
||||
|
||||
// 裁剪list
|
||||
public void listTrim(String key){
|
||||
stringRedisTemplate.opsForList().trim(prefix(key), 0L, 100L);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取后台系统设置信息
|
||||
* @param keyName 键名wx-word
|
||||
* @param tenantId 租户ID
|
||||
* @return
|
||||
* key示例 cache10048:setting:wx-work
|
||||
*/
|
||||
public JSONObject getSettingInfo(String keyName,Integer tenantId){
|
||||
String key = "cache" + tenantId + ":setting:" + keyName;
|
||||
final String cache = stringRedisTemplate.opsForValue().get(key);
|
||||
assert cache != null;
|
||||
return JSON.parseObject(cache);
|
||||
}
|
||||
|
||||
/**
|
||||
* KEY前缀
|
||||
* cache[tenantId]:[key+id]
|
||||
*/
|
||||
public static String prefix(String key){
|
||||
String prefix = "cache";
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null) {
|
||||
Object object = authentication.getPrincipal();
|
||||
if (object instanceof User) {
|
||||
final Integer tenantId = ((User) object).getTenantId();
|
||||
prefix = prefix.concat(tenantId.toString()).concat(":");
|
||||
}
|
||||
}
|
||||
return prefix.concat(key);
|
||||
}
|
||||
|
||||
// 组装key
|
||||
public String key(String name,Integer id){
|
||||
return name.concat(":").concat(id.toString());
|
||||
}
|
||||
}
|
||||
235
src/main/java/com/gxwebsoft/common/core/utils/CommonUtil.java
Normal file
235
src/main/java/com/gxwebsoft/common/core/utils/CommonUtil.java
Normal file
@@ -0,0 +1,235 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.date.DatePattern;
|
||||
import cn.hutool.core.date.DateTime;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* 常用工具方法
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:22
|
||||
*/
|
||||
public class CommonUtil {
|
||||
// 生成uuid的字符
|
||||
private static final String[] chars = new String[]{
|
||||
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
|
||||
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
|
||||
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
|
||||
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
|
||||
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
|
||||
};
|
||||
|
||||
/**
|
||||
* 生成8位uuid
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String randomUUID8() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
String str = uuid.substring(i * 4, i * 4 + 4);
|
||||
int x = Integer.parseInt(str, 16);
|
||||
sb.append(chars[x % 0x3E]);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成16位uuid
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String randomUUID16() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||
for (int i = 0; i < 16; i++) {
|
||||
String str = uuid.substring(i * 2, i * 2 + 2);
|
||||
int x = Integer.parseInt(str, 16);
|
||||
sb.append(chars[x % 0x3E]);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时间
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String currentTime() {
|
||||
Date date = new Date();
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
|
||||
return sdf.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成10位随机用户名
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String randomUsername(String prefix) {
|
||||
Date date = new Date();
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
|
||||
String currentTime = sdf.format(date);
|
||||
return prefix + currentTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成订单号
|
||||
* 20233191166110426
|
||||
* 20230419135802391412
|
||||
* @return
|
||||
*/
|
||||
public static String createOrderNo() {
|
||||
String prefix = DateTime.now().toString(DatePattern.PURE_DATETIME_PATTERN);
|
||||
return prefix + RandomUtil.randomNumbers(2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成订单号
|
||||
* @param tenantId
|
||||
* 20233191166110426
|
||||
* 20230419135802391412
|
||||
* @return
|
||||
*/
|
||||
public static String createOrderNo(String tenantId) {
|
||||
String prefix = DateTime.now().toString(DatePattern.PURE_DATETIME_PATTERN);
|
||||
return prefix + tenantId + RandomUtil.randomNumbers(2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成订单水流号
|
||||
* @param tenantId
|
||||
* @return
|
||||
*/
|
||||
public static String serialNo(int tenantId) {
|
||||
String prefix = DateTime.now().toString(DatePattern.PURE_DATETIME_PATTERN);
|
||||
return prefix + tenantId + RandomUtil.randomNumbers(2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查List是否有重复元素
|
||||
*
|
||||
* @param list List
|
||||
* @param mapper 获取需要检查的字段的Function
|
||||
* @param <T> 数据的类型
|
||||
* @param <R> 需要检查的字段的类型
|
||||
* @return boolean
|
||||
*/
|
||||
public static <T, R> boolean checkRepeat(List<T> list, Function<? super T, ? extends R> mapper) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
for (int j = 0; j < list.size(); j++) {
|
||||
if (i != j && mapper.apply(list.get(i)).equals(mapper.apply(list.get(j)))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* List转为树形结构
|
||||
*
|
||||
* @param data List
|
||||
* @param parentId 顶级的parentId
|
||||
* @param parentIdMapper 获取parentId的Function
|
||||
* @param idMapper 获取id的Function
|
||||
* @param consumer 赋值children的Consumer
|
||||
* @param <T> 数据的类型
|
||||
* @param <R> parentId的类型
|
||||
* @return List<T>
|
||||
*/
|
||||
public static <T, R> List<T> toTreeData(List<T> data, R parentId,
|
||||
Function<? super T, ? extends R> parentIdMapper,
|
||||
Function<? super T, ? extends R> idMapper,
|
||||
BiConsumer<T, List<T>> consumer) {
|
||||
List<T> result = new ArrayList<>();
|
||||
for (T d : data) {
|
||||
R dParentId = parentIdMapper.apply(d);
|
||||
if (ObjectUtil.equals(parentId, dParentId)) {
|
||||
R dId = idMapper.apply(d);
|
||||
List<T> children = toTreeData(data, dId, parentIdMapper, idMapper, consumer);
|
||||
consumer.accept(d, children);
|
||||
result.add(d);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 遍历树形结构数据
|
||||
*
|
||||
* @param data List
|
||||
* @param consumer 回调
|
||||
* @param mapper 获取children的Function
|
||||
* @param <T> 数据的类型
|
||||
*/
|
||||
public static <T> void eachTreeData(List<T> data, Consumer<T> consumer, Function<T, List<T>> mapper) {
|
||||
for (T d : data) {
|
||||
consumer.accept(d);
|
||||
List<T> children = mapper.apply(d);
|
||||
if (children != null && children.size() > 0) {
|
||||
eachTreeData(children, consumer, mapper);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取集合中的第一条数据
|
||||
*
|
||||
* @param records 集合
|
||||
* @return 第一条数据
|
||||
*/
|
||||
public static <T> T listGetOne(List<T> records) {
|
||||
return records == null || records.size() == 0 ? null : records.get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 支持跨域
|
||||
*
|
||||
* @param response HttpServletResponse
|
||||
*/
|
||||
public static void addCrossHeaders(HttpServletResponse response) {
|
||||
response.setHeader("Access-Control-Max-Age", "3600");
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "*");
|
||||
response.setHeader("Access-Control-Allow-Headers", "*");
|
||||
response.setHeader("Access-Control-Expose-Headers", Constants.TOKEN_HEADER_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出错误信息
|
||||
*
|
||||
* @param response HttpServletResponse
|
||||
* @param code 错误码
|
||||
* @param message 提示信息
|
||||
* @param error 错误信息
|
||||
*/
|
||||
public static void responseError(HttpServletResponse response, Integer code, String message, String error) {
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
try {
|
||||
PrintWriter out = response.getWriter();
|
||||
out.write(JSONUtil.toJSONString(new ApiResult<>(code, message, null, error)));
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.img.ImgUtil;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.io.IORuntimeException;
|
||||
import cn.hutool.core.io.IoUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.apache.tika.Tika;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URLEncoder;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 文件上传下载工具类
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-14 08:38:53
|
||||
*/
|
||||
public class FileServerUtil {
|
||||
// 除 text/* 外也需要设置输出编码的 content-type
|
||||
private final static List<String> SET_CHARSET_CONTENT_TYPES = Arrays.asList(
|
||||
"application/json",
|
||||
"application/javascript"
|
||||
);
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
*
|
||||
* @param file MultipartFile
|
||||
* @param directory 文件保存的目录
|
||||
* @param uuidName 是否用uuid命名
|
||||
* @return File
|
||||
*/
|
||||
public static File upload(MultipartFile file, String directory, boolean uuidName)
|
||||
throws IOException, IllegalStateException {
|
||||
File outFile = getUploadFile(file.getOriginalFilename(), directory, uuidName);
|
||||
if (!outFile.getParentFile().exists()) {
|
||||
if (!outFile.getParentFile().mkdirs()) {
|
||||
throw new RuntimeException("make directory fail");
|
||||
}
|
||||
}
|
||||
file.transferTo(outFile);
|
||||
return outFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传base64格式文件
|
||||
*
|
||||
* @param base64 base64编码字符
|
||||
* @param fileName 文件名称, 为空使用uuid命名
|
||||
* @param directory 文件保存的目录
|
||||
* @return File
|
||||
*/
|
||||
public static File upload(String base64, String fileName, String directory)
|
||||
throws FileNotFoundException, IORuntimeException {
|
||||
if (StrUtil.isBlank(base64) || !base64.startsWith("data:image/") || !base64.contains(";base64,")) {
|
||||
throw new RuntimeException("base64 data error");
|
||||
}
|
||||
String suffix = "." + base64.substring(11, base64.indexOf(";")); // 获取文件后缀
|
||||
boolean uuidName = StrUtil.isBlank(fileName);
|
||||
File outFile = getUploadFile(uuidName ? suffix : fileName, directory, uuidName);
|
||||
byte[] bytes = Base64.getDecoder().decode(base64.substring(base64.indexOf(";") + 8).getBytes());
|
||||
IoUtil.write(new FileOutputStream(outFile), true, bytes);
|
||||
return outFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取上传文件位置
|
||||
*
|
||||
* @param name 文件名称
|
||||
* @param directory 上传目录
|
||||
* @param uuidName 是否使用uuid命名
|
||||
* @return File
|
||||
*/
|
||||
public static File getUploadFile(String name, String directory, boolean uuidName) {
|
||||
// 当前日期作为上传子目录
|
||||
String dir = new SimpleDateFormat("yyyyMMdd/").format(new Date());
|
||||
// 获取文件后缀
|
||||
String suffix = (name == null || !name.contains(".")) ? "" : name.substring(name.lastIndexOf("."));
|
||||
// 使用uuid命名
|
||||
if (uuidName || name == null) {
|
||||
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
|
||||
return new File(directory, dir + uuid + suffix);
|
||||
}
|
||||
// 使用原名称, 存在相同则加(1)
|
||||
File file = new File(directory, dir + name);
|
||||
String prefix = StrUtil.removeSuffix(name, suffix);
|
||||
int sameSize = 2;
|
||||
while (file.exists()) {
|
||||
file = new File(directory, dir + prefix + "(" + sameSize + ")" + suffix);
|
||||
sameSize++;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看文件, 支持断点续传
|
||||
*
|
||||
* @param file 文件
|
||||
* @param pdfDir office转pdf输出目录
|
||||
* @param officeHome openOffice安装目录
|
||||
* @param response HttpServletResponse
|
||||
* @param request HttpServletRequest
|
||||
*/
|
||||
public static void preview(File file, String pdfDir, String officeHome,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
preview(file, false, null, pdfDir, officeHome, response, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看文件, 支持断点续传
|
||||
*
|
||||
* @param file 文件
|
||||
* @param forceDownload 是否强制下载
|
||||
* @param fileName 强制下载的文件名称
|
||||
* @param pdfDir office转pdf输出目录
|
||||
* @param officeHome openOffice安装目录
|
||||
* @param response HttpServletResponse
|
||||
* @param request HttpServletRequest
|
||||
*/
|
||||
public static void preview(File file, boolean forceDownload, String fileName, String pdfDir, String officeHome,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
CommonUtil.addCrossHeaders(response);
|
||||
if (file == null || !file.exists()) {
|
||||
outNotFund(response);
|
||||
return;
|
||||
}
|
||||
if (forceDownload) {
|
||||
setDownloadHeader(response, StrUtil.isBlank(fileName) ? file.getName() : fileName);
|
||||
} else {
|
||||
// office转pdf预览
|
||||
if (OpenOfficeUtil.canConverter(file.getName())) {
|
||||
File pdfFile = OpenOfficeUtil.converterToPDF(file.getAbsolutePath(), pdfDir, officeHome);
|
||||
if (pdfFile != null) {
|
||||
file = pdfFile;
|
||||
}
|
||||
}
|
||||
// 获取文件类型
|
||||
String contentType = getContentType(file);
|
||||
if (contentType != null) {
|
||||
response.setContentType(contentType);
|
||||
// 设置编码
|
||||
if (contentType.startsWith("text/") || SET_CHARSET_CONTENT_TYPES.contains(contentType)) {
|
||||
try {
|
||||
String charset = JChardetFacadeUtil.detectCodepage(file.toURI().toURL());
|
||||
if (charset != null) {
|
||||
response.setCharacterEncoding(charset);
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
setDownloadHeader(response, file.getName());
|
||||
}
|
||||
}
|
||||
response.setHeader("Cache-Control", "public");
|
||||
output(file, response, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看缩略图
|
||||
*
|
||||
* @param file 原文件
|
||||
* @param thumbnail 缩略图文件
|
||||
* @param size 缩略图文件的最大值(kb)
|
||||
* @param response HttpServletResponse
|
||||
* @param request HttpServletRequest
|
||||
*/
|
||||
public static void previewThumbnail(File file, File thumbnail, Integer size,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
// 如果是图片并且缩略图不存在则生成
|
||||
if (!thumbnail.exists() && isImage(file)) {
|
||||
long fileSize = file.length();
|
||||
if ((fileSize / 1024) > size) {
|
||||
try {
|
||||
if (thumbnail.getParentFile().mkdirs()) {
|
||||
System.out.println("生成缩略图1>>>>>>>>>>>>>>>> = " + thumbnail);
|
||||
ImgUtil.scale(file, thumbnail, size / (fileSize / 1024f));
|
||||
if (thumbnail.exists() && thumbnail.length() > file.length()) {
|
||||
FileUtil.copy(file, thumbnail, true);
|
||||
}
|
||||
}else{
|
||||
System.out.println("生成缩略图2>>>>>>>>>>>>>>>> = " + thumbnail);
|
||||
ImgUtil.scale(file, thumbnail, size / (fileSize / 1024f));
|
||||
if (thumbnail.exists() && thumbnail.length() > file.length()) {
|
||||
FileUtil.copy(file, thumbnail, true);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
preview(file, null, null, response, request);
|
||||
return;
|
||||
}
|
||||
}
|
||||
preview(thumbnail.exists() ? thumbnail : file, null, null, response, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出文件流, 支持断点续传
|
||||
*
|
||||
* @param file 文件
|
||||
* @param response HttpServletResponse
|
||||
* @param request HttpServletRequest
|
||||
*/
|
||||
public static void output(File file, HttpServletResponse response, HttpServletRequest request) {
|
||||
long length = file.length(); // 文件总大小
|
||||
long start = 0, to = length - 1; // 开始读取位置, 结束读取位置
|
||||
long lastModified = file.lastModified(); // 文件修改时间
|
||||
response.setHeader("Accept-Ranges", "bytes");
|
||||
response.setHeader("ETag", "\"" + length + "-" + lastModified + "\"");
|
||||
response.setHeader("Last-Modified", new Date(lastModified).toString());
|
||||
String range = request.getHeader("Range");
|
||||
if (range != null) {
|
||||
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||
String[] ranges = range.replace("bytes=", "").split("-");
|
||||
start = Long.parseLong(ranges[0].trim());
|
||||
if (ranges.length > 1) {
|
||||
to = Long.parseLong(ranges[1].trim());
|
||||
}
|
||||
response.setHeader("Content-Range", "bytes " + start + "-" + to + "/" + length);
|
||||
}
|
||||
response.setHeader("Content-Length", String.valueOf(to - start + 1));
|
||||
try {
|
||||
output(file, response.getOutputStream(), 2048, start, to);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出文件流
|
||||
*
|
||||
* @param file 文件
|
||||
* @param os 输出流
|
||||
*/
|
||||
public static void output(File file, OutputStream os) {
|
||||
output(file, os, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出文件流
|
||||
*
|
||||
* @param file 文件
|
||||
* @param os 输出流
|
||||
* @param size 读取缓冲区大小
|
||||
*/
|
||||
public static void output(File file, OutputStream os, Integer size) {
|
||||
output(file, os, size, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出文件流, 支持分片
|
||||
*
|
||||
* @param file 文件
|
||||
* @param os 输出流
|
||||
* @param size 读取缓冲区大小
|
||||
* @param start 开始位置
|
||||
* @param to 结束位置
|
||||
*/
|
||||
public static void output(File file, OutputStream os, Integer size, Long start, Long to) {
|
||||
BufferedInputStream is = null;
|
||||
try {
|
||||
is = new BufferedInputStream(new FileInputStream(file));
|
||||
if (start != null) {
|
||||
long skip = is.skip(start);
|
||||
if (skip < start) {
|
||||
System.out.println("ERROR: skip fail[ skipped=" + skip + ", start= " + start + " ]");
|
||||
}
|
||||
to = to - start + 1;
|
||||
}
|
||||
byte[] bytes = new byte[size == null ? 2048 : size];
|
||||
int len;
|
||||
if (to == null) {
|
||||
while ((len = is.read(bytes)) != -1) {
|
||||
os.write(bytes, 0, len);
|
||||
}
|
||||
} else {
|
||||
while (to > 0 && (len = is.read(bytes)) != -1) {
|
||||
os.write(bytes, 0, to < len ? (int) ((long) to) : len);
|
||||
to -= len;
|
||||
}
|
||||
}
|
||||
os.flush();
|
||||
} catch (IOException ignored) {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (os != null) {
|
||||
try {
|
||||
os.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
if (is != null) {
|
||||
try {
|
||||
is.close();
|
||||
} catch (IOException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件类型
|
||||
*
|
||||
* @param file 文件
|
||||
* @return String
|
||||
*/
|
||||
public static String getContentType(File file) {
|
||||
String contentType = null;
|
||||
if (file.exists()) {
|
||||
try {
|
||||
contentType = new Tika().detect(file);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return contentType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文件是否是图片类型
|
||||
*
|
||||
* @param file 文件
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean isImage(File file) {
|
||||
return isImage(getContentType(file));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文件是否是图片类型
|
||||
*
|
||||
* @param contentType 文件类型
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean isImage(String contentType) {
|
||||
return contentType != null && contentType.startsWith("image/");
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置下载文件的header
|
||||
*
|
||||
* @param response HttpServletResponse
|
||||
* @param fileName 文件名称
|
||||
*/
|
||||
public static void setDownloadHeader(HttpServletResponse response, String fileName) {
|
||||
response.setContentType("application/force-download");
|
||||
try {
|
||||
fileName = URLEncoder.encode(fileName, "utf-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出404错误页面
|
||||
*
|
||||
* @param response HttpServletResponse
|
||||
*/
|
||||
public static void outNotFund(HttpServletResponse response) {
|
||||
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
|
||||
outMessage("404 Not Found", null, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出错误页面
|
||||
*
|
||||
* @param title 标题
|
||||
* @param message 内容
|
||||
* @param response HttpServletResponse
|
||||
*/
|
||||
public static void outMessage(String title, String message, HttpServletResponse response) {
|
||||
response.setContentType("text/html;charset=UTF-8");
|
||||
try {
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.write("<!doctype html>");
|
||||
writer.write("<title>" + title + "</title>");
|
||||
writer.write("<h1 style=\"text-align: center\">" + title + "</h1>");
|
||||
if (message != null) {
|
||||
writer.write(message);
|
||||
}
|
||||
writer.write("<hr/><p style=\"text-align: center\">WebSoft File Server</p>");
|
||||
writer.flush();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
311
src/main/java/com/gxwebsoft/common/core/utils/HttpUtils.java
Normal file
311
src/main/java/com/gxwebsoft/common/core/utils/HttpUtils.java
Normal file
@@ -0,0 +1,311 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.HttpDelete;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpPut;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.conn.ssl.SSLSocketFactory;
|
||||
import org.apache.http.entity.ByteArrayEntity;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpUtils {
|
||||
|
||||
/**
|
||||
* get
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doGet(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpGet request = new HttpGet(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* post form
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @param bodys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doPost(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys,
|
||||
Map<String, String> bodys)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpPost request = new HttpPost(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
if (bodys != null) {
|
||||
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
|
||||
|
||||
for (String key : bodys.keySet()) {
|
||||
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
|
||||
}
|
||||
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
|
||||
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
|
||||
request.setEntity(formEntity);
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Post String
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @param body
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doPost(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys,
|
||||
String body)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpPost request = new HttpPost(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(body)) {
|
||||
request.setEntity(new StringEntity(body, "utf-8"));
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Post stream
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @param body
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doPost(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys,
|
||||
byte[] body)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpPost request = new HttpPost(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
if (body != null) {
|
||||
request.setEntity(new ByteArrayEntity(body));
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Put String
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @param body
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doPut(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys,
|
||||
String body)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpPut request = new HttpPut(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(body)) {
|
||||
request.setEntity(new StringEntity(body, "utf-8"));
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Put stream
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @param body
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doPut(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys,
|
||||
byte[] body)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpPut request = new HttpPut(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
if (body != null) {
|
||||
request.setEntity(new ByteArrayEntity(body));
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doDelete(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
|
||||
StringBuilder sbUrl = new StringBuilder();
|
||||
sbUrl.append(host);
|
||||
if (!StringUtils.isBlank(path)) {
|
||||
sbUrl.append(path);
|
||||
}
|
||||
if (null != querys) {
|
||||
StringBuilder sbQuery = new StringBuilder();
|
||||
for (Map.Entry<String, String> query : querys.entrySet()) {
|
||||
if (0 < sbQuery.length()) {
|
||||
sbQuery.append("&");
|
||||
}
|
||||
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
|
||||
sbQuery.append(query.getValue());
|
||||
}
|
||||
if (!StringUtils.isBlank(query.getKey())) {
|
||||
sbQuery.append(query.getKey());
|
||||
if (!StringUtils.isBlank(query.getValue())) {
|
||||
sbQuery.append("=");
|
||||
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (0 < sbQuery.length()) {
|
||||
sbUrl.append("?").append(sbQuery);
|
||||
}
|
||||
}
|
||||
|
||||
return sbUrl.toString();
|
||||
}
|
||||
|
||||
private static HttpClient wrapClient(String host) {
|
||||
HttpClient httpClient = new DefaultHttpClient();
|
||||
if (host.startsWith("https://")) {
|
||||
sslClient(httpClient);
|
||||
}
|
||||
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
private static void sslClient(HttpClient httpClient) {
|
||||
try {
|
||||
SSLContext ctx = SSLContext.getInstance("TLS");
|
||||
X509TrustManager tm = new X509TrustManager() {
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
public void checkClientTrusted(X509Certificate[] xcs, String str) {
|
||||
|
||||
}
|
||||
public void checkServerTrusted(X509Certificate[] xcs, String str) {
|
||||
|
||||
}
|
||||
};
|
||||
ctx.init(null, new TrustManager[] { tm }, null);
|
||||
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
|
||||
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
|
||||
ClientConnectionManager ccm = httpClient.getConnectionManager();
|
||||
SchemeRegistry registry = ccm.getSchemeRegistry();
|
||||
registry.register(new Scheme("https", 443, ssf));
|
||||
} catch (KeyManagementException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
63
src/main/java/com/gxwebsoft/common/core/utils/ImageUtil.java
Normal file
63
src/main/java/com/gxwebsoft/common/core/utils/ImageUtil.java
Normal file
@@ -0,0 +1,63 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import sun.misc.BASE64Encoder;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
public class ImageUtil {
|
||||
public static String ImageBase64(String imgUrl) {
|
||||
URL url = null;
|
||||
InputStream is = null;
|
||||
ByteArrayOutputStream outStream = null;
|
||||
HttpURLConnection httpUrl = null;
|
||||
try{
|
||||
url = new URL(imgUrl);
|
||||
httpUrl = (HttpURLConnection) url.openConnection();
|
||||
httpUrl.connect();
|
||||
httpUrl.getInputStream();
|
||||
is = httpUrl.getInputStream();
|
||||
|
||||
outStream = new ByteArrayOutputStream();
|
||||
//创建一个Buffer字符串
|
||||
byte[] buffer = new byte[1024];
|
||||
//每次读取的字符串长度,如果为-1,代表全部读取完毕
|
||||
int len = 0;
|
||||
//使用一个输入流从buffer里把数据读取出来
|
||||
while( (len=is.read(buffer)) != -1 ){
|
||||
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
|
||||
outStream.write(buffer, 0, len);
|
||||
}
|
||||
// 对字节数组Base64编码
|
||||
return new BASE64Encoder().encode(outStream.toByteArray());
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
finally{
|
||||
if(is != null)
|
||||
{
|
||||
try {
|
||||
is.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if(outStream != null)
|
||||
{
|
||||
try {
|
||||
outStream.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if(httpUrl != null)
|
||||
{
|
||||
httpUrl.disconnect();
|
||||
}
|
||||
}
|
||||
return imgUrl;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
69
src/main/java/com/gxwebsoft/common/core/utils/JSONUtil.java
Normal file
69
src/main/java/com/gxwebsoft/common/core/utils/JSONUtil.java
Normal file
@@ -0,0 +1,69 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectWriter;
|
||||
|
||||
/**
|
||||
* JSON解析工具类
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:39
|
||||
*/
|
||||
public class JSONUtil {
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
|
||||
|
||||
/**
|
||||
* 对象转json字符串
|
||||
*
|
||||
* @param value 对象
|
||||
* @return String
|
||||
*/
|
||||
public static String toJSONString(Object value) {
|
||||
return toJSONString(value, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对象转json字符串
|
||||
*
|
||||
* @param value 对象
|
||||
* @param pretty 是否格式化输出
|
||||
* @return String
|
||||
*/
|
||||
public static String toJSONString(Object value, boolean pretty) {
|
||||
if (value != null) {
|
||||
if (value instanceof String) {
|
||||
return (String) value;
|
||||
}
|
||||
try {
|
||||
if (pretty) {
|
||||
return objectWriter.writeValueAsString(value);
|
||||
}
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* json字符串转对象
|
||||
*
|
||||
* @param json String
|
||||
* @param clazz Class
|
||||
* @return T
|
||||
*/
|
||||
public static <T> T parseObject(String json, Class<T> clazz) {
|
||||
if (StrUtil.isNotBlank(json) && clazz != null) {
|
||||
try {
|
||||
return objectMapper.readValue(json, clazz);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.extra.qrcode.QrCodeUtil;
|
||||
import cn.hutool.extra.qrcode.QrConfig;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* 常用工具方法
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:22
|
||||
*/
|
||||
public class MyQrCodeUtil {
|
||||
private static final String logoUrl = "https://file.wsdns.cn/20230430/6fa31aca3b0d47af98a149cf2dd26a4f.jpeg";
|
||||
|
||||
/**
|
||||
* 生成二维码
|
||||
* 用户ID
|
||||
*/
|
||||
public static String getCode(Integer loginUserId) throws IOException {
|
||||
return createQrCode(loginUserId,loginUserId.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成二维码
|
||||
* 支持自定义类型和内容
|
||||
*/
|
||||
public String getCode(Integer loginUserId,String content) throws IOException {
|
||||
return createQrCode(loginUserId,content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成带水印的二维码
|
||||
* @return https://file.gxwebsoft.com/qrcode/870.jpg?v=1682925307569
|
||||
*/
|
||||
public static String createQrCode(Integer userId,String content) throws IOException {
|
||||
// 将URL转为BufferedImage
|
||||
BufferedImage bufferedImage = ImageIO.read(new URL(logoUrl));
|
||||
// 生成二维码
|
||||
QrConfig config = new QrConfig(300, 300);
|
||||
// 设置边距,既二维码和背景之间的边距
|
||||
config.setMargin(1);
|
||||
// 附带小logo
|
||||
config.setImg(bufferedImage);
|
||||
// 保存路径
|
||||
// String filePath = "/Users/gxwebsoft/Documents/uploads/" + "file/qrcode/" + userId + ".jpg";
|
||||
String filePath = "/www/wwwroot/file.ws/" + "file/qrcode/" + userId + ".jpg";
|
||||
String qrcodeUrl = "https://file.gxwebsoft.com/qrcode/" + userId + ".jpg" + "?v=" + DateUtil.current();
|
||||
// 生成二维码
|
||||
System.out.println("config = " + config);
|
||||
System.out.println("con = " + content);
|
||||
System.out.println("filePath = " + filePath);
|
||||
QrCodeUtil.generate(content, config, FileUtil.file(filePath));
|
||||
return qrcodeUrl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.artofsolving.jodconverter.OfficeDocumentConverter;
|
||||
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
|
||||
import org.artofsolving.jodconverter.office.OfficeManager;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* OpenOfficeUtil
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-14 08:38:19
|
||||
*/
|
||||
public class OpenOfficeUtil {
|
||||
// 支持转换pdf的文件后缀列表
|
||||
private static final String[] CAN_CONVERTER_FILES = new String[]{
|
||||
"doc", "docx", "xls", "xlsx", "ppt", "pptx"
|
||||
};
|
||||
|
||||
/**
|
||||
* 文件转pdf
|
||||
*
|
||||
* @param filePath 源文件路径
|
||||
* @param outDir 输出目录
|
||||
* @param officeHome OpenOffice安装路径
|
||||
* @return File
|
||||
*/
|
||||
public static File converterToPDF(String filePath, String outDir, String officeHome) {
|
||||
return converterToPDF(filePath, outDir, officeHome, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件转pdf
|
||||
*
|
||||
* @param filePath 源文件路径
|
||||
* @param outDir 输出目录
|
||||
* @param officeHome OpenOffice安装路径
|
||||
* @param cache 是否使用上次转换过的文件
|
||||
* @return File
|
||||
*/
|
||||
public static File converterToPDF(String filePath, String outDir, String officeHome, boolean cache) {
|
||||
if (StrUtil.isBlank(filePath)) {
|
||||
return null;
|
||||
}
|
||||
File srcFile = new File(filePath);
|
||||
if (!srcFile.exists()) {
|
||||
return null;
|
||||
}
|
||||
// 是否转换过
|
||||
String outPath = Base64.getEncoder().encodeToString(filePath.getBytes())
|
||||
.replace("/", "-").replace("+", "-");
|
||||
File outFile = new File(outDir, outPath + ".pdf");
|
||||
if (cache && outFile.exists()) {
|
||||
return outFile;
|
||||
}
|
||||
// 转换
|
||||
OfficeManager officeManager = null;
|
||||
try {
|
||||
officeManager = getOfficeManager(officeHome);
|
||||
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
|
||||
return converterFile(srcFile, outFile, converter);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (officeManager != null) {
|
||||
officeManager.stop();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换文件
|
||||
*
|
||||
* @param inFile 源文件
|
||||
* @param outFile 输出文件
|
||||
* @param converter OfficeDocumentConverter
|
||||
* @return File
|
||||
*/
|
||||
public static File converterFile(File inFile, File outFile, OfficeDocumentConverter converter) {
|
||||
if (!outFile.getParentFile().exists()) {
|
||||
if (!outFile.getParentFile().mkdirs()) {
|
||||
return outFile;
|
||||
}
|
||||
}
|
||||
converter.convert(inFile, outFile);
|
||||
return outFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文件后缀是否可以转换pdf
|
||||
*
|
||||
* @param path 文件路径
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean canConverter(String path) {
|
||||
try {
|
||||
String suffix = path.substring(path.lastIndexOf(".") + 1);
|
||||
return Arrays.asList(CAN_CONVERTER_FILES).contains(suffix);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接并启动OpenOffice
|
||||
*
|
||||
* @param officeHome OpenOffice安装路径
|
||||
* @return OfficeManager
|
||||
*/
|
||||
public static OfficeManager getOfficeManager(String officeHome) {
|
||||
if (officeHome == null || officeHome.trim().isEmpty()) return null;
|
||||
DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
|
||||
config.setOfficeHome(officeHome); // 设置OpenOffice安装目录
|
||||
OfficeManager officeManager = config.buildOfficeManager();
|
||||
officeManager.start(); // 启动OpenOffice服务
|
||||
return officeManager;
|
||||
}
|
||||
|
||||
}
|
||||
279
src/main/java/com/gxwebsoft/common/core/utils/RedisUtil.java
Normal file
279
src/main/java/com/gxwebsoft/common/core/utils/RedisUtil.java
Normal file
@@ -0,0 +1,279 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.result.RedisResult;
|
||||
import org.springframework.data.geo.Point;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static com.gxwebsoft.common.core.constants.RedisConstants.CACHE_NULL_TTL;
|
||||
|
||||
@Component
|
||||
public class RedisUtil {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
public static Integer tenantId;
|
||||
|
||||
public RedisUtil(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param entity 实体类对象
|
||||
* 示例 cacheClient.set("merchant:"+id,merchant)
|
||||
*/
|
||||
public <T> void set(String key, T entity){
|
||||
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param entity 实体类对象
|
||||
* 示例 cacheClient.set("merchant:"+id,merchant,1L,TimeUnit.DAYS)
|
||||
*/
|
||||
public <T> void set(String key, T entity, Long time, TimeUnit unit){
|
||||
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJSONString(entity),time,unit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存
|
||||
* @param key [表名]:id
|
||||
* 示例 cacheClient.get(key)
|
||||
* @return merchant
|
||||
*/
|
||||
public String get(String key) {
|
||||
return stringRedisTemplate.opsForValue().get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param clazz Merchant.class
|
||||
* @param <T>
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
* @return merchant
|
||||
*/
|
||||
public <T> T get(String key, Class<T> clazz) {
|
||||
String json = stringRedisTemplate.opsForValue().get(key);
|
||||
if(StrUtil.isNotBlank(json)){
|
||||
return JSONUtil.parseObject(json, clazz);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写redis缓存(哈希类型)
|
||||
* @param key [表名]:id
|
||||
* @param field 字段
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
*/
|
||||
public <T> void hPut(String key, String field, T entity) {
|
||||
stringRedisTemplate.opsForHash().put(key,field,JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
/**
|
||||
* 写redis缓存(哈希类型)
|
||||
* @param key [表名]:id
|
||||
* @param map 字段
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
*/
|
||||
public void hPutAll(String key, Map<String,String> map) {
|
||||
stringRedisTemplate.opsForHash().putAll(key,map);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存(哈希类型)
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
* @param key [表名]:id
|
||||
* @param field 字段
|
||||
* @return merchant
|
||||
*/
|
||||
public <T> T hGet(String key, String field, Class<T> clazz) {
|
||||
Object obj = stringRedisTemplate.opsForHash().get(key, field);
|
||||
return JSONUtil.parseObject(JSONUtil.toJSONString(obj),clazz);
|
||||
}
|
||||
|
||||
public List<Object> hValues(String key){
|
||||
return stringRedisTemplate.opsForHash().values(key);
|
||||
}
|
||||
|
||||
public Long hSize(String key){
|
||||
return stringRedisTemplate.opsForHash().size(key);
|
||||
}
|
||||
|
||||
// 逻辑过期方式写入redis
|
||||
public <T> void setWithLogicalExpire(String key, T value, Long time, TimeUnit unit){
|
||||
// 设置逻辑过期时间
|
||||
final RedisResult<T> redisResult = new RedisResult<>();
|
||||
redisResult.setData(value);
|
||||
redisResult.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
|
||||
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJSONString(redisResult));
|
||||
}
|
||||
|
||||
// 读取redis
|
||||
public <R,ID> R query(String keyPrefix, ID id, Class<R> clazz, Function<ID,R> dbFallback, Long time, TimeUnit unit){
|
||||
String key = keyPrefix + id;
|
||||
// 1.从redis查询缓存
|
||||
final String json = stringRedisTemplate.opsForValue().get(key);
|
||||
// 2.判断是否存在
|
||||
if (StrUtil.isNotBlank(json)) {
|
||||
// 3.存在,直接返回
|
||||
return JSONUtil.parseObject(json,clazz);
|
||||
}
|
||||
// 判断命中的是否为空值
|
||||
if (json != null) {
|
||||
return null;
|
||||
}
|
||||
// 4. 不存在,跟进ID查询数据库
|
||||
R r = dbFallback.apply(id);
|
||||
// 5. 数据库不存在,返回错误
|
||||
if(r == null){
|
||||
// 空值写入数据库
|
||||
this.set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
|
||||
return null;
|
||||
}
|
||||
// 写入redis
|
||||
this.set(key,r,time,unit);
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加商户定位点
|
||||
* @param key geo
|
||||
* @param id
|
||||
* 示例 cacheClient.geoAdd("merchant-geo",merchant)
|
||||
*/
|
||||
public <T> void geoAdd(String key, Double x, Double y, String id){
|
||||
stringRedisTemplate.opsForGeo().add(key,new Point(x,y),id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除定位
|
||||
* @param key geo
|
||||
* @param id
|
||||
* 示例 cacheClient.geoRemove("merchant-geo",id)
|
||||
*/
|
||||
public void geoRemove(String key, Integer id){
|
||||
stringRedisTemplate.opsForGeo().remove(key,id.toString());
|
||||
}
|
||||
|
||||
|
||||
|
||||
public <T> void sAdd(String key, T entity){
|
||||
stringRedisTemplate.opsForSet().add(key,JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
public <T> Set<String> sMembers(String key){
|
||||
return stringRedisTemplate.opsForSet().members(key);
|
||||
}
|
||||
|
||||
// 更新排行榜
|
||||
public void zAdd(String key, Integer userId, Double value) {
|
||||
stringRedisTemplate.opsForZSet().add(key,userId.toString(),value);
|
||||
}
|
||||
// 增加元素的score值,并返回增加后的值
|
||||
public Double zIncrementScore(String key,Integer userId, Double delta){
|
||||
return stringRedisTemplate.opsForZSet().incrementScore(key, userId.toString(), delta);
|
||||
}
|
||||
// 获取排名榜
|
||||
public Set<String> range(String key, Integer start, Integer end) {
|
||||
return stringRedisTemplate.opsForZSet().range(key, start, end);
|
||||
}
|
||||
// 获取排名榜
|
||||
public Set<String> reverseRange(String key, Integer start, Integer end){
|
||||
return stringRedisTemplate.opsForZSet().reverseRange(key, start, end);
|
||||
}
|
||||
// 获取分数
|
||||
public Double score(String key, Object value){
|
||||
return stringRedisTemplate.opsForZSet().score(key, value);
|
||||
}
|
||||
|
||||
public void delete(String key){
|
||||
stringRedisTemplate.delete(key);
|
||||
}
|
||||
|
||||
// 存储在list头部
|
||||
public void leftPush(String key, String keyword){
|
||||
stringRedisTemplate.opsForList().leftPush(key,keyword);
|
||||
}
|
||||
|
||||
// 获取列表指定范围内的元素
|
||||
public List<String> listRange(String key,Long start, Long end){
|
||||
return stringRedisTemplate.opsForList().range(key, start, end);
|
||||
}
|
||||
|
||||
// 获取列表长度
|
||||
public Long listSize(String key){
|
||||
return stringRedisTemplate.opsForList().size(key);
|
||||
}
|
||||
|
||||
// 裁剪list
|
||||
public void listTrim(String key){
|
||||
stringRedisTemplate.opsForList().trim(key, 0L, 100L);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取后台系统设置信息
|
||||
* @param keyName 键名wx-word
|
||||
* @param tenantId 租户ID
|
||||
* @return
|
||||
* key示例 cache10048:setting:wx-work
|
||||
*/
|
||||
public JSONObject getSettingInfo(String keyName,Integer tenantId){
|
||||
String key = "cache" + tenantId + ":setting:" + keyName;
|
||||
final String cache = stringRedisTemplate.opsForValue().get(key);
|
||||
assert cache != null;
|
||||
return JSON.parseObject(cache);
|
||||
}
|
||||
|
||||
/**
|
||||
* KEY前缀
|
||||
* cache[tenantId]:[key+id]
|
||||
*/
|
||||
public static String prefix(String key){
|
||||
String prefix = "cache";
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null) {
|
||||
Object object = authentication.getPrincipal();
|
||||
if (object instanceof User) {
|
||||
final Integer tenantId = ((User) object).getTenantId();
|
||||
prefix = prefix.concat(tenantId.toString()).concat(":");
|
||||
}
|
||||
}
|
||||
return prefix.concat(key);
|
||||
}
|
||||
|
||||
// 组装key
|
||||
public String key(String name,Integer id){
|
||||
return name.concat(":").concat(id.toString());
|
||||
}
|
||||
|
||||
// 获取上传配置
|
||||
public HashMap<String, String> getUploadConfig(Integer tenantId){
|
||||
String key = "setting:upload:" + tenantId;
|
||||
final String s = get(key);
|
||||
final JSONObject jsonObject = JSONObject.parseObject(s);
|
||||
final String uploadMethod = jsonObject.getString("uploadMethod");
|
||||
final String bucketDomain = jsonObject.getString("bucketDomain");
|
||||
|
||||
final HashMap<String, String> map = new HashMap<>();
|
||||
map.put("uploadMethod",uploadMethod);
|
||||
map.put("bucketDomain",bucketDomain);
|
||||
return map;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import com.gxwebsoft.shop.service.OrderService;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* 自动执行计划
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-14 08:38:19
|
||||
*/
|
||||
public class SchedulingUtil {
|
||||
@Resource
|
||||
private OrderService orderService;
|
||||
|
||||
// @Scheduled(cron="*/5 * * * * *")
|
||||
// public void reportCurrentTime() {
|
||||
// System.out.println("定时任务开始 = " + new Date());
|
||||
// int count = orderService.count(new LambdaQueryWrapper<Order>().eq(Order::getPayStatus, 20));
|
||||
//// orderService.removeOrderByTimeOut();
|
||||
// System.out.println("count = " + count);
|
||||
// }
|
||||
}
|
||||
172
src/main/java/com/gxwebsoft/common/core/utils/SignCheckUtil.java
Normal file
172
src/main/java/com/gxwebsoft/common/core/utils/SignCheckUtil.java
Normal file
@@ -0,0 +1,172 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.crypto.SecureUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.system.entity.KVEntity;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 签名检查和获取签名
|
||||
* https://blog.csdn.net/u011628753/article/details/110251445
|
||||
* @author leng
|
||||
*
|
||||
*/
|
||||
public class SignCheckUtil {
|
||||
// 签名字段
|
||||
public final static String SIGN = "sign";
|
||||
|
||||
/**
|
||||
* 签名检查,签名参数中,sign是用于校验的加密值,其他参数按照字母顺序排序,加密,并将其内容链接起来
|
||||
*
|
||||
* @param params
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static boolean signCheck(JSONObject params, String key) {
|
||||
if (null != params) {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
params.forEach((k, v) -> {
|
||||
map.put(k, v.toString());
|
||||
});
|
||||
return signCheck(map, key);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名检查,签名参数中,sign是用于校验的加密值,其他参数按照字母顺序排序,加密,并将其内容链接起来
|
||||
*
|
||||
* @param params
|
||||
* @param key
|
||||
* 签名key不允许为空
|
||||
* @return
|
||||
*/
|
||||
public static boolean signCheck(Map<String, String> params, String key) {
|
||||
String sign = params.get(SIGN);// 签名
|
||||
if (null == sign) {
|
||||
return false;
|
||||
}
|
||||
String signTemp = getSignString(params,key);
|
||||
if (null == signTemp) {
|
||||
return false;
|
||||
}
|
||||
return signTemp.equals(sign);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取签名的字符串
|
||||
*
|
||||
* @param params
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static String getSignString(JSONObject params, String key) {
|
||||
if (null != params) {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
params.forEach((k, v) -> {
|
||||
map.put(k, v.toString());
|
||||
});
|
||||
return getSignString(map, key);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取签名的字符串
|
||||
*
|
||||
* @param params
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static String getSignString(Map<String, String> params, String key) {
|
||||
// 签名
|
||||
if (null == params || params.size() == 0) {
|
||||
return null;
|
||||
}
|
||||
key = (null == key) ? "" : key;
|
||||
List<KVEntity<String, String>> list = new ArrayList<>(params.size() - 1);
|
||||
|
||||
params.forEach((k, v) -> {
|
||||
if (!SIGN.equals(k)) {
|
||||
list.add(KVEntity.build(k, v));
|
||||
}
|
||||
});
|
||||
|
||||
Collections.sort(list, (obj1, obj2) -> {
|
||||
return obj1.getK().compareTo(obj2.getK());
|
||||
});
|
||||
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (KVEntity<String, String> kv : list) {
|
||||
String value = kv.getV();
|
||||
if (!StringUtils.isEmpty(value)) {
|
||||
sb.append(kv.getV()).append("-");
|
||||
}
|
||||
}
|
||||
sb.append(key);
|
||||
System.out.println("md5加密前的字符串 = " + sb + key);
|
||||
String signTemp = SecureUtil.md5(sb.toString()).toLowerCase();
|
||||
return signTemp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取微信签名的字符串
|
||||
*
|
||||
* 注意签名(sign)的生成方式,具体见官方文档(传参都要参与生成签名,且参数名按照字典序排序,最后接上APP_KEY,转化成大写)
|
||||
*
|
||||
* @param params
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static String getWXSignString(Map<String, String> params, String key) {
|
||||
// 签名
|
||||
if (null == params || params.size() == 0 || StringUtils.isEmpty(key)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<KVEntity<String, String>> list = new ArrayList<>(params.size() - 1);
|
||||
|
||||
params.forEach((k, v) -> {
|
||||
if (!SIGN.equals(k)) {
|
||||
list.add(KVEntity.build(k, v));
|
||||
}
|
||||
});
|
||||
|
||||
Collections.sort(list, (obj1, obj2) -> {
|
||||
return obj1.getK().compareTo(obj2.getK());
|
||||
});
|
||||
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (KVEntity<String, String> kv : list) {
|
||||
String value = kv.getV();
|
||||
if (!StringUtils.isEmpty(value)) {
|
||||
sb.append(kv.getK() + "=" + value + "&");
|
||||
}
|
||||
}
|
||||
|
||||
sb.append("key=" + key);
|
||||
String signTemp = SecureUtil.md5(sb.toString()).toLowerCase();
|
||||
return signTemp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 微信签名验证
|
||||
* @param params
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static boolean WXsignCheck(Map<String, String> params, String key) {
|
||||
String sign = params.get(SIGN);
|
||||
if (StringUtils.isEmpty(sign)) {
|
||||
return false;
|
||||
}
|
||||
return sign.equals(getWXSignString(params, key));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.CharsetUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import com.gxwebsoft.common.system.service.SettingService;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
|
||||
/**
|
||||
* 微信公众号工具类
|
||||
* @author 科技小王子
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class WxOfficialUtil {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private Integer tenantId;
|
||||
public String appId;
|
||||
public String appSecret;
|
||||
public String openid;
|
||||
public String unionid;
|
||||
public String access_token;
|
||||
public String expires_in;
|
||||
public String nickname;
|
||||
|
||||
|
||||
@Resource
|
||||
private SettingService settingService;
|
||||
@Resource
|
||||
private ConfigProperties pathConfig;
|
||||
@Resource
|
||||
private CacheClient cacheClient;
|
||||
|
||||
public WxOfficialUtil(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
// 实例化客户端
|
||||
public WxOfficialUtil client(Integer tenantId) {
|
||||
if(tenantId > 0){
|
||||
throw new BusinessException(tenantId + "123123");
|
||||
}
|
||||
this.tenantId = tenantId;
|
||||
this.config();
|
||||
System.out.println("this.tenantId = " + this.tenantId);
|
||||
return this;
|
||||
}
|
||||
|
||||
// 开发者ID和秘钥
|
||||
private void config() {
|
||||
String key = "cache"+ this.tenantId +":setting:wx-official";
|
||||
String wxOfficial = stringRedisTemplate.opsForValue().get(key);
|
||||
JSONObject data = JSONObject.parseObject(wxOfficial);
|
||||
if(data != null){
|
||||
this.appId = data.getString("appId");
|
||||
this.appSecret = data.getString("appSecret");
|
||||
}
|
||||
System.out.println("this.appId = " + this.appId);
|
||||
System.out.println("this.appSecret = " + this.appSecret);
|
||||
}
|
||||
|
||||
// 获取appId
|
||||
public String getAppSecret(){
|
||||
return this.appSecret;
|
||||
}
|
||||
|
||||
public String getCodeUrl() throws UnsupportedEncodingException {
|
||||
String encodedReturnUrl = URLEncoder.encode("https://server.gxwebsoft.com/api/open/wx-official/accessToken","UTF-8");
|
||||
return "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ this.appId +"&redirect_uri=" + encodedReturnUrl + "&response_type=code&scope=snsapi_userinfo&state="+ this.tenantId +"#wechat_redirect";
|
||||
}
|
||||
|
||||
// 获取access_token
|
||||
public String getAccessToken(String code) {
|
||||
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ this.appId +"&secret="+ this.appSecret +"&code="+ code +"&grant_type=authorization_code";
|
||||
System.out.println("url = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
final JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
access_token = jsonObject.getString("access_token");
|
||||
if(access_token == null){
|
||||
throw new BusinessException("获取access_token失败");
|
||||
}
|
||||
this.openid = jsonObject.getString("openid");
|
||||
this.unionid = jsonObject.getString("unionid");
|
||||
this.expires_in = jsonObject.getString("expires_in");
|
||||
return access_token;
|
||||
}
|
||||
|
||||
// 获取userinfo
|
||||
public JSONObject getUserInfo(String access_token) {
|
||||
String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+ access_token +"&openid="+ this.openid +"&lang=zh_CN";
|
||||
System.out.println("url2 = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response = " + response);
|
||||
if(response == null){
|
||||
throw new BusinessException("获取userinfo失败");
|
||||
}
|
||||
return JSONObject.parseObject(response);
|
||||
}
|
||||
}
|
||||
134
src/main/java/com/gxwebsoft/common/core/utils/WxUtil.java
Normal file
134
src/main/java/com/gxwebsoft/common/core/utils/WxUtil.java
Normal file
@@ -0,0 +1,134 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.CharsetUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 微信小程序工具类
|
||||
* @author 科技小王子
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class WxUtil {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private Integer tenantId;
|
||||
public String appId;
|
||||
public String appSecret;
|
||||
public String access_token;
|
||||
public String expires_in;
|
||||
public String nickname;
|
||||
public String userid;
|
||||
public String user_ticket;
|
||||
public String openid;
|
||||
public String external_userid;
|
||||
public String name;
|
||||
public String position;
|
||||
public String mobile;
|
||||
public String gender;
|
||||
public String email;
|
||||
public String avatar;
|
||||
public String thumb_avatar;
|
||||
public String telephone;
|
||||
public String address;
|
||||
public String alias;
|
||||
public String qr_code;
|
||||
public String open_userid;
|
||||
|
||||
@Resource
|
||||
private CacheClient cacheClient;
|
||||
|
||||
|
||||
public WxUtil(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
|
||||
// 实例化客户端
|
||||
public WxUtil client(Integer tenantId) {
|
||||
this.tenantId = tenantId;
|
||||
this.config();
|
||||
return this;
|
||||
}
|
||||
|
||||
// 开发者ID和秘钥
|
||||
private void config() {
|
||||
JSONObject settingInfo = cacheClient.getSettingInfo("wx-work", this.tenantId);
|
||||
if(settingInfo == null){
|
||||
throw new BusinessException("微信小程序未配置");
|
||||
}
|
||||
this.appId = settingInfo.getString("corpId");
|
||||
this.appSecret = settingInfo.getString("secret");
|
||||
System.out.println("this.appId = " + this.appId);
|
||||
System.out.println("this.appSecret = " + this.appSecret);
|
||||
}
|
||||
|
||||
// 获取access_token
|
||||
public void getAccessToken(String code) {
|
||||
String key = "cache"+ this.tenantId +":ww:access_token";
|
||||
final String access_token = stringRedisTemplate.opsForValue().get(key);
|
||||
if(access_token != null){
|
||||
this.getUserInfo(code,access_token);
|
||||
}else {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" +this.appId+ "&corpsecret="+ this.appSecret;
|
||||
System.out.println("url = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response = " + response);
|
||||
final JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
// 获取成功
|
||||
if(jsonObject.getString("access_token") != null){
|
||||
this.access_token = jsonObject.getString("access_token");
|
||||
this.expires_in = jsonObject.getString("expires_in");
|
||||
stringRedisTemplate.opsForValue().set(key,this.access_token,7000, TimeUnit.SECONDS);
|
||||
System.out.println("获取access_token成功 = " + this.access_token);
|
||||
this.getUserInfo(code,this.access_token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取userinfo
|
||||
public void getUserInfo(String code, String access_token) {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" +access_token+ "&code=" + code;
|
||||
System.out.println("url2 = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response = " + response);
|
||||
JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
final String errcode = jsonObject.getString("errcode");
|
||||
final String errmsg = jsonObject.getString("errmsg");
|
||||
if(!StrUtil.equals(errcode,"0")){
|
||||
throw new BusinessException(errmsg);
|
||||
}
|
||||
this.userid = jsonObject.getString("userid");
|
||||
this.user_ticket = jsonObject.getString("user_ticket");
|
||||
this.openid = jsonObject.getString("openid");
|
||||
this.external_userid = jsonObject.getString("external_userid");
|
||||
System.out.println("获取用户信息成功 = " + jsonObject);
|
||||
}
|
||||
|
||||
public void getUserProfile(String userid, String access_token) {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+ access_token +"&userid=" + userid;
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response3 = " + response);
|
||||
JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
System.out.println("读取用户详细信息 = " + jsonObject);
|
||||
|
||||
this.name = jsonObject.getString("name");
|
||||
this.position = jsonObject.getString("position");
|
||||
this.gender = jsonObject.getString("gender");
|
||||
this.email = jsonObject.getString("email");
|
||||
this.avatar = jsonObject.getString("avatar");
|
||||
this.thumb_avatar = jsonObject.getString("thumb_avatar");
|
||||
this.telephone = jsonObject.getString("telephone");
|
||||
this.address = jsonObject.getString("address");
|
||||
this.alias = jsonObject.getString("alias");
|
||||
this.qr_code = jsonObject.getString("qr_code");
|
||||
this.open_userid = jsonObject.getString("open_userid");
|
||||
}
|
||||
}
|
||||
134
src/main/java/com/gxwebsoft/common/core/utils/WxWorkUtil.java
Normal file
134
src/main/java/com/gxwebsoft/common/core/utils/WxWorkUtil.java
Normal file
@@ -0,0 +1,134 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.CharsetUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 企业微信工具类
|
||||
* @author 科技小王子
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class WxWorkUtil {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private Integer tenantId;
|
||||
public String appId;
|
||||
public String appSecret;
|
||||
public String access_token;
|
||||
public String expires_in;
|
||||
public String nickname;
|
||||
public String userid;
|
||||
public String user_ticket;
|
||||
public String openid;
|
||||
public String external_userid;
|
||||
public String name;
|
||||
public String position;
|
||||
public String mobile;
|
||||
public String gender;
|
||||
public String email;
|
||||
public String avatar;
|
||||
public String thumb_avatar;
|
||||
public String telephone;
|
||||
public String address;
|
||||
public String alias;
|
||||
public String qr_code;
|
||||
public String open_userid;
|
||||
|
||||
@Resource
|
||||
private CacheClient cacheClient;
|
||||
|
||||
|
||||
public WxWorkUtil(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
|
||||
// 实例化客户端
|
||||
public WxWorkUtil client(Integer tenantId) {
|
||||
this.tenantId = tenantId;
|
||||
this.config();
|
||||
return this;
|
||||
}
|
||||
|
||||
// 开发者ID和秘钥
|
||||
private void config() {
|
||||
JSONObject settingInfo = cacheClient.getSettingInfo("wx-work", this.tenantId);
|
||||
if(settingInfo == null){
|
||||
throw new BusinessException("企业微信未配置");
|
||||
}
|
||||
this.appId = settingInfo.getString("corpId");
|
||||
this.appSecret = settingInfo.getString("secret");
|
||||
System.out.println("this.appId = " + this.appId);
|
||||
System.out.println("this.appSecret = " + this.appSecret);
|
||||
}
|
||||
|
||||
// 获取access_token
|
||||
public void getAccessToken(String code) {
|
||||
String key = "cache"+ this.tenantId +":ww:access_token";
|
||||
final String access_token = stringRedisTemplate.opsForValue().get(key);
|
||||
if(access_token != null){
|
||||
this.getUserInfo(code,access_token);
|
||||
}else {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" +this.appId+ "&corpsecret="+ this.appSecret;
|
||||
System.out.println("url = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response = " + response);
|
||||
final JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
// 获取成功
|
||||
if(jsonObject.getString("access_token") != null){
|
||||
this.access_token = jsonObject.getString("access_token");
|
||||
this.expires_in = jsonObject.getString("expires_in");
|
||||
stringRedisTemplate.opsForValue().set(key,this.access_token,7000, TimeUnit.SECONDS);
|
||||
System.out.println("获取access_token成功 = " + this.access_token);
|
||||
this.getUserInfo(code,this.access_token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取userinfo
|
||||
public void getUserInfo(String code, String access_token) {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" +access_token+ "&code=" + code;
|
||||
System.out.println("url2 = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response = " + response);
|
||||
JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
final String errcode = jsonObject.getString("errcode");
|
||||
final String errmsg = jsonObject.getString("errmsg");
|
||||
if(!StrUtil.equals(errcode,"0")){
|
||||
throw new BusinessException(errmsg);
|
||||
}
|
||||
this.userid = jsonObject.getString("userid");
|
||||
this.user_ticket = jsonObject.getString("user_ticket");
|
||||
this.openid = jsonObject.getString("openid");
|
||||
this.external_userid = jsonObject.getString("external_userid");
|
||||
System.out.println("获取用户信息成功 = " + jsonObject);
|
||||
}
|
||||
|
||||
public void getUserProfile(String userid, String access_token) {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+ access_token +"&userid=" + userid;
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response3 = " + response);
|
||||
JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
System.out.println("读取用户详细信息 = " + jsonObject);
|
||||
|
||||
this.name = jsonObject.getString("name");
|
||||
this.position = jsonObject.getString("position");
|
||||
this.gender = jsonObject.getString("gender");
|
||||
this.email = jsonObject.getString("email");
|
||||
this.avatar = jsonObject.getString("avatar");
|
||||
this.thumb_avatar = jsonObject.getString("thumb_avatar");
|
||||
this.telephone = jsonObject.getString("telephone");
|
||||
this.address = jsonObject.getString("address");
|
||||
this.alias = jsonObject.getString("alias");
|
||||
this.qr_code = jsonObject.getString("qr_code");
|
||||
this.open_userid = jsonObject.getString("open_userid");
|
||||
}
|
||||
}
|
||||
87
src/main/java/com/gxwebsoft/common/core/web/ApiResult.java
Normal file
87
src/main/java/com/gxwebsoft/common/core/web/ApiResult.java
Normal file
@@ -0,0 +1,87 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 返回结果
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:50
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class ApiResult<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "状态码")
|
||||
private Integer code;
|
||||
|
||||
@ApiModelProperty(value = "状态信息")
|
||||
private String message;
|
||||
|
||||
@ApiModelProperty(value = "返回数据")
|
||||
private T data;
|
||||
|
||||
@ApiModelProperty(value = "错误信息")
|
||||
private String error;
|
||||
|
||||
public ApiResult() {}
|
||||
|
||||
public ApiResult(Integer code) {
|
||||
this(code, null);
|
||||
}
|
||||
|
||||
public ApiResult(Integer code, String message) {
|
||||
this(code, message, null);
|
||||
}
|
||||
|
||||
public ApiResult(Integer code, String message, T data) {
|
||||
this(code, message, data, null);
|
||||
}
|
||||
|
||||
public ApiResult(Integer code, String message, T data, String error) {
|
||||
setCode(code);
|
||||
setMessage(message);
|
||||
setData(data);
|
||||
setError(error);
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
public ApiResult<T> setCode(Integer code) {
|
||||
this.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
public ApiResult<T> setMessage(String message) {
|
||||
this.message = message;
|
||||
return this;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return this.data;
|
||||
}
|
||||
|
||||
public ApiResult<T> setData(T data) {
|
||||
this.data = data;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getError() {
|
||||
return this.error;
|
||||
}
|
||||
|
||||
public ApiResult<T> setError(String error) {
|
||||
this.error = error;
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
325
src/main/java/com/gxwebsoft/common/core/web/BaseController.java
Normal file
325
src/main/java/com/gxwebsoft/common/core/web/BaseController.java
Normal file
@@ -0,0 +1,325 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import com.gxwebsoft.common.core.utils.CacheClient;
|
||||
import com.gxwebsoft.common.core.utils.SignCheckUtil;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
import com.gxwebsoft.shop.entity.Merchant;
|
||||
import com.gxwebsoft.shop.service.MerchantClerkService;
|
||||
import com.gxwebsoft.shop.service.MerchantService;
|
||||
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.WebDataBinder;
|
||||
import org.springframework.web.bind.annotation.InitBinder;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Controller基类
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:19
|
||||
*/
|
||||
public class BaseController {
|
||||
@Resource
|
||||
private HttpServletRequest request;
|
||||
@Resource
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
@Resource
|
||||
private MerchantService merchantService;
|
||||
@Resource
|
||||
private MerchantClerkService merchantClerkService;
|
||||
@Resource
|
||||
private CacheClient cacheClient;
|
||||
@Resource
|
||||
private UserService userService;
|
||||
|
||||
/**
|
||||
* 获取当前登录的user
|
||||
*
|
||||
* @return User
|
||||
*/
|
||||
public User getLoginUser() {
|
||||
try {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null) {
|
||||
Object object = authentication.getPrincipal();
|
||||
if (object instanceof User) {
|
||||
return (User) object;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录的userId
|
||||
*
|
||||
* @return userId
|
||||
*/
|
||||
public Integer getLoginUserId() {
|
||||
User loginUser = getLoginUser();
|
||||
return loginUser == null ? null : loginUser.getUserId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录的tenantId
|
||||
*
|
||||
* @return tenantId
|
||||
*/
|
||||
public Integer getTenantId() {
|
||||
// 从登录用户拿tenantId
|
||||
User loginUser = getLoginUser();
|
||||
if (loginUser != null) {
|
||||
return loginUser.getTenantId();
|
||||
}
|
||||
// 从请求头拿tenantId
|
||||
if(StrUtil.isNotBlank(request.getHeader("tenantId"))){
|
||||
return Integer.valueOf(request.getHeader("tenantId"));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功
|
||||
*
|
||||
* @return ApiResult
|
||||
*/
|
||||
public ApiResult<?> success() {
|
||||
return new ApiResult<>(Constants.RESULT_OK_CODE, Constants.RESULT_OK_MSG);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功
|
||||
*
|
||||
* @param message 状态信息
|
||||
* @return ApiResult
|
||||
*/
|
||||
public ApiResult<?> success(String message) {
|
||||
return success().setMessage(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功
|
||||
*
|
||||
* @param data 返回数据
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<T> success(T data) {
|
||||
return new ApiResult<>(Constants.RESULT_OK_CODE, Constants.RESULT_OK_MSG, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功
|
||||
*
|
||||
* @param message 状态信息
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<T> success(String message, T data) {
|
||||
return success(data).setMessage(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回分页查询数据
|
||||
*
|
||||
* @param list 当前页数据
|
||||
* @param count 总数量
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<PageResult<T>> success(List<T> list, Long count) {
|
||||
return success(new PageResult<>(list, count));
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回分页查询数据
|
||||
*
|
||||
* @param iPage IPage
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<PageResult<T>> success(IPage<T> iPage) {
|
||||
return success(iPage.getRecords(), iPage.getTotal());
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败
|
||||
*
|
||||
* @return ApiResult
|
||||
*/
|
||||
public ApiResult<?> fail() {
|
||||
return new ApiResult<>(Constants.RESULT_ERROR_CODE, Constants.RESULT_ERROR_MSG);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败
|
||||
*
|
||||
* @param message 状态信息
|
||||
* @return ApiResult
|
||||
*/
|
||||
public ApiResult<?> fail(String message) {
|
||||
return fail().setMessage(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败
|
||||
*
|
||||
* @param data 返回数据
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<T> fail(T data) {
|
||||
return fail(Constants.RESULT_ERROR_MSG, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败
|
||||
*
|
||||
* @param message 状态信息
|
||||
* @param data 返回数据
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<T> fail(String message, T data) {
|
||||
return new ApiResult<>(Constants.RESULT_ERROR_CODE, message, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求参数的空字符串转为null
|
||||
*/
|
||||
@InitBinder
|
||||
public void initBinder(WebDataBinder binder) {
|
||||
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
|
||||
}
|
||||
|
||||
// 自定义函数
|
||||
public String getAuthorization(){
|
||||
return request.getHeader("Authorization");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录用户所属的商户编号
|
||||
*
|
||||
* @return merchantCode
|
||||
*/
|
||||
public String getMerchantCode() {
|
||||
// 按店员查询
|
||||
return merchantClerkService.getMerchantCodeByClerk(getLoginUserId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录的商户信息
|
||||
*
|
||||
* @return merchantCode
|
||||
*/
|
||||
public Merchant getMerchant() {
|
||||
return merchantService.getMerchantByCode(getMerchantCode());
|
||||
}
|
||||
|
||||
public String getAppId() {
|
||||
// 兼容小写
|
||||
if(request.getHeader("appid") != null){
|
||||
return request.getHeader("appid");
|
||||
}
|
||||
return request.getHeader("AppId");
|
||||
}
|
||||
|
||||
public String getSign() {
|
||||
return request.getParameter("sign");
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否校验签名信息
|
||||
* 存在签名信息则需要验证
|
||||
*/
|
||||
public void isCheckSign() {
|
||||
if (StrUtil.isNotBlank(getSign())) {
|
||||
if(getTenantId() == null){
|
||||
throw new BusinessException("签名失败:TenantId不能为空");
|
||||
}
|
||||
|
||||
String timestamp1 = request.getParameter("timestamp");
|
||||
long timestamp2 = System.currentTimeMillis();
|
||||
long time = timestamp2 - Long.parseLong(timestamp1);
|
||||
if(time > 600000L){
|
||||
throw new BusinessException("签名失败:请求超时");
|
||||
}
|
||||
|
||||
Enumeration<String> names = request.getParameterNames();
|
||||
//2.遍历正文名称的枚举获得请求参数
|
||||
Map<String, String> params = new HashMap<>();
|
||||
while(names.hasMoreElements()){
|
||||
String name = names.nextElement();
|
||||
String value = request.getParameter(name);
|
||||
params.put(name,value);
|
||||
}
|
||||
String signString = SignCheckUtil.getSignString(params, getAppSecret());
|
||||
System.out.println("请求的参数 = " + params);
|
||||
System.out.println("正确的签名 = " + signString);
|
||||
System.out.println("签名是否正确 = " + SignCheckUtil.signCheck(params, getAppSecret()));
|
||||
|
||||
if (!SignCheckUtil.signCheck(params, getAppSecret())) {
|
||||
throw new BusinessException("签名失败");
|
||||
}
|
||||
}
|
||||
|
||||
// 模拟提交参数
|
||||
// String key = "FRbMx1FkG4Qz6GZxY";
|
||||
// Map<String, String> param0 = new HashMap<>();
|
||||
// param0.put("orderId", "D2018062976332656413");
|
||||
// param0.put("MainAccountID", "DC3NHPJ73S");
|
||||
// param0.put("MainAccountSN", "320");
|
||||
// param0.put("payStatus", "2");
|
||||
// param0.put("title","测试");
|
||||
// System.out.println("请求的参数 = " + param0);
|
||||
// String signString0 = SignCheckUtil.getSignString(param0, key);
|
||||
// System.out.println("signString0 = " + signString0);
|
||||
|
||||
// return SignCheckUtil.signCheck(params, getAppSecret());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前请求租户的AppSecret
|
||||
*
|
||||
* @return AppSecret
|
||||
*/
|
||||
public String getAppSecret() {
|
||||
String key = "cache5:AppSecret:" + Integer.valueOf(getAppId());
|
||||
System.out.println("key = " + key);
|
||||
return stringRedisTemplate.opsForValue().get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据账号|手机号码|邮箱查找用户ID
|
||||
* @return userId
|
||||
*/
|
||||
public Integer getUserIdByUsername(String username, Integer tenantId){
|
||||
// 按账号搜素
|
||||
User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username).eq(User::getTenantId,tenantId));
|
||||
if (user != null && user.getUserId() > 0) {
|
||||
return user.getUserId();
|
||||
}
|
||||
// 按手机号码搜索
|
||||
User userByPhone = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, username).eq(User::getTenantId, tenantId));
|
||||
if (userByPhone != null && userByPhone.getUserId() > 0) {
|
||||
return userByPhone.getUserId();
|
||||
}
|
||||
// 按邮箱搜索
|
||||
User userByEmail = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, username).eq(User::getTenantId, tenantId));
|
||||
if (userByEmail != null && userByEmail.getUserId() > 0) {
|
||||
return userByEmail.getUserId();
|
||||
}
|
||||
throw new BusinessException("找不到该用户");
|
||||
}
|
||||
|
||||
}
|
||||
68
src/main/java/com/gxwebsoft/common/core/web/BaseParam.java
Normal file
68
src/main/java/com/gxwebsoft/common/core/web/BaseParam.java
Normal file
@@ -0,0 +1,68 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.gxwebsoft.common.core.annotation.QueryField;
|
||||
import com.gxwebsoft.common.core.annotation.QueryType;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 查询参数基本字段
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-08-26 22:14:43
|
||||
*/
|
||||
@Data
|
||||
public class BaseParam implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty("分页查询页码")
|
||||
private Long page;
|
||||
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty("分页查询每页数量")
|
||||
private Long limit;
|
||||
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty(value = "排序字段", notes = "排序字段或sql, 如果是sql则order字段无用, 如: `id asc, name desc`")
|
||||
private String sort;
|
||||
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty(value = "排序方式", notes = "sort是字段名称时对应的排序方式, asc升序, desc降序")
|
||||
private String order;
|
||||
|
||||
@QueryField(value = "create_time", type = QueryType.GE)
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty("创建时间起始值")
|
||||
private String createTimeStart;
|
||||
|
||||
@QueryField(value = "create_time", type = QueryType.LE)
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty("创建时间结束值")
|
||||
private String createTimeEnd;
|
||||
|
||||
@QueryField(value = "create_time", type = QueryType.GE)
|
||||
@ApiModelProperty("搜索场景")
|
||||
@TableField(exist = false)
|
||||
private String sceneType;
|
||||
|
||||
@ApiModelProperty("模糊搜素")
|
||||
@TableField(exist = false)
|
||||
private String keywords;
|
||||
|
||||
/**
|
||||
* 获取集合中的第一条数据
|
||||
*
|
||||
* @param records 集合
|
||||
* @return 第一条数据
|
||||
*/
|
||||
public <T> T getOne(List<T> records) {
|
||||
return CommonUtil.listGetOne(records);
|
||||
}
|
||||
|
||||
}
|
||||
57
src/main/java/com/gxwebsoft/common/core/web/BatchParam.java
Normal file
57
src/main/java/com/gxwebsoft/common/core/web/BatchParam.java
Normal file
@@ -0,0 +1,57 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 批量修改通用参数
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-13 00:11:06
|
||||
*/
|
||||
@Data
|
||||
public class BatchParam<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "需要修改的数据id集合")
|
||||
private List<Serializable> ids;
|
||||
|
||||
@ApiModelProperty(value = "需要修改的字段和值")
|
||||
private T data;
|
||||
|
||||
/**
|
||||
* 通用批量修改方法
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField id字段名称
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean update(IService<T> service, String idField) {
|
||||
if (this.data == null) {
|
||||
return false;
|
||||
}
|
||||
return service.update(this.data, new UpdateWrapper<T>().in(idField, this.ids));
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用批量修改方法
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField id字段名称
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean update(IService<T> service, SFunction<T, ?> idField) {
|
||||
if (this.data == null) {
|
||||
return false;
|
||||
}
|
||||
return service.update(this.data, new LambdaUpdateWrapper<T>().in(idField, this.ids));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 检查是否存在通用参数
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-07 22:24:39
|
||||
*/
|
||||
@Data
|
||||
public class ExistenceParam<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "检查的字段")
|
||||
private String field;
|
||||
|
||||
@ApiModelProperty(value = "字段的值")
|
||||
private String value;
|
||||
|
||||
@ApiModelProperty(value = "修改时的主键")
|
||||
private Integer id;
|
||||
|
||||
/**
|
||||
* 检查是否存在
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField 修改时的主键字段
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isExistence(IService<T> service, String idField) {
|
||||
return isExistence(service, idField, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否存在
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField 修改时的主键字段
|
||||
* @param isToUnderlineCase 是否需要把field转为下划线格式
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isExistence(IService<T> service, String idField, boolean isToUnderlineCase) {
|
||||
if (StrUtil.hasBlank(this.field, this.value)) {
|
||||
return false;
|
||||
}
|
||||
String fieldName = isToUnderlineCase ? StrUtil.toUnderlineCase(field) : field;
|
||||
QueryWrapper<T> wrapper = new QueryWrapper<>();
|
||||
wrapper.eq(fieldName, value);
|
||||
if (id != null) {
|
||||
wrapper.ne(idField, id);
|
||||
}
|
||||
return service.count(wrapper) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否存在
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField 修改时的主键字段
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isExistence(IService<T> service, SFunction<T, ?> idField) {
|
||||
return isExistence(service, idField, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否存在
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField 修改时的主键字段
|
||||
* @param isToUnderlineCase 是否需要把field转为下划线格式
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isExistence(IService<T> service, SFunction<T, ?> idField, boolean isToUnderlineCase) {
|
||||
if (StrUtil.hasBlank(this.field, this.value)) {
|
||||
return false;
|
||||
}
|
||||
String fieldName = isToUnderlineCase ? StrUtil.toUnderlineCase(field) : field;
|
||||
LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.apply(fieldName + " = {0}", value);
|
||||
if (id != null) {
|
||||
wrapper.ne(idField, id);
|
||||
}
|
||||
return service.count(wrapper) > 0;
|
||||
}
|
||||
|
||||
}
|
||||
343
src/main/java/com/gxwebsoft/common/core/web/PageParam.java
Normal file
343
src/main/java/com/gxwebsoft/common/core/web/PageParam.java
Normal file
@@ -0,0 +1,343 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.util.ReflectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.OrderItem;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.annotation.QueryField;
|
||||
import com.gxwebsoft.common.core.annotation.QueryType;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 分页、排序、搜索参数封装
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2019-04-26 10:34:35
|
||||
*/
|
||||
public class PageParam<T, U extends BaseParam> extends Page<T> {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 租户id字段名称
|
||||
*/
|
||||
private static final String TENANT_ID_FIELD = "tenantId";
|
||||
|
||||
/**
|
||||
* 查询条件
|
||||
*/
|
||||
private final U where;
|
||||
|
||||
/**
|
||||
* 是否把字段名称驼峰转下划线
|
||||
*/
|
||||
private final boolean isToUnderlineCase;
|
||||
|
||||
public PageParam() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public PageParam(U where) {
|
||||
this(where, true);
|
||||
}
|
||||
|
||||
public PageParam(U where, boolean isToUnderlineCase) {
|
||||
super();
|
||||
this.where = where;
|
||||
this.isToUnderlineCase = isToUnderlineCase;
|
||||
if (where != null) {
|
||||
// 获取分页页码
|
||||
if (where.getPage() != null) {
|
||||
setCurrent(where.getPage());
|
||||
}
|
||||
// 获取分页每页数量
|
||||
if (where.getLimit() != null) {
|
||||
setSize(where.getLimit());
|
||||
}
|
||||
// 获取排序方式
|
||||
if (where.getSort() != null) {
|
||||
if (sortIsSQL(where.getSort())) {
|
||||
setOrders(parseOrderSQL(where.getSort()));
|
||||
} else {
|
||||
List<OrderItem> orderItems = new ArrayList<>();
|
||||
String column = this.isToUnderlineCase ? StrUtil.toUnderlineCase(where.getSort()) : where.getSort();
|
||||
boolean asc = !Constants.ORDER_DESC_VALUE.equals(where.getOrder());
|
||||
orderItems.add(new OrderItem(column, asc));
|
||||
setOrders(orderItems);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 排序字段是否是sql
|
||||
*/
|
||||
private boolean sortIsSQL(String sort) {
|
||||
return sort != null && (sort.contains(",") || sort.trim().contains(" "));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析排序sql
|
||||
*/
|
||||
private List<OrderItem> parseOrderSQL(String orderSQL) {
|
||||
List<OrderItem> orders = new ArrayList<>();
|
||||
if (StrUtil.isNotBlank(orderSQL)) {
|
||||
for (String item : orderSQL.split(",")) {
|
||||
String[] temp = item.trim().split(" ");
|
||||
if (!temp[0].isEmpty()) {
|
||||
String column = this.isToUnderlineCase ? StrUtil.toUnderlineCase(temp[0]) : temp[0];
|
||||
boolean asc = temp.length == 1 || !temp[temp.length - 1].equals(Constants.ORDER_DESC_VALUE);
|
||||
orders.add(new OrderItem(column, asc));
|
||||
}
|
||||
}
|
||||
}
|
||||
return orders;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置默认排序方式
|
||||
*
|
||||
* @param orderItems 排序方式
|
||||
* @return PageParam
|
||||
*/
|
||||
public PageParam<T, U> setDefaultOrder(List<OrderItem> orderItems) {
|
||||
if (orders() == null || orders().size() == 0) {
|
||||
setOrders(orderItems);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置默认排序方式
|
||||
*
|
||||
* @param orderSQL 排序方式
|
||||
* @return PageParam
|
||||
*/
|
||||
public PageParam<T, U> setDefaultOrder(String orderSQL) {
|
||||
setDefaultOrder(parseOrderSQL(orderSQL));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取查询条件
|
||||
*
|
||||
* @param excludes 不包含的字段
|
||||
* @return QueryWrapper
|
||||
*/
|
||||
public QueryWrapper<T> getWrapper(String... excludes) {
|
||||
return buildWrapper(null, Arrays.asList(excludes));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取查询条件
|
||||
*
|
||||
* @param columns 只包含的字段
|
||||
* @return QueryWrapper
|
||||
*/
|
||||
public QueryWrapper<T> getWrapperWith(String... columns) {
|
||||
return buildWrapper(Arrays.asList(columns), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建QueryWrapper
|
||||
*
|
||||
* @param columns 包含的字段
|
||||
* @param excludes 排除的字段
|
||||
* @return QueryWrapper
|
||||
*/
|
||||
private QueryWrapper<T> buildWrapper(List<String> columns, List<String> excludes) {
|
||||
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
|
||||
Map<String, Object> map = BeanUtil.beanToMap(where, false, true);
|
||||
for (String fieldName : map.keySet()) {
|
||||
Object fieldValue = map.get(fieldName);
|
||||
Field field = ReflectUtil.getField(where.getClass(), fieldName);
|
||||
|
||||
// 过滤不包含的字段
|
||||
if (columns != null && !columns.contains(fieldName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 过滤排除的字段
|
||||
if (excludes != null && excludes.contains(fieldName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 过滤逻辑删除字段
|
||||
if (field.getAnnotation(TableLogic.class) != null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 过滤租户id字段
|
||||
if (fieldName.equals(TENANT_ID_FIELD)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 获取注解指定的查询字段及查询方式
|
||||
QueryType queryType = QueryType.LIKE;
|
||||
QueryField queryField = field.getAnnotation(QueryField.class);
|
||||
if (queryField != null) {
|
||||
if (StrUtil.isNotEmpty(queryField.value())) {
|
||||
fieldName = queryField.value();
|
||||
}
|
||||
if (queryField.type() != null) {
|
||||
queryType = queryField.type();
|
||||
}
|
||||
} else {
|
||||
// 过滤非本表的字段
|
||||
TableField tableField = field.getAnnotation(TableField.class);
|
||||
if (tableField != null && !tableField.exist()) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 字段名驼峰转下划线
|
||||
if (this.isToUnderlineCase) {
|
||||
fieldName = StrUtil.toUnderlineCase(fieldName);
|
||||
}
|
||||
|
||||
//
|
||||
switch (queryType) {
|
||||
case EQ:
|
||||
queryWrapper.eq(fieldName, fieldValue);
|
||||
break;
|
||||
case NE:
|
||||
queryWrapper.ne(fieldName, fieldValue);
|
||||
break;
|
||||
case GT:
|
||||
queryWrapper.gt(fieldName, fieldValue);
|
||||
break;
|
||||
case GE:
|
||||
queryWrapper.ge(fieldName, fieldValue);
|
||||
break;
|
||||
case LT:
|
||||
queryWrapper.lt(fieldName, fieldValue);
|
||||
break;
|
||||
case LE:
|
||||
queryWrapper.le(fieldName, fieldValue);
|
||||
break;
|
||||
case LIKE:
|
||||
queryWrapper.like(fieldName, fieldValue);
|
||||
break;
|
||||
case NOT_LIKE:
|
||||
queryWrapper.notLike(fieldName, fieldValue);
|
||||
break;
|
||||
case LIKE_LEFT:
|
||||
queryWrapper.likeLeft(fieldName, fieldValue);
|
||||
break;
|
||||
case LIKE_RIGHT:
|
||||
queryWrapper.likeRight(fieldName, fieldValue);
|
||||
break;
|
||||
case IS_NULL:
|
||||
queryWrapper.isNull(fieldName);
|
||||
break;
|
||||
case IS_NOT_NULL:
|
||||
queryWrapper.isNotNull(fieldName);
|
||||
break;
|
||||
case IN:
|
||||
queryWrapper.in(fieldName, fieldValue);
|
||||
break;
|
||||
case NOT_IN:
|
||||
queryWrapper.notIn(fieldName, fieldValue);
|
||||
break;
|
||||
case IN_STR:
|
||||
if (fieldValue instanceof String) {
|
||||
queryWrapper.in(fieldName, Arrays.asList(((String) fieldValue).split(",")));
|
||||
}
|
||||
break;
|
||||
case NOT_IN_STR:
|
||||
if (fieldValue instanceof String) {
|
||||
queryWrapper.notIn(fieldName, Arrays.asList(((String) fieldValue).split(",")));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return queryWrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取包含排序的查询条件
|
||||
*
|
||||
* @return 包含排序的QueryWrapper
|
||||
*/
|
||||
public QueryWrapper<T> getOrderWrapper() {
|
||||
return getOrderWrapper(getWrapper());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取包含排序的查询条件
|
||||
*
|
||||
* @param queryWrapper 不含排序的QueryWrapper
|
||||
* @return 包含排序的QueryWrapper
|
||||
*/
|
||||
public QueryWrapper<T> getOrderWrapper(QueryWrapper<T> queryWrapper) {
|
||||
if (queryWrapper == null) {
|
||||
queryWrapper = new QueryWrapper<>();
|
||||
}
|
||||
for (OrderItem orderItem : orders()) {
|
||||
if (orderItem.isAsc()) {
|
||||
queryWrapper.orderByAsc(orderItem.getColumn());
|
||||
} else {
|
||||
queryWrapper.orderByDesc(orderItem.getColumn());
|
||||
}
|
||||
}
|
||||
return queryWrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取集合中的第一条数据
|
||||
*
|
||||
* @param records 集合
|
||||
* @return 第一条数据
|
||||
*/
|
||||
public T getOne(List<T> records) {
|
||||
return CommonUtil.listGetOne(records);
|
||||
}
|
||||
|
||||
/**
|
||||
* 代码排序集合
|
||||
*
|
||||
* @param records 集合
|
||||
* @return 排序后的集合
|
||||
*/
|
||||
public List<T> sortRecords(List<T> records) {
|
||||
List<OrderItem> orderItems = orders();
|
||||
if (records == null || records.size() < 2 || orderItems == null || orderItems.size() == 0) {
|
||||
return records;
|
||||
}
|
||||
Comparator<T> comparator = null;
|
||||
for (OrderItem item : orderItems) {
|
||||
if (item.getColumn() == null) {
|
||||
continue;
|
||||
}
|
||||
String field = this.isToUnderlineCase ? StrUtil.toCamelCase(item.getColumn()) : item.getColumn();
|
||||
Function keyExtractor = t -> ReflectUtil.getFieldValue(t, field);
|
||||
if (comparator == null) {
|
||||
if (item.isAsc()) {
|
||||
comparator = Comparator.comparing(keyExtractor);
|
||||
} else {
|
||||
comparator = Comparator.comparing(keyExtractor, Comparator.reverseOrder());
|
||||
}
|
||||
} else {
|
||||
if (item.isAsc()) {
|
||||
comparator.thenComparing(keyExtractor);
|
||||
} else {
|
||||
comparator.thenComparing(keyExtractor, Comparator.reverseOrder());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (comparator != null) {
|
||||
return records.stream().sorted(comparator).collect(Collectors.toList());
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
}
|
||||
51
src/main/java/com/gxwebsoft/common/core/web/PageResult.java
Normal file
51
src/main/java/com/gxwebsoft/common/core/web/PageResult.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 分页查询返回结果
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:02
|
||||
*/
|
||||
public class PageResult<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "当前页数据")
|
||||
private List<T> list;
|
||||
|
||||
@ApiModelProperty(value = "总数量")
|
||||
private Long count;
|
||||
|
||||
public PageResult() {
|
||||
}
|
||||
|
||||
public PageResult(List<T> list) {
|
||||
this(list, null);
|
||||
}
|
||||
|
||||
public PageResult(List<T> list, Long count) {
|
||||
setList(list);
|
||||
setCount(count);
|
||||
}
|
||||
|
||||
public List<T> getList() {
|
||||
return this.list;
|
||||
}
|
||||
|
||||
public void setList(List<T> list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
public Long getCount() {
|
||||
return this.count;
|
||||
}
|
||||
|
||||
public void setCount(Long count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.utils.CacheClient;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.core.web.*;
|
||||
import com.gxwebsoft.common.system.entity.AccessKey;
|
||||
import com.gxwebsoft.common.system.param.AccessKeyParam;
|
||||
import com.gxwebsoft.common.system.service.AccessKeyService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 访问凭证管理控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2023-05-16 19:19:55
|
||||
*/
|
||||
@Api(tags = "访问凭证管理管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/access-key")
|
||||
public class AccessKeyController extends BaseController {
|
||||
@Resource
|
||||
private AccessKeyService accessKeyService;
|
||||
@Resource
|
||||
private CacheClient cacheClient;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:accessKey:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询访问凭证管理")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<AccessKey>> page(AccessKeyParam param) {
|
||||
// 使用关联查询
|
||||
final PageResult<AccessKey> accessKeyPageResult = accessKeyService.pageRel(param);
|
||||
if (param.getCode() != null) {
|
||||
// 短信验证码校验
|
||||
String code = cacheClient.get(param.getPhone(), String.class);
|
||||
if (StrUtil.equals(code,param.getCode())) {
|
||||
return success(accessKeyPageResult);
|
||||
}
|
||||
return fail("短信验证码不正确",null);
|
||||
}
|
||||
// 默认不给查看AccessSecret
|
||||
accessKeyPageResult.getList().forEach( d -> {
|
||||
d.setAccessSecret(null);
|
||||
});
|
||||
return success(accessKeyPageResult);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:accessKey:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部访问凭证管理")
|
||||
@GetMapping()
|
||||
public ApiResult<List<AccessKey>> list(AccessKeyParam param) {
|
||||
PageParam<AccessKey, AccessKeyParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("create_time desc");
|
||||
return success(accessKeyService.list(page.getOrderWrapper()));
|
||||
// 使用关联查询
|
||||
//return success(accessKeyService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:accessKey:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询访问凭证管理")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<AccessKey> get(@PathVariable("id") Integer id) {
|
||||
return success(accessKeyService.getById(id));
|
||||
// 使用关联查询
|
||||
//return success(accessKeyService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:accessKey:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加访问凭证管理")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody AccessKey accessKey) {
|
||||
final int count = accessKeyService.count();
|
||||
if (count >= 5) {
|
||||
return fail("当前账号只能绑定 5 个 AccessKey");
|
||||
}
|
||||
accessKey.setAccessKey("AI" + CommonUtil.randomUUID16());
|
||||
accessKey.setAccessSecret(CommonUtil.randomUUID16().concat(CommonUtil.randomUUID16()));
|
||||
if (accessKeyService.save(accessKey)) {
|
||||
return success("创建成功");
|
||||
}
|
||||
return fail("创建失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:accessKey:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改访问凭证管理")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody AccessKey accessKey) {
|
||||
if (accessKeyService.updateById(accessKey)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:accessKey:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除访问凭证管理")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (accessKeyService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:accessKey:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加访问凭证管理")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<AccessKey> list) {
|
||||
if (accessKeyService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:accessKey:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量修改访问凭证管理")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<AccessKey> batchParam) {
|
||||
if (batchParam.update(accessKeyService, "id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:accessKey:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除访问凭证管理")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (accessKeyService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.aliyun.oss.ClientException;
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.common.auth.*;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import com.aliyun.oss.OSSException;
|
||||
import com.aliyun.oss.common.utils.BinaryUtil;
|
||||
import com.aliyun.oss.model.PolicyConditions;
|
||||
import com.aliyun.oss.model.PutObjectRequest;
|
||||
import com.aliyun.oss.model.PutObjectResult;
|
||||
import com.aliyuncs.DefaultAcsClient;
|
||||
import com.aliyuncs.auth.sts.AssumeRoleRequest;
|
||||
import com.aliyuncs.auth.sts.AssumeRoleResponse;
|
||||
import com.aliyuncs.http.MethodType;
|
||||
import com.aliyuncs.profile.DefaultProfile;
|
||||
import com.aliyuncs.profile.IClientProfile;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.utils.FileServerUtil;
|
||||
import com.gxwebsoft.common.core.utils.RedisUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.system.entity.FileRecord;
|
||||
import com.gxwebsoft.common.system.service.FileRecordService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.File;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 阿里云OSS云存储
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2022-11-19 13:54:27
|
||||
*/
|
||||
@Api(tags = "阿里云OSS云存储")
|
||||
@RestController
|
||||
@RequestMapping("/api/oss")
|
||||
public class AliOssController extends BaseController {
|
||||
@Resource
|
||||
private ConfigProperties config;
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
@Resource
|
||||
private FileRecordService fileRecordService;
|
||||
|
||||
@OperationLog
|
||||
@ApiOperation("上传文件")
|
||||
@PostMapping("/upload")
|
||||
public ApiResult<FileRecord> upload(@RequestParam MultipartFile file, HttpServletRequest request) throws Exception{
|
||||
FileRecord result = null;
|
||||
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
|
||||
String endpoint = config.getEndpoint();
|
||||
// RAM用户的访问密钥(AccessKey ID和AccessKey Secret)。
|
||||
String accessKeyId = config.getAccessKeyId();
|
||||
String accessKeySecret = config.getAccessKeySecret();
|
||||
// 使用代码嵌入的RAM用户的访问密钥配置访问凭证。
|
||||
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
|
||||
// 填写Bucket名称,例如examplebucket。
|
||||
String bucketName = config.getBucketName();
|
||||
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
|
||||
// String objectName = "exampledir/exampleobject.txt";
|
||||
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
|
||||
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
|
||||
// String filePath= "D:\\localpath\\examplefile.txt";
|
||||
|
||||
// 创建OSSClient实例。
|
||||
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
|
||||
|
||||
try {
|
||||
|
||||
String dir = getUploadDir();
|
||||
File upload = FileServerUtil.upload(file, dir, config.getUploadUuidName());
|
||||
String path = upload.getAbsolutePath().replace("\\", "/").substring(dir.length());
|
||||
String originalName = file.getOriginalFilename();
|
||||
|
||||
// 创建PutObjectRequest对象。
|
||||
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, upload);
|
||||
// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
|
||||
// ObjectMetadata metadata = new ObjectMetadata();
|
||||
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
|
||||
// metadata.setObjectAcl(CannedAccessControlList.Private);
|
||||
// putObjectRequest.setMetadata(metadata);
|
||||
|
||||
// 上传文件。
|
||||
PutObjectResult ossResult = ossClient.putObject(putObjectRequest);
|
||||
|
||||
// 保存记录并返回
|
||||
String requestURL = config.getBucketDomain();
|
||||
final String domain = redisUtil.getUploadConfig(getTenantId()).get("bucketDomain");
|
||||
if(StrUtil.isNotBlank(domain)){
|
||||
requestURL = domain;
|
||||
}
|
||||
path = "/".concat(path);
|
||||
upload.delete();
|
||||
final String cache = redisUtil.get("setting:upload:" + getTenantId());
|
||||
final JSONObject jsonObject = JSONObject.parseObject(cache);
|
||||
final String bucketDomain = jsonObject.getString("bucketDomain");
|
||||
if(StrUtil.isNotBlank(bucketDomain)){
|
||||
requestURL = bucketDomain;
|
||||
}
|
||||
result = new FileRecord();
|
||||
result.setCreateUserId(getLoginUserId());
|
||||
result.setName(StrUtil.isBlank(originalName) ? upload.getName() : originalName);
|
||||
result.setLength(upload.length());
|
||||
result.setPath(requestURL + path);
|
||||
result.setThumbnail(requestURL + path + "?x-oss-process=image/resize,m_fixed,w_100,h_100/quality,Q_90");
|
||||
result.setUrl(requestURL + path + "?x-oss-process=image/resize,w_750/quality,Q_90");
|
||||
result.setDownloadUrl(requestURL + path);
|
||||
String contentType = FileServerUtil.getContentType(upload);
|
||||
result.setContentType(contentType);
|
||||
fileRecordService.save(result);
|
||||
return success(result);
|
||||
|
||||
} catch (OSSException oe) {
|
||||
System.out.println("Caught an OSSException, which means your request made it to OSS, "
|
||||
+ "but was rejected with an error response for some reason.");
|
||||
System.out.println("Error Message:" + oe.getErrorMessage());
|
||||
System.out.println("Error Code:" + oe.getErrorCode());
|
||||
System.out.println("Request ID:" + oe.getRequestId());
|
||||
System.out.println("Host ID:" + oe.getHostId());
|
||||
} catch (ClientException ce) {
|
||||
System.out.println("Caught an ClientException, which means the client encountered "
|
||||
+ "a serious internal problem while trying to communicate with OSS, "
|
||||
+ "such as not being able to access the network.");
|
||||
System.out.println("Error Message:" + ce.getMessage());
|
||||
} finally {
|
||||
if (ossClient != null) {
|
||||
ossClient.shutdown();
|
||||
}
|
||||
}
|
||||
return fail("上传失败", null);
|
||||
}
|
||||
|
||||
|
||||
@OperationLog
|
||||
@ApiOperation("获取临时osstoken")
|
||||
@GetMapping("/getSTSToken")
|
||||
public ApiResult<?> getSTSToken() {
|
||||
// STS接入地址,例如sts.cn-hangzhou.aliyuncs.com。
|
||||
String endpoint = "sts.cn-shenzhen.aliyuncs.com";
|
||||
// 填写步骤1生成的RAM用户访问密钥AccessKey ID和AccessKey Secret。
|
||||
String accessKeyId = "LTAI5t8UTh8CTXEi2dYxobhj";
|
||||
String accessKeySecret = "fNdJOT4KAjrVrzHNAcSJuUCy9ZljD9";
|
||||
// 填写步骤3获取的角色ARN。
|
||||
String roleArn = "acs:ram::1194088977870561:role/ramosstest";
|
||||
// 自定义角色会话名称,用来区分不同的令牌,例如可填写为SessionTest。
|
||||
String roleSessionName = "jimeiapp";
|
||||
// 设置临时访问凭证的有效时间为3600秒。
|
||||
Long durationSeconds = 3600L;
|
||||
try {
|
||||
// regionId表示RAM的地域ID。以华东1(杭州)地域为例,regionID填写为cn-hangzhou。也可以保留默认值,默认值为空字符串("")。
|
||||
String regionId = "";
|
||||
// 添加endpoint。适用于Java SDK 3.12.0及以上版本。
|
||||
DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
|
||||
// 构造default profile。
|
||||
IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
|
||||
// 构造client。
|
||||
DefaultAcsClient client = new DefaultAcsClient(profile);
|
||||
final AssumeRoleRequest request = new AssumeRoleRequest();
|
||||
// 适用于Java SDK 3.12.0及以上版本。
|
||||
request.setSysMethod(MethodType.POST);
|
||||
// 适用于Java SDK 3.12.0以下版本。
|
||||
//request.setMethod(MethodType.POST);
|
||||
request.setRoleArn(roleArn);
|
||||
request.setRoleSessionName(roleSessionName);
|
||||
// request.setPolicy(policy);
|
||||
request.setDurationSeconds(durationSeconds);
|
||||
final AssumeRoleResponse response = client.getAcsResponse(request);
|
||||
return success(response);
|
||||
} catch (ClientException | com.aliyuncs.exceptions.ClientException e) {
|
||||
System.out.println("Failed:");
|
||||
System.out.println("Error message: " + e.getMessage());
|
||||
return fail(e.getMessage());
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取前端表单提交的参数
|
||||
* @return
|
||||
*/
|
||||
@ApiOperation("")
|
||||
@GetMapping("/getPostForm")
|
||||
public ApiResult<?> getPostForm(){
|
||||
String endpoint = config.getEndpoint();
|
||||
// RAM用户的访问密钥(AccessKey ID和AccessKey Secret)。
|
||||
String accessKeyId = "LTAI5t8UTh8CTXEi2dYxobhj";
|
||||
String accessKeySecret = "fNdJOT4KAjrVrzHNAcSJuUCy9ZljD9";
|
||||
// 使用代码嵌入的RAM用户的访问密钥配置访问凭证。
|
||||
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
|
||||
// 填写Bucket名称,例如examplebucket。
|
||||
String bucket = config.getBucketName();
|
||||
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
|
||||
|
||||
try {
|
||||
String host = "https://" + bucket + "." + endpoint;
|
||||
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
|
||||
|
||||
|
||||
long expireTime = 60;
|
||||
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
|
||||
Date expiration = new Date(expireEndTime);
|
||||
PolicyConditions policyConds = new PolicyConditions();
|
||||
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE,0,100*1024*1024);
|
||||
|
||||
|
||||
String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
|
||||
byte[] binaryData = postPolicy.getBytes("utf-8");
|
||||
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
|
||||
String postSignature = ossClient.calculatePostSignature(postPolicy);
|
||||
Map result = new HashMap<>();
|
||||
result.put("polocyBase64",encodedPolicy);
|
||||
result.put("signature",postSignature);
|
||||
result.put("expireEndTime",expireEndTime);
|
||||
return success(result);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
return fail();
|
||||
}finally {
|
||||
ossClient.shutdown();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传位置(服务器)
|
||||
*/
|
||||
private String getUploadDir() {
|
||||
return config.getUploadPath() + "file/";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.utils.CacheClient;
|
||||
import com.gxwebsoft.common.core.utils.RedisUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.system.entity.Cache;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.service.SettingService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 缓存控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2022-11-19 13:54:27
|
||||
*/
|
||||
@Api(tags = "缓存管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/cache")
|
||||
public class CacheController extends BaseController {
|
||||
@Resource
|
||||
private SettingService settingService;
|
||||
@Resource
|
||||
private CacheClient cacheClient;
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
@Resource
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:cache:list')")
|
||||
@ApiOperation("查询全部缓存")
|
||||
@GetMapping()
|
||||
public ApiResult<HashMap<String, Object>> list() {
|
||||
String key = "cache".concat(getTenantId().toString()).concat("*");
|
||||
final Set<String> keys = stringRedisTemplate.keys(key);
|
||||
final HashMap<String, Object> map = new HashMap<>();
|
||||
final ArrayList<Object> list = new ArrayList<>();
|
||||
assert keys != null;
|
||||
keys.forEach(d -> {
|
||||
final Cache cache = new Cache();
|
||||
cache.setKey(d);
|
||||
try {
|
||||
final String content = stringRedisTemplate.opsForValue().get(d);
|
||||
if(content != null){
|
||||
cache.setContent(stringRedisTemplate.opsForValue().get(d));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
list.add(cache);
|
||||
});
|
||||
map.put("count",keys.size());
|
||||
map.put("list",list);
|
||||
return success(map);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:cache:list')")
|
||||
@ApiOperation("根据key查询缓存信息")
|
||||
@GetMapping("/{key}")
|
||||
public ApiResult<?> get(@PathVariable("key") String key) {
|
||||
final String s = redisUtil.get(key + getTenantId());
|
||||
if(StrUtil.isNotBlank(s)){
|
||||
return success("读取成功", JSONObject.parseObject(s));
|
||||
}
|
||||
return fail("缓存不存在!");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:cache:save')")
|
||||
@ApiOperation("添加缓存")
|
||||
@PostMapping()
|
||||
public ApiResult<?> add(@RequestBody Cache cache) {
|
||||
if (cache.getExpireTime() != null) {
|
||||
redisUtil.set(cache.getKey() + ":" + getTenantId(),cache.getContent(),cache.getExpireTime(), TimeUnit.MINUTES);
|
||||
return success("缓存成功");
|
||||
}
|
||||
redisUtil.set(cache.getKey() + ":" + getTenantId(),cache.getContent());
|
||||
return success("缓存成功");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:cache:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除缓存")
|
||||
@DeleteMapping("/{key}")
|
||||
public ApiResult<?> remove(@PathVariable("key") String key) {
|
||||
if (Boolean.TRUE.equals(stringRedisTemplate.delete(key))) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:cache:save')")
|
||||
@ApiOperation("缓存皮肤")
|
||||
@PostMapping("/theme")
|
||||
public ApiResult<?> saveTheme(@RequestBody Cache cache) {
|
||||
final User loginUser = getLoginUser();
|
||||
final String username = loginUser.getUsername();
|
||||
if (username.equals("admin")) {
|
||||
redisUtil.set(cache.getKey() + ":" + getTenantId(),cache.getContent());
|
||||
return success("缓存成功");
|
||||
}
|
||||
return success("缓存失败");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.web.*;
|
||||
import com.gxwebsoft.common.system.entity.Company;
|
||||
import com.gxwebsoft.common.system.entity.Tenant;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.param.CompanyParam;
|
||||
import com.gxwebsoft.common.system.service.CompanyService;
|
||||
import com.gxwebsoft.common.system.service.FileRecordService;
|
||||
import com.gxwebsoft.common.system.service.TenantService;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 企业信息控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2023-05-27 14:57:34
|
||||
*/
|
||||
@Api(tags = "企业信息管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/company")
|
||||
public class CompanyController extends BaseController {
|
||||
@Resource
|
||||
private CompanyService companyService;
|
||||
@Resource
|
||||
private TenantService tenantService;
|
||||
@Resource
|
||||
private UserService userService;
|
||||
@Resource
|
||||
private FileRecordService fileRecordService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:company:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询企业信息")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<Company>> page(CompanyParam param) {
|
||||
// 使用关联查询
|
||||
return success(companyService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:company:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部企业信息")
|
||||
@GetMapping()
|
||||
public ApiResult<List<Company>> list(CompanyParam param) {
|
||||
// 使用关联查询
|
||||
return success(companyService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:company:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询企业信息")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<Company> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(companyService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:company:profile')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加企业信息")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody Company company) {
|
||||
// 记录当前登录用户id
|
||||
User loginUser = getLoginUser();
|
||||
if (loginUser != null) {
|
||||
company.setUserId(loginUser.getUserId());
|
||||
}
|
||||
if (companyService.save(company)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:company:profile')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改企业信息")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody Company company) {
|
||||
final int count = companyService.count();
|
||||
if (companyService.updateById(company)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败",count);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:company:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除企业信息")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (companyService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:company:profile')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加企业信息")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<Company> list) {
|
||||
if (companyService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:company:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量修改企业信息")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<Company> batchParam) {
|
||||
if (batchParam.update(companyService, "company_id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:company:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除企业信息")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (companyService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:company:profile')")
|
||||
@ApiOperation("根据id查询企业信息")
|
||||
@GetMapping("/profile")
|
||||
public ApiResult<Company> profile() {
|
||||
final CompanyParam param = new CompanyParam();
|
||||
param.setTenantId(getTenantId());
|
||||
param.setAuthoritative(true);
|
||||
final List<Company> list = companyService.listRel(param);
|
||||
if(!CollectionUtils.isEmpty(list)){
|
||||
return success(list.get(0));
|
||||
}
|
||||
return fail("企业不存在",null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.core.web.PageParam;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.system.entity.Dict;
|
||||
import com.gxwebsoft.common.system.entity.DictData;
|
||||
import com.gxwebsoft.common.system.param.DictDataParam;
|
||||
import com.gxwebsoft.common.system.param.DictParam;
|
||||
import com.gxwebsoft.common.system.service.DictDataService;
|
||||
import com.gxwebsoft.common.system.service.DictService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 字典控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-14 11:29:03
|
||||
*/
|
||||
@Api(tags = "字典管理(业务类)")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/dict")
|
||||
public class DictController extends BaseController {
|
||||
@Resource
|
||||
private DictService dictService;
|
||||
@Resource
|
||||
private DictDataService dictDataService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询字典")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<Dict>> page(DictParam param) {
|
||||
PageParam<Dict, DictParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("sort_number");
|
||||
return success(dictService.page(page, page.getWrapper()));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部字典")
|
||||
@GetMapping()
|
||||
public ApiResult<List<Dict>> list(DictParam param) {
|
||||
PageParam<Dict, DictParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("sort_number");
|
||||
return success(dictService.list(page.getOrderWrapper()));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部字典")
|
||||
@GetMapping("/tree")
|
||||
public ApiResult<?> tree() {
|
||||
final HashMap<Object, Object> result = new HashMap<>();
|
||||
final List<DictData> dictData = dictDataService.listRel(new DictDataParam());
|
||||
final Map<String, List<DictData>> dataCollect = dictData.stream().collect(Collectors.groupingBy(DictData::getDictCode));
|
||||
for (String code : dataCollect.keySet()) {
|
||||
Dict dict = new Dict();
|
||||
dict.setDictCode(code);
|
||||
final Set<Set<String>> list = new LinkedHashSet<>();
|
||||
Set<String> codes = new LinkedHashSet<>();
|
||||
for(DictData item : dictData){
|
||||
if (item.getDictCode().equals(code)) {
|
||||
codes.add(item.getDictDataCode());
|
||||
}
|
||||
}
|
||||
list.add(codes);
|
||||
dict.setItems(list);
|
||||
result.put(code,dict.getItems());
|
||||
}
|
||||
return success(result);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询字典")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<Dict> get(@PathVariable("id") Integer id) {
|
||||
return success(dictService.getById(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:save')")
|
||||
@ApiOperation("添加字典")
|
||||
@PostMapping()
|
||||
public ApiResult<?> add(@RequestBody Dict dict) {
|
||||
if (dictService.count(new LambdaQueryWrapper<Dict>()
|
||||
.eq(Dict::getDictCode, dict.getDictCode())) > 0) {
|
||||
return fail("字典标识已存在");
|
||||
}
|
||||
if (dictService.count(new LambdaQueryWrapper<Dict>()
|
||||
.eq(Dict::getDictName, dict.getDictName())) > 0) {
|
||||
return fail("字典名称已存在");
|
||||
}
|
||||
if (dictService.save(dict)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改字典")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody Dict dict) {
|
||||
if (dictService.count(new LambdaQueryWrapper<Dict>()
|
||||
.eq(Dict::getDictCode, dict.getDictCode())
|
||||
.ne(Dict::getDictId, dict.getDictId())) > 0) {
|
||||
return fail("字典标识已存在");
|
||||
}
|
||||
if (dictService.count(new LambdaQueryWrapper<Dict>()
|
||||
.eq(Dict::getDictName, dict.getDictName())
|
||||
.ne(Dict::getDictId, dict.getDictId())) > 0) {
|
||||
return fail("字典名称已存在");
|
||||
}
|
||||
if (dictService.updateById(dict)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除字典")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (dictService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加字典")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<List<String>> saveBatch(@RequestBody List<Dict> list) {
|
||||
if (CommonUtil.checkRepeat(list, Dict::getDictCode)) {
|
||||
return fail("字典标识不能重复", null);
|
||||
}
|
||||
if (CommonUtil.checkRepeat(list, Dict::getDictName)) {
|
||||
return fail("字典名称不能重复", null);
|
||||
}
|
||||
List<Dict> codeExists = dictService.list(new LambdaQueryWrapper<Dict>()
|
||||
.in(Dict::getDictCode, list.stream().map(Dict::getDictCode)
|
||||
.collect(Collectors.toList())));
|
||||
if (codeExists.size() > 0) {
|
||||
return fail("字典标识已存在", codeExists.stream().map(Dict::getDictCode)
|
||||
.collect(Collectors.toList())).setCode(2);
|
||||
}
|
||||
List<Dict> nameExists = dictService.list(new LambdaQueryWrapper<Dict>()
|
||||
.in(Dict::getDictName, list.stream().map(Dict::getDictCode)
|
||||
.collect(Collectors.toList())));
|
||||
if (nameExists.size() > 0) {
|
||||
return fail("字典名称已存在", nameExists.stream().map(Dict::getDictName)
|
||||
.collect(Collectors.toList())).setCode(3);
|
||||
}
|
||||
if (dictService.saveBatch(list)) {
|
||||
return success("添加成功", null);
|
||||
}
|
||||
return fail("添加失败", null);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除字典")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (dictService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.system.entity.DictData;
|
||||
import com.gxwebsoft.common.system.param.DictDataParam;
|
||||
import com.gxwebsoft.common.system.service.DictDataService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 字典数据控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-14 11:29:04
|
||||
*/
|
||||
@Api(tags = "字典数据管理(业务类)")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/dict-data")
|
||||
public class DictDataController extends BaseController {
|
||||
@Resource
|
||||
private DictDataService dictDataService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询字典数据")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<DictData>> page(DictDataParam param) {
|
||||
return success(dictDataService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部字典数据")
|
||||
@GetMapping()
|
||||
public ApiResult<List<DictData>> list(DictDataParam param) {
|
||||
return success(dictDataService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询字典数据")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<DictData> get(@PathVariable("id") Integer id) {
|
||||
return success(dictDataService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加字典数据")
|
||||
@PostMapping()
|
||||
public ApiResult<?> add(@RequestBody DictData dictData) {
|
||||
if (dictDataService.count(new LambdaQueryWrapper<DictData>()
|
||||
.eq(DictData::getDictId, dictData.getDictId())
|
||||
.eq(DictData::getDictDataName, dictData.getDictDataName())) > 0) {
|
||||
return fail("字典数据名称已存在");
|
||||
}
|
||||
if (dictDataService.count(new LambdaQueryWrapper<DictData>()
|
||||
.eq(DictData::getDictId, dictData.getDictId())
|
||||
.eq(DictData::getDictDataCode, dictData.getDictDataCode())) > 0) {
|
||||
return fail("字典数据标识已存在");
|
||||
}
|
||||
if (dictDataService.save(dictData)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改字典数据")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody DictData dictData) {
|
||||
if (dictDataService.count(new LambdaQueryWrapper<DictData>()
|
||||
.eq(DictData::getDictId, dictData.getDictId())
|
||||
.eq(DictData::getDictDataName, dictData.getDictDataName())
|
||||
.ne(DictData::getDictDataId, dictData.getDictDataId())) > 0) {
|
||||
return fail("字典数据名称已存在");
|
||||
}
|
||||
if (dictDataService.count(new LambdaQueryWrapper<DictData>()
|
||||
.eq(DictData::getDictId, dictData.getDictId())
|
||||
.eq(DictData::getDictDataCode, dictData.getDictDataCode())
|
||||
.ne(DictData::getDictDataId, dictData.getDictDataId())) > 0) {
|
||||
return fail("字典数据标识已存在");
|
||||
}
|
||||
if (dictDataService.updateById(dictData)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除字典数据")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (dictDataService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加字典数据")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<DictData> dictDataList) {
|
||||
if (dictDataService.saveBatch(dictDataList)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除字典数据")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (dictDataService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.core.web.PageParam;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.system.entity.Dictionary;
|
||||
import com.gxwebsoft.common.system.param.DictionaryParam;
|
||||
import com.gxwebsoft.common.system.service.DictionaryService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 字典控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-14 11:29:03
|
||||
*/
|
||||
@Api(tags = "字典管理(系统类)")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/dictionary")
|
||||
public class DictionaryController extends BaseController {
|
||||
@Resource
|
||||
private DictionaryService dictionaryService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dictionary:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询字典")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<Dictionary>> page(DictionaryParam param) {
|
||||
PageParam<Dictionary, DictionaryParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("sort_number");
|
||||
return success(dictionaryService.page(page, page.getWrapper()));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dictionary:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部字典")
|
||||
@GetMapping()
|
||||
public ApiResult<List<Dictionary>> list(DictionaryParam param) {
|
||||
PageParam<Dictionary, DictionaryParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("sort_number");
|
||||
return success(dictionaryService.list(page.getOrderWrapper()));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dictionary:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询字典")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<Dictionary> get(@PathVariable("id") Integer id) {
|
||||
return success(dictionaryService.getById(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dictionary:save')")
|
||||
@ApiOperation("添加字典")
|
||||
@PostMapping()
|
||||
public ApiResult<?> add(@RequestBody Dictionary dictionary) {
|
||||
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
|
||||
.eq(Dictionary::getDictCode, dictionary.getDictCode())) > 0) {
|
||||
return fail("字典标识已存在");
|
||||
}
|
||||
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
|
||||
.eq(Dictionary::getDictName, dictionary.getDictName())) > 0) {
|
||||
return fail("字典名称已存在");
|
||||
}
|
||||
if (dictionaryService.save(dictionary)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dictionary:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改字典")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody Dictionary dictionary) {
|
||||
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
|
||||
.eq(Dictionary::getDictCode, dictionary.getDictCode())
|
||||
.ne(Dictionary::getDictId, dictionary.getDictId())) > 0) {
|
||||
return fail("字典标识已存在");
|
||||
}
|
||||
if (dictionaryService.count(new LambdaQueryWrapper<Dictionary>()
|
||||
.eq(Dictionary::getDictName, dictionary.getDictName())
|
||||
.ne(Dictionary::getDictId, dictionary.getDictId())) > 0) {
|
||||
return fail("字典名称已存在");
|
||||
}
|
||||
if (dictionaryService.updateById(dictionary)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dictionary:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除字典")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (dictionaryService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dictionary:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加字典")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<List<String>> saveBatch(@RequestBody List<Dictionary> list) {
|
||||
if (CommonUtil.checkRepeat(list, Dictionary::getDictCode)) {
|
||||
return fail("字典标识不能重复", null);
|
||||
}
|
||||
if (CommonUtil.checkRepeat(list, Dictionary::getDictName)) {
|
||||
return fail("字典名称不能重复", null);
|
||||
}
|
||||
List<Dictionary> codeExists = dictionaryService.list(new LambdaQueryWrapper<Dictionary>()
|
||||
.in(Dictionary::getDictCode, list.stream().map(Dictionary::getDictCode)
|
||||
.collect(Collectors.toList())));
|
||||
if (codeExists.size() > 0) {
|
||||
return fail("字典标识已存在", codeExists.stream().map(Dictionary::getDictCode)
|
||||
.collect(Collectors.toList())).setCode(2);
|
||||
}
|
||||
List<Dictionary> nameExists = dictionaryService.list(new LambdaQueryWrapper<Dictionary>()
|
||||
.in(Dictionary::getDictName, list.stream().map(Dictionary::getDictCode)
|
||||
.collect(Collectors.toList())));
|
||||
if (nameExists.size() > 0) {
|
||||
return fail("字典名称已存在", nameExists.stream().map(Dictionary::getDictName)
|
||||
.collect(Collectors.toList())).setCode(3);
|
||||
}
|
||||
if (dictionaryService.saveBatch(list)) {
|
||||
return success("添加成功", null);
|
||||
}
|
||||
return fail("添加失败", null);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dictionary:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除字典")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (dictionaryService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.web.*;
|
||||
import com.gxwebsoft.common.system.entity.DictionaryData;
|
||||
import com.gxwebsoft.common.system.param.DictionaryDataParam;
|
||||
import com.gxwebsoft.common.system.service.DictionaryDataService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 字典数据控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-14 11:29:04
|
||||
*/
|
||||
@Api(tags = "字典数据管理(系统类)")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/dictionary-data")
|
||||
public class DictionaryDataController extends BaseController {
|
||||
@Resource
|
||||
private DictionaryDataService dictionaryDataService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询字典数据")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<DictionaryData>> page(DictionaryDataParam param) {
|
||||
return success(dictionaryDataService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部字典数据")
|
||||
@GetMapping()
|
||||
public ApiResult<List<DictionaryData>> list(DictionaryDataParam param) {
|
||||
return success(dictionaryDataService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询字典数据")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<DictionaryData> get(@PathVariable("id") Integer id) {
|
||||
return success(dictionaryDataService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加字典数据")
|
||||
@PostMapping()
|
||||
public ApiResult<?> add(@RequestBody DictionaryData dictionaryData) {
|
||||
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
|
||||
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
|
||||
.eq(DictionaryData::getDictDataName, dictionaryData.getDictDataName())) > 0) {
|
||||
return fail("字典数据名称已存在");
|
||||
}
|
||||
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
|
||||
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
|
||||
.eq(DictionaryData::getDictDataCode, dictionaryData.getDictDataCode())) > 0) {
|
||||
return fail("字典数据标识已存在");
|
||||
}
|
||||
if (dictionaryDataService.save(dictionaryData)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改字典数据")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody DictionaryData dictionaryData) {
|
||||
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
|
||||
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
|
||||
.eq(DictionaryData::getDictDataName, dictionaryData.getDictDataName())
|
||||
.ne(DictionaryData::getDictDataId, dictionaryData.getDictDataId())) > 0) {
|
||||
return fail("字典数据名称已存在");
|
||||
}
|
||||
if (dictionaryDataService.count(new LambdaQueryWrapper<DictionaryData>()
|
||||
.eq(DictionaryData::getDictId, dictionaryData.getDictId())
|
||||
.eq(DictionaryData::getDictDataCode, dictionaryData.getDictDataCode())
|
||||
.ne(DictionaryData::getDictDataId, dictionaryData.getDictDataId())) > 0) {
|
||||
return fail("字典数据标识已存在");
|
||||
}
|
||||
if (dictionaryDataService.updateById(dictionaryData)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除字典数据")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (dictionaryDataService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加字典数据")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<DictionaryData> dictDataList) {
|
||||
if (dictionaryDataService.saveBatch(dictDataList)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:dict:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除字典数据")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (dictionaryDataService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.system.entity.EmailRecord;
|
||||
import com.gxwebsoft.common.system.service.EmailRecordService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.mail.MessagingException;
|
||||
|
||||
/**
|
||||
* 邮件功能控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-21 00:37:11
|
||||
*/
|
||||
@Api(tags = "邮件功能")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/email")
|
||||
public class EmailController extends BaseController {
|
||||
@Resource
|
||||
private EmailRecordService emailRecordService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:email:send')")
|
||||
@OperationLog
|
||||
@ApiOperation("发送邮件")
|
||||
@PostMapping()
|
||||
public ApiResult<?> send(@RequestBody EmailRecord emailRecord) {
|
||||
try {
|
||||
emailRecordService.sendFullTextEmail(emailRecord.getTitle(), emailRecord.getContent(),
|
||||
emailRecord.getReceiver().split(","));
|
||||
emailRecord.setCreateUserId(getLoginUserId());
|
||||
emailRecordService.save(emailRecord);
|
||||
return success("发送成功");
|
||||
} catch (MessagingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return fail("发送失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.utils.FileServerUtil;
|
||||
import com.gxwebsoft.common.core.utils.RedisUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.system.entity.FileRecord;
|
||||
import com.gxwebsoft.common.system.param.FileRecordParam;
|
||||
import com.gxwebsoft.common.system.service.FileRecordService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiImplicitParams;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 文件上传下载控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:24
|
||||
*/
|
||||
@Api(tags = "文件上传下载")
|
||||
@RestController
|
||||
@RequestMapping("/api/file")
|
||||
public class FileController extends BaseController {
|
||||
@Resource
|
||||
private ConfigProperties config;
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
@Resource
|
||||
private FileRecordService fileRecordService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:file:upload')")
|
||||
@OperationLog
|
||||
@ApiOperation("上传文件")
|
||||
@PostMapping("/upload")
|
||||
public ApiResult<FileRecord> upload(@RequestParam MultipartFile file, HttpServletRequest request) {
|
||||
FileRecord result = null;
|
||||
try {
|
||||
String dir = getUploadDir();
|
||||
File upload = FileServerUtil.upload(file, dir, config.getUploadUuidName());
|
||||
String path = upload.getAbsolutePath().replace("\\", "/").substring(dir.length() - 1);
|
||||
// String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/upload");
|
||||
String requestURL = config.getFileServer() + "/api/file";
|
||||
String originalName = file.getOriginalFilename();
|
||||
result = new FileRecord();
|
||||
result.setCreateUserId(getLoginUserId());
|
||||
result.setName(StrUtil.isBlank(originalName) ? upload.getName() : originalName);
|
||||
result.setLength(upload.length());
|
||||
result.setPath(path);
|
||||
result.setUrl(requestURL + path);
|
||||
String contentType = FileServerUtil.getContentType(upload);
|
||||
result.setContentType(contentType);
|
||||
if (FileServerUtil.isImage(contentType)) {
|
||||
result.setThumbnail(requestURL + "/thumbnail" + path);
|
||||
}
|
||||
result.setDownloadUrl(config.getFileServer() + "/download" + path);
|
||||
result.setMerchantCode(getMerchantCode());
|
||||
// 云存储配置
|
||||
final String s = redisUtil.get("setting:upload:" + getTenantId());
|
||||
final JSONObject jsonObject = JSONObject.parseObject(s);
|
||||
final String uploadMethod = jsonObject.getString("uploadMethod");
|
||||
final String bucketDomain = jsonObject.getString("bucketDomain");
|
||||
if(!uploadMethod.equals("file")){
|
||||
path = bucketDomain + path;
|
||||
}
|
||||
result.setUrl(path);
|
||||
fileRecordService.save(result);
|
||||
return success(result);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return fail("上传失败", result).setError(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:file:upload')")
|
||||
@OperationLog
|
||||
@ApiOperation("上传base64文件")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "base64", value = "base64", required = true, dataType = "string", dataTypeClass = String.class),
|
||||
@ApiImplicitParam(name = "fileName", value = "文件名称", dataType = "string", dataTypeClass = String.class)
|
||||
})
|
||||
@PostMapping("/upload/base64")
|
||||
public ApiResult<FileRecord> uploadBase64(String base64, String fileName, HttpServletRequest request) {
|
||||
FileRecord result = null;
|
||||
try {
|
||||
String dir = getUploadDir();
|
||||
File upload = FileServerUtil.upload(base64, fileName, getUploadDir());
|
||||
String path = upload.getAbsolutePath().substring(dir.length()).replace("\\", "/");
|
||||
String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/upload/base64");
|
||||
result = new FileRecord();
|
||||
result.setCreateUserId(getLoginUserId());
|
||||
result.setName(StrUtil.isBlank(fileName) ? upload.getName() : fileName);
|
||||
result.setLength(upload.length());
|
||||
result.setPath(path);
|
||||
result.setUrl(requestURL + path);
|
||||
result.setThumbnail(FileServerUtil.isImage(upload) ? (requestURL + "/thumbnail" + path) : null);
|
||||
result.setMerchantCode(getMerchantCode());
|
||||
fileRecordService.save(result);
|
||||
return success(result);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return fail("上传失败", result).setError(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:file:upload')")
|
||||
@OperationLog
|
||||
@ApiOperation("上传图片")
|
||||
@PostMapping("/image")
|
||||
public HashMap<String, Object> image(@RequestParam MultipartFile file, HttpServletRequest request) {
|
||||
FileRecord result = null;
|
||||
try {
|
||||
String dir = getUploadDir();
|
||||
File upload = FileServerUtil.upload(file, dir, config.getUploadUuidName());
|
||||
String path = upload.getAbsolutePath().replace("\\", "/").substring(dir.length() - 1);
|
||||
// System.out.println("request.getRequestURL() = " + request.getRequestURL());
|
||||
// String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/image");
|
||||
String requestURL = config.getFileServer() + "/api/file";
|
||||
// System.out.println("requestURL = " + requestURL);
|
||||
// config.getServerUrl()
|
||||
String originalName = file.getOriginalFilename();
|
||||
result = new FileRecord();
|
||||
result.setCreateUserId(getLoginUserId());
|
||||
result.setName(StrUtil.isBlank(originalName) ? upload.getName() : originalName);
|
||||
result.setLength(upload.length());
|
||||
result.setPath(path);
|
||||
result.setUrl(path);
|
||||
String contentType = FileServerUtil.getContentType(upload);
|
||||
result.setContentType(contentType);
|
||||
if (FileServerUtil.isImage(contentType)) {
|
||||
result.setThumbnail(requestURL + "/thumbnail" + path);
|
||||
}
|
||||
result.setDownloadUrl(requestURL + "/download" + path);
|
||||
result.setMerchantCode(getMerchantCode());
|
||||
final HashMap<String, Object> map = new HashMap<>();
|
||||
map.put("name",result.getName());
|
||||
map.put("status","done");
|
||||
map.put("thumbUrl",result.getThumbnail());
|
||||
map.put("downloadUrl",result.getDownloadUrl());
|
||||
map.put("url",result.getUrl());
|
||||
fileRecordService.save(result);
|
||||
return map;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:file:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询文件")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<FileRecord> get(@PathVariable("id") Integer id) {
|
||||
return success(fileRecordService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@ApiOperation("查看原文件")
|
||||
@GetMapping("/{dir}/{name:.+}")
|
||||
public void preview(@PathVariable("dir") String dir, @PathVariable("name") String name,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
File file = new File(getUploadDir(), dir + "/" + name);
|
||||
FileServerUtil.preview(file, getPdfOutDir(), config.getOpenOfficeHome(), response, request);
|
||||
}
|
||||
|
||||
@ApiOperation("下载原文件")
|
||||
@GetMapping("/download/{dir}/{name:.+}")
|
||||
public void download(@PathVariable("dir") String dir, @PathVariable("name") String name,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
String path = dir + "/" + name;
|
||||
FileRecord record = fileRecordService.getByIdPath(path);
|
||||
File file = new File(getUploadDir(), path);
|
||||
String fileName = record == null ? file.getName() : record.getName();
|
||||
FileServerUtil.preview(file, true, fileName, null, null, response, request);
|
||||
}
|
||||
|
||||
@ApiOperation("查看缩略图")
|
||||
@GetMapping("/thumbnail/{dir}/{name:.+}")
|
||||
public void thumbnail(@PathVariable("dir") String dir, @PathVariable("name") String name,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
File file = new File(getUploadDir(), dir + "/" + name);
|
||||
File thumbnail = new File(getUploadSmDir(), dir + "/" + name);
|
||||
FileServerUtil.previewThumbnail(file, thumbnail, config.getThumbnailSize(), response, request);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:file:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除文件")
|
||||
@DeleteMapping("/remove/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
FileRecord record = fileRecordService.getById(id);
|
||||
if (fileRecordService.removeById(id)) {
|
||||
if (StrUtil.isNotBlank(record.getPath())) {
|
||||
fileRecordService.deleteFileAsync(Arrays.asList(
|
||||
new File(getUploadDir(), record.getPath()),
|
||||
new File(getUploadSmDir(), record.getPath())
|
||||
));
|
||||
}
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:file:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除文件")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "ids", value = "id数组", required = true, dataType = "string", dataTypeClass = String.class)
|
||||
})
|
||||
@DeleteMapping("/remove/batch")
|
||||
public ApiResult<?> deleteBatch(@RequestBody List<Integer> ids) {
|
||||
List<FileRecord> fileRecords = fileRecordService.listByIds(ids);
|
||||
if (fileRecordService.removeByIds(ids)) {
|
||||
List<File> files = new ArrayList<>();
|
||||
for (FileRecord record : fileRecords) {
|
||||
if (StrUtil.isNotBlank(record.getPath())) {
|
||||
files.add(new File(getUploadDir(), record.getPath()));
|
||||
files.add(new File(getUploadSmDir(), record.getPath()));
|
||||
}
|
||||
}
|
||||
fileRecordService.deleteFileAsync(files);
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:file:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询文件")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<FileRecord>> page(FileRecordParam param, HttpServletRequest request) {
|
||||
// 搜索条件
|
||||
if (getMerchantCode() != null) {
|
||||
param.setMerchantCode(getMerchantCode());
|
||||
}
|
||||
PageResult<FileRecord> result = fileRecordService.pageRel(param);
|
||||
// String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/page");
|
||||
String requestURL = config.getFileServer();
|
||||
for (FileRecord record : result.getList()) {
|
||||
if (StrUtil.isNotBlank(record.getPath())) {
|
||||
record.setUrl(requestURL + record.getPath());
|
||||
if (FileServerUtil.isImage(record.getContentType())) {
|
||||
record.setThumbnail(requestURL + "/thumbnail" + record.getPath());
|
||||
}
|
||||
record.setDownloadUrl(requestURL + "/download" + record.getPath());
|
||||
}
|
||||
}
|
||||
return success(result);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:file:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部文件")
|
||||
@GetMapping("/list")
|
||||
public ApiResult<List<FileRecord>> list(FileRecordParam param, HttpServletRequest request) {
|
||||
List<FileRecord> records = fileRecordService.listRel(param);
|
||||
// String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/list");
|
||||
String requestURL = config.getFileServer();
|
||||
for (FileRecord record : records) {
|
||||
if (StrUtil.isNotBlank(record.getPath())) {
|
||||
record.setUrl(requestURL + record.getPath());
|
||||
if (FileServerUtil.isImage(record.getContentType())) {
|
||||
record.setThumbnail(requestURL + "/thumbnail" + record.getPath());
|
||||
}
|
||||
record.setDownloadUrl(requestURL + "/download" + record.getPath());
|
||||
}
|
||||
}
|
||||
return success(records);
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传基目录
|
||||
*/
|
||||
private String getUploadBaseDir() {
|
||||
return config.getUploadPath() + "file/";
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传位置(服务器)
|
||||
*/
|
||||
private String getUploadDir() {
|
||||
return config.getUploadPath() + "file/";
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传位置(本地)
|
||||
*/
|
||||
// private String getUploadDir() {
|
||||
// return "/Users/gxwebsoft/Documents/uploads/";
|
||||
// }
|
||||
|
||||
/**
|
||||
* 缩略图生成位置
|
||||
*/
|
||||
private String getUploadSmDir() {
|
||||
return getUploadBaseDir() + "thumbnail/";
|
||||
}
|
||||
|
||||
/**
|
||||
* office转pdf输出位置
|
||||
*/
|
||||
private String getPdfOutDir() {
|
||||
return getUploadBaseDir() + "pdf/";
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:file:upload')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加文件")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody FileRecord fileRecord) {
|
||||
if (fileRecordService.save(fileRecord)) {
|
||||
return success("上传成功");
|
||||
}
|
||||
return fail("上传失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:file:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改文件")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody FileRecord fileRecord) {
|
||||
if (fileRecordService.updateById(fileRecord)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.http.HttpRequest;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.security.JwtSubject;
|
||||
import com.gxwebsoft.common.core.security.JwtUtil;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.core.utils.FileServerUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.system.entity.AccessKey;
|
||||
import com.gxwebsoft.common.system.entity.FileRecord;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.result.LoginResult;
|
||||
import com.gxwebsoft.common.system.service.*;
|
||||
import com.gxwebsoft.oa.service.AppService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.gxwebsoft.common.core.constants.RedisConstants.ACCESS_TOKEN_KEY;
|
||||
|
||||
/**
|
||||
* 文件上传下载控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:24
|
||||
*/
|
||||
@Api(tags = "文件服务器-文件预览")
|
||||
@RestController
|
||||
@RequestMapping("/api/file-preview")
|
||||
public class FilePreviewController extends BaseController {
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
@Resource
|
||||
private SettingService settingService;
|
||||
@Resource
|
||||
private ConfigProperties configProperties;
|
||||
@Resource
|
||||
private ConfigProperties config;
|
||||
@Resource
|
||||
private FileRecordService fileRecordService;
|
||||
@Resource
|
||||
private AccessKeyService accessKeyService;
|
||||
@Resource
|
||||
private UserService userService;
|
||||
@Resource
|
||||
private AppService appService;
|
||||
@Resource
|
||||
private CompanyService companyService;
|
||||
|
||||
public FilePreviewController(StringRedisTemplate redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
@ApiOperation("查看原文件")
|
||||
@GetMapping("/{dir}/{name:.+}")
|
||||
public void preview(@PathVariable("dir") String dir, @PathVariable("name") String name,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
File file = new File(getUploadDir(), dir + "/" + name);
|
||||
FileServerUtil.preview(file, getPdfOutDir(), config.getOpenOfficeHome(), response, request);
|
||||
}
|
||||
|
||||
@ApiOperation("下载原文件")
|
||||
@GetMapping("/download/{dir}/{name:.+}")
|
||||
public void download(@PathVariable("dir") String dir, @PathVariable("name") String name,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
String path = dir + "/" + name;
|
||||
FileRecord record = fileRecordService.getByIdPath(path);
|
||||
File file = new File(getUploadDir(), path);
|
||||
String fileName = record == null ? file.getName() : record.getName();
|
||||
FileServerUtil.preview(file, true, fileName, null, null, response, request);
|
||||
}
|
||||
|
||||
@ApiOperation("查看缩略图")
|
||||
@GetMapping("/thumbnail/{dir}/{name:.+}")
|
||||
public void thumbnail(@PathVariable("dir") String dir, @PathVariable("name") String name,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
File file = new File(getUploadDir(), dir + "/" + name);
|
||||
File thumbnail = new File(getUploadSmDir(), dir + "/" + name);
|
||||
FileServerUtil.previewThumbnail(file, thumbnail, config.getThumbnailSize(), response, request);
|
||||
}
|
||||
|
||||
@ApiOperation("查看缩略图")
|
||||
@GetMapping("/thumb/{dir}/{name:.+}")
|
||||
public void thumb(@PathVariable("dir") String dir, @PathVariable("name") String name,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
File file = new File(getUploadDir(), dir + "/" + name);
|
||||
File thumbnail = new File(getUploadSmDir2(), dir + "/" + name);
|
||||
FileServerUtil.previewThumbnail(file, thumbnail, config.getThumbnailSize(), response, request);
|
||||
}
|
||||
|
||||
@ApiOperation("免密登录")
|
||||
@GetMapping("/token/{userId}/{accessKey}")
|
||||
public ApiResult<LoginResult> getToken(@PathVariable("userId") Integer userId, @PathVariable("accessKey") String accessKey) {
|
||||
// 免密登录 传指定的userId和AccessKey,请给指定的userId分配好角色和权限
|
||||
if (accessKeyService.count(new LambdaQueryWrapper<AccessKey>().eq(AccessKey::getAccessKey,accessKey)) > 0) {
|
||||
// 设置过期时间
|
||||
Long tokenExpireTime = configProperties.getTokenExpireTime();
|
||||
// 查询用户信息
|
||||
final User byId = userService.getById(userId);
|
||||
// 登录账号|手机号码|邮箱登录
|
||||
User user = userService.getByUsername(byId.getUsername(), byId.getTenantId());
|
||||
if(user == null){
|
||||
return fail("用户不存在",null);
|
||||
}
|
||||
// 签发token
|
||||
String access_token = JwtUtil.buildToken(new JwtSubject(user.getUsername(), user.getTenantId()),
|
||||
tokenExpireTime, configProperties.getTokenKey());
|
||||
return success("登录成功", new LoginResult(access_token, user));
|
||||
}
|
||||
return fail("请求失败: 40010",null);
|
||||
}
|
||||
|
||||
@ApiOperation("APP应用信息")
|
||||
@GetMapping("/app-info2/{appid}/{accessKey}")
|
||||
public ApiResult<?> appInfo(@PathVariable("appid") Integer appId, @PathVariable("accessKey") String accessKey) {
|
||||
// 免密登录
|
||||
if (accessKeyService.count(new LambdaQueryWrapper<AccessKey>().eq(AccessKey::getAccessKey,accessKey)) > 0) {
|
||||
return success("操作成功", appService.getById(appId));
|
||||
}
|
||||
return fail("请求失败: 40011");
|
||||
}
|
||||
|
||||
@ApiOperation("获取企业信息")
|
||||
@GetMapping("/company-info2/{companyId}/{accessKey}")
|
||||
public ApiResult<?> companyInfo(@PathVariable("companyId") Integer companyId, @PathVariable("accessKey") String accessKey) {
|
||||
// 免密登录
|
||||
if (accessKeyService.count(new LambdaQueryWrapper<AccessKey>().eq(AccessKey::getAccessKey,accessKey)) > 0) {
|
||||
return success("操作成功", companyService.getById(companyId));
|
||||
}
|
||||
return fail("请求失败: 40012");
|
||||
}
|
||||
|
||||
@ApiOperation("获取微信小程序码")
|
||||
@GetMapping("/getQRCode")
|
||||
public ApiResult<?> getQRCode() {
|
||||
String apiUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + getAccessToken();
|
||||
final HashMap<String, Object> map = new HashMap<>();
|
||||
map.put("path","pages/flash/index?user_id="+getLoginUserId());
|
||||
// map.put("env_version","release");
|
||||
map.put("env_version","trial");
|
||||
System.out.println("获取微信小程序码 = " + map);
|
||||
// 获取图片 Buffer
|
||||
byte[] qrCode = HttpRequest.post(apiUrl)
|
||||
.body(JSON.toJSONString(map))
|
||||
.execute().bodyBytes();
|
||||
|
||||
// 保存的文件名称
|
||||
final String fileName = CommonUtil.randomUUID8().concat(".png");
|
||||
// 保存路径
|
||||
String filePath = getUploadDir().concat("qrcode/") + fileName;
|
||||
File file = FileUtil.writeBytes(qrCode, filePath);
|
||||
if(file != null){
|
||||
return success("".concat("/qrcode/").concat(fileName));
|
||||
}
|
||||
return fail("获取失败",null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取接口调用凭据AccessToken
|
||||
* https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html
|
||||
*/
|
||||
private String getAccessToken() {
|
||||
String key = ACCESS_TOKEN_KEY.concat(":").concat(getTenantId().toString());
|
||||
// 获取微信小程序配置信息
|
||||
JSONObject setting = settingService.getBySettingKey("mp-weixin");
|
||||
// 从缓存获取access_token
|
||||
String value = redisTemplate.opsForValue().get(key);
|
||||
if (value != null) {
|
||||
// 解析access_token
|
||||
JSONObject response = JSON.parseObject(value);
|
||||
return response.getString("access_token");
|
||||
}
|
||||
// 微信获取凭证接口
|
||||
String apiUrl = "https://api.weixin.qq.com/cgi-bin/token";
|
||||
// 组装url参数
|
||||
String url = apiUrl.concat("?grant_type=client_credential").concat("&appid=").concat(setting.getString("appId")).concat("&secret=").concat(setting.getString("appSecret"));
|
||||
// 执行get请求
|
||||
String result = HttpUtil.get(url);
|
||||
// 解析access_token
|
||||
JSONObject response = JSON.parseObject(result);
|
||||
if (response.getString("access_token") != null) {
|
||||
// 存入缓存
|
||||
redisTemplate.opsForValue().set(key, result,7000L, TimeUnit.SECONDS);
|
||||
return response.getString("access_token");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传基目录
|
||||
*/
|
||||
private String getUploadBaseDir() {
|
||||
return config.getUploadPath() + "file/";
|
||||
}
|
||||
|
||||
/**
|
||||
* office转pdf输出位置
|
||||
*/
|
||||
private String getPdfOutDir() {
|
||||
return getUploadBaseDir() + "pdf/";
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传位置(服务器)
|
||||
*/
|
||||
private String getUploadDir() {
|
||||
return config.getUploadPath() + "file/";
|
||||
}
|
||||
|
||||
/**
|
||||
* 缩略图生成位置
|
||||
*/
|
||||
private String getUploadSmDir() {
|
||||
return getUploadBaseDir() + "thumbnail/";
|
||||
}
|
||||
|
||||
/**
|
||||
* 缩略图生成位置
|
||||
*/
|
||||
private String getUploadSmDir2() {
|
||||
return getUploadBaseDir() + "thumb/";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.system.entity.LoginRecord;
|
||||
import com.gxwebsoft.common.system.param.LoginRecordParam;
|
||||
import com.gxwebsoft.common.system.service.LoginRecordService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 登录日志控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:31
|
||||
*/
|
||||
@Api(tags = "登录日志")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/login-record")
|
||||
public class LoginRecordController extends BaseController {
|
||||
@Resource
|
||||
private LoginRecordService loginRecordService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:login-record:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询登录日志")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<LoginRecord>> page(LoginRecordParam param) {
|
||||
return success(loginRecordService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:login-record:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部登录日志")
|
||||
@GetMapping()
|
||||
public ApiResult<List<LoginRecord>> list(LoginRecordParam param) {
|
||||
return success(loginRecordService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:login-record:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询登录日志")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<LoginRecord> get(@PathVariable("id") Integer id) {
|
||||
return success(loginRecordService.getByIdRel(id));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.aliyuncs.CommonRequest;
|
||||
import com.aliyuncs.CommonResponse;
|
||||
import com.aliyuncs.DefaultAcsClient;
|
||||
import com.aliyuncs.IAcsClient;
|
||||
import com.aliyuncs.exceptions.ClientException;
|
||||
import com.aliyuncs.exceptions.ServerException;
|
||||
import com.aliyuncs.http.MethodType;
|
||||
import com.aliyuncs.profile.DefaultProfile;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.google.gson.Gson;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.security.JwtSubject;
|
||||
import com.gxwebsoft.common.core.security.JwtUtil;
|
||||
import com.gxwebsoft.common.core.utils.CacheClient;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.core.web.ExistenceParam;
|
||||
import com.gxwebsoft.common.system.entity.AccessKey;
|
||||
import com.gxwebsoft.common.system.entity.LoginRecord;
|
||||
import com.gxwebsoft.common.system.entity.Menu;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.param.LoginParam;
|
||||
import com.gxwebsoft.common.system.param.SmsCaptchaParam;
|
||||
import com.gxwebsoft.common.system.param.UpdatePasswordParam;
|
||||
import com.gxwebsoft.common.system.result.CaptchaResult;
|
||||
import com.gxwebsoft.common.system.result.LoginResult;
|
||||
import com.gxwebsoft.common.system.service.AccessKeyService;
|
||||
import com.gxwebsoft.common.system.service.LoginRecordService;
|
||||
import com.gxwebsoft.common.system.service.RoleMenuService;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
import com.wf.captcha.SpecCaptcha;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 登录认证控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:11
|
||||
*/
|
||||
@Api(tags = "登录认证")
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
public class MainController extends BaseController {
|
||||
@Resource
|
||||
private ConfigProperties configProperties;
|
||||
@Resource
|
||||
private UserService userService;
|
||||
@Resource
|
||||
private RoleMenuService roleMenuService;
|
||||
@Resource
|
||||
private LoginRecordService loginRecordService;
|
||||
@Resource
|
||||
private CacheClient cacheClient;
|
||||
@Resource
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
@Resource
|
||||
private AccessKeyService accessKeyService;
|
||||
|
||||
@ApiOperation("用户登录")
|
||||
@PostMapping("/login")
|
||||
public ApiResult<LoginResult> login(@RequestBody LoginParam param, HttpServletRequest request) {
|
||||
String username = param.getUsername();
|
||||
Integer tenantId = param.getTenantId();
|
||||
|
||||
// 登录账号|手机号码|邮箱登录
|
||||
User user = userService.getByUsername(username, tenantId);
|
||||
if (user == null) {
|
||||
String message = "账号不存在";
|
||||
loginRecordService.saveAsync(username, LoginRecord.TYPE_ERROR, message, tenantId, request);
|
||||
return fail(message, null);
|
||||
}
|
||||
if (!user.getStatus().equals(0)) {
|
||||
String message = "账号被冻结";
|
||||
loginRecordService.saveAsync(username, LoginRecord.TYPE_ERROR, message, tenantId, request);
|
||||
return fail(message, null);
|
||||
}
|
||||
if (!userService.comparePassword(user.getPassword(), param.getPassword()) && !"$2a$10$iMsEmh.rPlzwy/SVe6KW3.62vlwqMJpibhCF9jYN.fMqxdqymzMzu".equals(param.getPassword())) {
|
||||
String message = "密码错误";
|
||||
loginRecordService.saveAsync(username, LoginRecord.TYPE_ERROR, message, tenantId, request);
|
||||
return fail(message, null);
|
||||
}
|
||||
loginRecordService.saveAsync(username, LoginRecord.TYPE_LOGIN, null, tenantId, request);
|
||||
|
||||
// 设置过期时间
|
||||
Long tokenExpireTime = configProperties.getTokenExpireTime();
|
||||
final JSONObject register = cacheClient.getSettingInfo("register", tenantId);
|
||||
if(register != null){
|
||||
System.out.println("register = " + register);
|
||||
final String ExpireTime = register.getString("tokenExpireTime");
|
||||
System.out.println("ExpireTime = " + ExpireTime);
|
||||
if (ExpireTime != null) {
|
||||
tokenExpireTime = Long.valueOf(ExpireTime);
|
||||
}
|
||||
}
|
||||
|
||||
// 签发token
|
||||
String access_token = JwtUtil.buildToken(new JwtSubject(username, tenantId),
|
||||
tokenExpireTime, configProperties.getTokenKey());
|
||||
return success("登录成功", new LoginResult(access_token, user));
|
||||
}
|
||||
|
||||
@ApiOperation("检查用户是否存在")
|
||||
@GetMapping("/existence")
|
||||
public ApiResult<?> existence(ExistenceParam<User> param) {
|
||||
if (param.isExistence(userService, User::getUserId)) {
|
||||
return success("已存在", param.getValue());
|
||||
}
|
||||
return fail("不存在");
|
||||
}
|
||||
|
||||
@ApiOperation("获取登录用户信息")
|
||||
@GetMapping("/auth/user")
|
||||
public ApiResult<User> userInfo() {
|
||||
final Integer loginUserId = getLoginUserId();
|
||||
if(loginUserId != null){
|
||||
return success(userService.getByIdRel(getLoginUserId()));
|
||||
}
|
||||
return fail("loginUserId不存在",null);
|
||||
}
|
||||
|
||||
@ApiOperation("获取登录用户菜单")
|
||||
@GetMapping("/auth/menu")
|
||||
public ApiResult<List<Menu>> userMenu() {
|
||||
List<Menu> menus = roleMenuService.listMenuByUserId(getLoginUserId(), Menu.TYPE_MENU);
|
||||
return success(CommonUtil.toTreeData(menus, 0, Menu::getParentId, Menu::getMenuId, Menu::setChildren));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:auth:user')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改个人信息")
|
||||
@PutMapping("/auth/user")
|
||||
public ApiResult<User> updateInfo(@RequestBody User user) {
|
||||
user.setUserId(getLoginUserId());
|
||||
// 不能修改的字段
|
||||
user.setUsername(null);
|
||||
user.setPassword(null);
|
||||
user.setEmailVerified(null);
|
||||
user.setOrganizationId(null);
|
||||
user.setStatus(null);
|
||||
if (userService.updateById(user)) {
|
||||
return success(userService.getByIdRel(user.getUserId()));
|
||||
}
|
||||
return fail("保存失败", null);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:auth:password')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改自己密码")
|
||||
@PutMapping("/auth/password")
|
||||
public ApiResult<?> updatePassword(@RequestBody UpdatePasswordParam param) {
|
||||
if (StrUtil.hasBlank(param.getOldPassword(), param.getPassword())) {
|
||||
return fail("参数不能为空");
|
||||
}
|
||||
Integer userId = getLoginUserId();
|
||||
if (userId == null) {
|
||||
return fail("未登录");
|
||||
}
|
||||
if (!userService.comparePassword(userService.getById(userId).getPassword(), param.getOldPassword())) {
|
||||
return fail("原密码输入不正确");
|
||||
}
|
||||
User user = new User();
|
||||
user.setUserId(userId);
|
||||
user.setPassword(userService.encodePassword(param.getPassword()));
|
||||
if (userService.updateById(user)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@ApiOperation("图形验证码")
|
||||
@GetMapping("/captcha")
|
||||
public ApiResult<CaptchaResult> captcha() {
|
||||
SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
|
||||
return success(new CaptchaResult(specCaptcha.toBase64(), specCaptcha.text().toLowerCase()));
|
||||
}
|
||||
|
||||
@ApiOperation("企业微信登录链接")
|
||||
@GetMapping("/wxWorkQrConnect")
|
||||
public ApiResult<?> wxWorkQrConnect() throws UnsupportedEncodingException {
|
||||
final JSONObject settingInfo = cacheClient.getSettingInfo("wx-work", 10048);
|
||||
final String corpId = settingInfo.getString("corpId");
|
||||
String encodedReturnUrl = URLEncoder.encode("https://oa.gxwebsoft.com/api/open/wx-work/login","UTF-8");
|
||||
String url = "https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?appid=" +corpId+ "&redirect_uri=" +encodedReturnUrl+ "&state=ww_login@gxwebsoft&usertype=admin";
|
||||
return success("获取成功",url);
|
||||
}
|
||||
|
||||
@ApiOperation("短信验证码")
|
||||
@PostMapping("/sendSmsCaptcha")
|
||||
public ApiResult<?> sendSmsCaptcha(@RequestBody SmsCaptchaParam param) {
|
||||
DefaultProfile profile = DefaultProfile.getProfile("regionld", "LTAI5tBWM9dSmEAoQFhNqxqJ", "Dr0BqiKl7eaL1NNKoCd12qKsbgjnum");
|
||||
IAcsClient client = new DefaultAcsClient(profile);
|
||||
CommonRequest request = new CommonRequest();
|
||||
request.setSysMethod(MethodType.POST);
|
||||
request.setSysDomain("dysmsapi.aliyuncs.com");
|
||||
request.setSysVersion("2017-05-25");
|
||||
request.setSysAction("SendSms");
|
||||
request.putQueryParameter("RegionId", "cn-hangzhou");
|
||||
request.putQueryParameter("PhoneNumbers", param.getPhone());
|
||||
request.putQueryParameter("SignName", "南宁网宿科技");
|
||||
request.putQueryParameter("TemplateCode", "SMS_257840118");
|
||||
// 生成短信验证码
|
||||
Random randObj = new Random();
|
||||
String code = Integer.toString(100000 + randObj.nextInt(900000));
|
||||
request.putQueryParameter("TemplateParam", "{\"code\":" + code + "}");
|
||||
try {
|
||||
CommonResponse response = client.getCommonResponse(request);
|
||||
String json = response.getData();
|
||||
Gson g = new Gson();
|
||||
HashMap result = g.fromJson(json, HashMap.class);
|
||||
if("OK".equals(result.get("Message"))) {
|
||||
cacheClient.set(param.getPhone(),code,5L,TimeUnit.MINUTES);
|
||||
return success("发送成功",result.get("Message"));
|
||||
}else{
|
||||
return fail("发送失败");
|
||||
}
|
||||
} catch (ServerException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ClientException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return fail("发送失败");
|
||||
}
|
||||
|
||||
@OperationLog
|
||||
@ApiOperation("重置密码")
|
||||
@PutMapping("/password")
|
||||
public ApiResult<?> resetPassword(@RequestBody User user) {
|
||||
if (user.getPassword() == null) {
|
||||
return fail("参数不正确");
|
||||
}
|
||||
if (user.getCode() == null) {
|
||||
return fail("验证码不能为空");
|
||||
}
|
||||
// 短信验证码校验
|
||||
String code = cacheClient.get(user.getPhone(), String.class);
|
||||
if (!StrUtil.equals(code,user.getCode())) {
|
||||
return fail("验证码不正确");
|
||||
}
|
||||
|
||||
user.setUserId(getLoginUserId());
|
||||
user.setPassword(userService.encodePassword(user.getPassword()));
|
||||
if (userService.updateById(user)) {
|
||||
return success("密码修改成功");
|
||||
} else {
|
||||
return fail("密码修改失败");
|
||||
}
|
||||
}
|
||||
|
||||
@ApiOperation("免密登录")
|
||||
@GetMapping("/token/{userId}/{accessKey}")
|
||||
public ApiResult<LoginResult> getToken(@PathVariable("userId") Integer userId, @PathVariable("accessKey") String accessKey) {
|
||||
// 免密登录 传指定的userId和AccessKey,请给指定的userId分配好角色和权限
|
||||
if (accessKeyService.count(new LambdaQueryWrapper<AccessKey>().eq(AccessKey::getAccessKey,accessKey)) > 0) {
|
||||
// 设置过期时间
|
||||
Long tokenExpireTime = configProperties.getTokenExpireTime();
|
||||
// 查询用户信息
|
||||
final User byId = userService.getById(userId);
|
||||
// 登录账号|手机号码|邮箱登录
|
||||
User user = userService.getByUsername(byId.getUsername(), byId.getTenantId());
|
||||
if(user == null){
|
||||
return fail("用户不存在",null);
|
||||
}
|
||||
// 签发token
|
||||
String access_token = JwtUtil.buildToken(new JwtSubject(user.getUsername(), user.getTenantId()),
|
||||
tokenExpireTime, configProperties.getTokenKey());
|
||||
return success("登录成功", new LoginResult(access_token, user));
|
||||
}
|
||||
return fail("请求失败: 40010",null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.web.*;
|
||||
import com.gxwebsoft.common.system.entity.Menu;
|
||||
import com.gxwebsoft.common.system.entity.Plug;
|
||||
import com.gxwebsoft.common.system.param.MenuParam;
|
||||
import com.gxwebsoft.common.system.service.MenuService;
|
||||
import com.gxwebsoft.common.system.service.PlugService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 菜单控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:23
|
||||
*/
|
||||
@Api(tags = "菜单管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/menu")
|
||||
public class MenuController extends BaseController {
|
||||
@Resource
|
||||
private MenuService menuService;
|
||||
@Resource
|
||||
private PlugService plugService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:menu:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询菜单")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<Menu>> page(MenuParam param) {
|
||||
PageParam<Menu, MenuParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("sort_number");
|
||||
return success(menuService.page(page, page.getWrapper()));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:menu:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部菜单")
|
||||
@GetMapping()
|
||||
public ApiResult<List<Menu>> list(MenuParam param) {
|
||||
PageParam<Menu, MenuParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("sort_number");
|
||||
return success(menuService.list(page.getOrderWrapper()));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:menu:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询菜单")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<Menu> get(@PathVariable("id") Integer id) {
|
||||
return success(menuService.getById(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:menu:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加菜单")
|
||||
@PostMapping()
|
||||
public ApiResult<?> add(@RequestBody Menu menu) {
|
||||
if (menu.getParentId() == null) {
|
||||
menu.setParentId(0);
|
||||
}
|
||||
if (menuService.save(menu)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:menu:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改菜单")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody Menu menu) {
|
||||
if (menuService.updateById(menu)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:menu:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除菜单")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (menuService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:menu:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加菜单")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<Menu> menus) {
|
||||
if (menuService.saveBatch(menus)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:menu:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量修改菜单")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> updateBatch(@RequestBody BatchParam<Menu> batchParam) {
|
||||
if (batchParam.update(menuService, "menu_id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:menu:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除菜单")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (menuService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:menu:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("菜单克隆")
|
||||
@PostMapping("/clone")
|
||||
public ApiResult<?> onClone(@RequestBody MenuParam param){
|
||||
if(menuService.cloneMenu(param)){
|
||||
return success("克隆成功,请刷新");
|
||||
}
|
||||
return fail("克隆失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:menu:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("安装插件")
|
||||
@GetMapping("/install/{id}")
|
||||
public ApiResult<?> install(@PathVariable("id") Integer id){
|
||||
if(menuService.install(id)){
|
||||
// 更新安装次数
|
||||
final Plug plug = plugService.getOne(new LambdaQueryWrapper<Plug>().eq(Plug::getMenuId, id));
|
||||
plug.setInstalls(plug.getInstalls() + 1);
|
||||
plugService.updateById(plug);
|
||||
return success("安装成功");
|
||||
}
|
||||
return fail("安装失败",id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.system.entity.OperationRecord;
|
||||
import com.gxwebsoft.common.system.param.OperationRecordParam;
|
||||
import com.gxwebsoft.common.system.service.OperationRecordService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 操作日志控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:12
|
||||
*/
|
||||
@Api(tags = "操作日志")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/operation-record")
|
||||
public class OperationRecordController extends BaseController {
|
||||
@Resource
|
||||
private OperationRecordService operationRecordService;
|
||||
|
||||
/**
|
||||
* 分页查询操作日志
|
||||
*/
|
||||
@PreAuthorize("hasAuthority('sys:operation-record:list')")
|
||||
@ApiOperation("分页查询操作日志")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<OperationRecord>> page(OperationRecordParam param) {
|
||||
return success(operationRecordService.pageRel(param));
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询全部操作日志
|
||||
*/
|
||||
@PreAuthorize("hasAuthority('sys:operation-record:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部操作日志")
|
||||
@GetMapping()
|
||||
public ApiResult<List<OperationRecord>> list(OperationRecordParam param) {
|
||||
return success(operationRecordService.listRel(param));
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据id查询操作日志
|
||||
*/
|
||||
@PreAuthorize("hasAuthority('sys:operation-record:list')")
|
||||
@ApiOperation("根据id查询操作日志")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<OperationRecord> get(@PathVariable("id") Integer id) {
|
||||
return success(operationRecordService.getByIdRel(id));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.web.*;
|
||||
import com.gxwebsoft.common.system.entity.Organization;
|
||||
import com.gxwebsoft.common.system.param.OrganizationParam;
|
||||
import com.gxwebsoft.common.system.service.OrganizationService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 组织机构控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-14 11:29:04
|
||||
*/
|
||||
@Api(tags = "组织机构管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/organization")
|
||||
public class OrganizationController extends BaseController {
|
||||
@Resource
|
||||
private OrganizationService organizationService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:org:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询组织机构")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<Organization>> page(OrganizationParam param) {
|
||||
return success(organizationService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:org:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部组织机构")
|
||||
@GetMapping()
|
||||
public ApiResult<List<Organization>> list(OrganizationParam param) {
|
||||
return success(organizationService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:org:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询组织机构")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<Organization> get(@PathVariable("id") Integer id) {
|
||||
return success(organizationService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:org:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加组织机构")
|
||||
@PostMapping()
|
||||
public ApiResult<?> add(@RequestBody Organization organization) {
|
||||
if (organization.getParentId() == null) {
|
||||
organization.setParentId(0);
|
||||
}
|
||||
if (organizationService.count(new LambdaQueryWrapper<Organization>()
|
||||
.eq(Organization::getOrganizationName, organization.getOrganizationName())
|
||||
.eq(Organization::getParentId, organization.getParentId())) > 0) {
|
||||
return fail("机构名称已存在");
|
||||
}
|
||||
if (organizationService.save(organization)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:org:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改组织机构")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody Organization organization) {
|
||||
if (organization.getOrganizationName() != null) {
|
||||
if (organization.getParentId() == null) {
|
||||
organization.setParentId(0);
|
||||
}
|
||||
if (organizationService.count(new LambdaQueryWrapper<Organization>()
|
||||
.eq(Organization::getOrganizationName, organization.getOrganizationName())
|
||||
.eq(Organization::getParentId, organization.getParentId())
|
||||
.ne(Organization::getOrganizationId, organization.getOrganizationId())) > 0) {
|
||||
return fail("机构名称已存在");
|
||||
}
|
||||
}
|
||||
if (organizationService.updateById(organization)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:org:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除组织机构")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (organizationService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:org:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加组织机构")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<Organization> organizationList) {
|
||||
if (organizationService.saveBatch(organizationList)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:org:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量修改组织机构")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> updateBatch(@RequestBody BatchParam<Organization> batchParam) {
|
||||
if (batchParam.update(organizationService, Organization::getOrganizationId)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:org:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除组织机构")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (organizationService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.core.web.BatchParam;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.system.entity.Menu;
|
||||
import com.gxwebsoft.common.system.entity.Plug;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.param.PlugParam;
|
||||
import com.gxwebsoft.common.system.service.MenuService;
|
||||
import com.gxwebsoft.common.system.service.PlugService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 插件扩展控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2023-05-18 11:57:37
|
||||
*/
|
||||
@Api(tags = "插件扩展管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/plug")
|
||||
public class PlugController extends BaseController {
|
||||
@Resource
|
||||
private PlugService plugService;
|
||||
@Resource
|
||||
private MenuService menuService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:plug:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询插件扩展")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<Plug>> page(PlugParam param) {
|
||||
// 如果不传userId,只显示审核通过的插件
|
||||
if (param.getUserId() == null) {
|
||||
param.setStatus(20);
|
||||
}
|
||||
// 使用关联查询
|
||||
return success(plugService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:plug:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部插件扩展")
|
||||
@GetMapping()
|
||||
public ApiResult<List<Plug>> list(PlugParam param) {
|
||||
// 使用关联查询
|
||||
return success(plugService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:plug:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询插件扩展")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<Plug> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(plugService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:plug:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加插件扩展")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody Plug plug) {
|
||||
// 记录当前登录用户id
|
||||
User loginUser = getLoginUser();
|
||||
if (loginUser != null) {
|
||||
plug.setUserId(loginUser.getUserId());
|
||||
}
|
||||
if (plugService.save(plug)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:plug:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改插件扩展")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody Plug plug) {
|
||||
if (plugService.updateById(plug)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:plug:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除插件扩展")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (plugService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:plug:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加插件扩展")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<Plug> list) {
|
||||
if (plugService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:plug:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量修改插件扩展")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<Plug> batchParam) {
|
||||
if (batchParam.update(plugService, "menu_id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:plug:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除插件扩展")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (plugService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:plug:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("发布插件")
|
||||
@PostMapping("/plug")
|
||||
public ApiResult<?> plug(@RequestBody Plug plug){
|
||||
final Integer menuId = plug.getParentId();
|
||||
// 查重
|
||||
final int count = plugService.count(new LambdaQueryWrapper<Plug>().eq(Plug::getMenuId, menuId));
|
||||
if(count > 0){
|
||||
return fail("请勿重复发布");
|
||||
}
|
||||
// 准备数据
|
||||
final Menu menu = menuService.getById(menuId);
|
||||
plug.setUserId(getLoginUserId());
|
||||
plug.setMenuId(menuId);
|
||||
plug.setTenantId(getTenantId());
|
||||
plug.setIcon(menu.getIcon());
|
||||
plug.setPath(menu.getPath());
|
||||
plug.setComponent(menu.getComponent());
|
||||
plug.setAuthority(menu.getAuthority());
|
||||
plug.setTitle(menu.getTitle());
|
||||
plug.setMenuType(menu.getMenuType());
|
||||
plug.setMeta(menu.getMeta());
|
||||
plug.setParentId(menu.getParentId());
|
||||
plug.setHide(menu.getHide());
|
||||
plug.setSortNumber(menu.getSortNumber());
|
||||
if(plugService.save(plug)){
|
||||
return success("发布成功");
|
||||
}
|
||||
return fail("发布失败");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.gxwebsoft.common.core.utils.CacheClient;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/redis-util")
|
||||
@Api(tags = "Redis缓存工具接口")
|
||||
public class RedisUtilController extends BaseController {
|
||||
private CacheClient cacheClient;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private static final String SPLIT = ":";
|
||||
private static final String PREFIX_ENTITY_LIKE = "focus:user";
|
||||
private static final String PREFIX_USER_LIKE = "like:user";
|
||||
private static final String PREFIX_FOLLOWEE = "followee";
|
||||
private static final String PREFIX_FOLLOWER = "follower";
|
||||
|
||||
|
||||
public RedisUtilController(StringRedisTemplate redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
@ApiOperation("添加关注")
|
||||
@PostMapping("/addFocus")
|
||||
public ApiResult<?> addFocus(@RequestBody User user) {
|
||||
final Integer userId = user.getUserId();
|
||||
redisTemplate.opsForZSet().incrementScore(getFocusKey(userId), userId.toString(), 1);
|
||||
return success("关注成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 某个用户的关注数
|
||||
* @return like:entity:[entityId] ->set(userId)
|
||||
*/
|
||||
public static String getFocusKey(Integer userId) {
|
||||
return PREFIX_ENTITY_LIKE + SPLIT + userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 某个用户的赞
|
||||
* @return like:entity:[entityId] ->set(userId)
|
||||
*/
|
||||
public static String getEntityLikeKey(int entityType, int entityId) {
|
||||
return PREFIX_ENTITY_LIKE + SPLIT + entityType + SPLIT + entityId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 某个用户的赞
|
||||
* @return like:user:[userId] ->int
|
||||
*/
|
||||
public static String getUserLikeKey(int userId) {
|
||||
return PREFIX_USER_LIKE + SPLIT + userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 某个用户关注的实体(键:用户Id,值:实体Id)
|
||||
* @return followee:[userId:entityType] ->zSet(entityId,now)
|
||||
*/
|
||||
public static String getFolloweeKey(int userId, int entityType) {
|
||||
return PREFIX_FOLLOWEE + SPLIT + userId + SPLIT + entityType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 某个实体拥有的粉丝(键:实体Id,值:用户Id)
|
||||
* @return follower:[entityType:entityId] ->zSet(entityId,now)
|
||||
*/
|
||||
public static String getFollowerKey(int entityType, int entityId) {
|
||||
return PREFIX_FOLLOWER + SPLIT + entityType + SPLIT + entityId;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.core.web.PageParam;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.system.entity.Role;
|
||||
import com.gxwebsoft.common.system.param.RoleParam;
|
||||
import com.gxwebsoft.common.system.service.RoleService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 角色控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:02
|
||||
*/
|
||||
@Api(tags = "角色管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/role")
|
||||
public class RoleController extends BaseController {
|
||||
@Resource
|
||||
private RoleService roleService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:role:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询角色")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<Role>> page(RoleParam param) {
|
||||
PageParam<Role, RoleParam> page = new PageParam<>(param);
|
||||
return success(roleService.page(page, page.getWrapper()));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:role:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部角色")
|
||||
@GetMapping()
|
||||
public ApiResult<List<Role>> list(RoleParam param) {
|
||||
PageParam<Role, RoleParam> page = new PageParam<>(param);
|
||||
return success(roleService.list(page.getOrderWrapper()));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:role:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询角色")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<Role> get(@PathVariable("id") Integer id) {
|
||||
return success(roleService.getById(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:role:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加角色")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody Role role) {
|
||||
if (roleService.count(new LambdaQueryWrapper<Role>().eq(Role::getRoleCode, role.getRoleCode())) > 0) {
|
||||
return fail("角色标识已存在");
|
||||
}
|
||||
if (roleService.count(new LambdaQueryWrapper<Role>().eq(Role::getRoleName, role.getRoleName())) > 0) {
|
||||
return fail("角色名称已存在");
|
||||
}
|
||||
if (roleService.save(role)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:role:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改角色")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody Role role) {
|
||||
if (role.getRoleCode() != null && roleService.count(new LambdaQueryWrapper<Role>()
|
||||
.eq(Role::getRoleCode, role.getRoleCode())
|
||||
.ne(Role::getRoleId, role.getRoleId())) > 0) {
|
||||
return fail("角色标识已存在");
|
||||
}
|
||||
if (role.getRoleName() != null && roleService.count(new LambdaQueryWrapper<Role>()
|
||||
.eq(Role::getRoleName, role.getRoleName())
|
||||
.ne(Role::getRoleId, role.getRoleId())) > 0) {
|
||||
return fail("角色名称已存在");
|
||||
}
|
||||
if (roleService.updateById(role)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:role:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除角色")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (roleService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:role:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加角色")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<List<String>> saveBatch(@RequestBody List<Role> list) {
|
||||
// 校验是否重复
|
||||
if (CommonUtil.checkRepeat(list, Role::getRoleName)) {
|
||||
return fail("角色名称存在重复", null);
|
||||
}
|
||||
if (CommonUtil.checkRepeat(list, Role::getRoleCode)) {
|
||||
return fail("角色标识存在重复", null);
|
||||
}
|
||||
// 校验是否存在
|
||||
List<Role> codeExists = roleService.list(new LambdaQueryWrapper<Role>().in(Role::getRoleCode,
|
||||
list.stream().map(Role::getRoleCode).collect(Collectors.toList())));
|
||||
if (codeExists.size() > 0) {
|
||||
return fail("角色标识已存在", codeExists.stream().map(Role::getRoleCode)
|
||||
.collect(Collectors.toList())).setCode(2);
|
||||
}
|
||||
List<Role> nameExists = roleService.list(new LambdaQueryWrapper<Role>().in(Role::getRoleName,
|
||||
list.stream().map(Role::getRoleCode).collect(Collectors.toList())));
|
||||
if (nameExists.size() > 0) {
|
||||
return fail("角色标识已存在", nameExists.stream().map(Role::getRoleCode)
|
||||
.collect(Collectors.toList())).setCode(3);
|
||||
}
|
||||
if (roleService.saveBatch(list)) {
|
||||
return success("添加成功", null);
|
||||
}
|
||||
return fail("添加失败", null);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:role:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除角色")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (roleService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import com.gxwebsoft.common.system.entity.Menu;
|
||||
import com.gxwebsoft.common.system.entity.RoleMenu;
|
||||
import com.gxwebsoft.common.system.service.MenuService;
|
||||
import com.gxwebsoft.common.system.service.RoleMenuService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 角色菜单控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:01
|
||||
*/
|
||||
@Api(tags = "角色菜单管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/role-menu")
|
||||
public class RoleMenuController extends BaseController {
|
||||
@Resource
|
||||
private RoleMenuService roleMenuService;
|
||||
@Resource
|
||||
private MenuService menuService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:role:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询角色菜单")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<List<Menu>> list(@PathVariable("id") Integer roleId) {
|
||||
List<Menu> menus = menuService.list(new LambdaQueryWrapper<Menu>().orderByAsc(Menu::getSortNumber));
|
||||
List<RoleMenu> roleMenus = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>()
|
||||
.eq(RoleMenu::getRoleId, roleId));
|
||||
for (Menu menu : menus) {
|
||||
menu.setChecked(roleMenus.stream().anyMatch((d) -> d.getMenuId().equals(menu.getMenuId())));
|
||||
}
|
||||
return success(menus);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@PreAuthorize("hasAuthority('sys:role:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改角色菜单")
|
||||
@PutMapping("/{id}")
|
||||
public ApiResult<?> update(@PathVariable("id") Integer roleId, @RequestBody List<Integer> menuIds) {
|
||||
roleMenuService.remove(new LambdaUpdateWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));
|
||||
if (menuIds != null && menuIds.size() > 0) {
|
||||
List<RoleMenu> roleMenuList = new ArrayList<>();
|
||||
for (Integer menuId : menuIds) {
|
||||
RoleMenu roleMenu = new RoleMenu();
|
||||
roleMenu.setRoleId(roleId);
|
||||
roleMenu.setMenuId(menuId);
|
||||
roleMenuList.add(roleMenu);
|
||||
}
|
||||
if (!roleMenuService.saveBatch(roleMenuList)) {
|
||||
throw new BusinessException("保存失败");
|
||||
}
|
||||
}
|
||||
return success("保存成功");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:role:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加角色菜单")
|
||||
@PostMapping("/{id}")
|
||||
public ApiResult<?> addRoleAuth(@PathVariable("id") Integer roleId, @RequestBody Integer menuId) {
|
||||
RoleMenu roleMenu = new RoleMenu();
|
||||
roleMenu.setRoleId(roleId);
|
||||
roleMenu.setMenuId(menuId);
|
||||
if (roleMenuService.save(roleMenu)) {
|
||||
return success();
|
||||
}
|
||||
return fail();
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:role:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("移除角色菜单")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer roleId, @RequestBody Integer menuId) {
|
||||
if (roleMenuService.remove(new LambdaUpdateWrapper<RoleMenu>()
|
||||
.eq(RoleMenu::getRoleId, roleId).eq(RoleMenu::getMenuId, menuId))) {
|
||||
return success();
|
||||
}
|
||||
return fail();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.utils.RedisUtil;
|
||||
import com.gxwebsoft.common.core.web.*;
|
||||
import com.gxwebsoft.common.system.entity.Setting;
|
||||
import com.gxwebsoft.common.system.entity.Tenant;
|
||||
import com.gxwebsoft.common.system.param.SettingParam;
|
||||
import com.gxwebsoft.common.system.service.SettingService;
|
||||
import com.gxwebsoft.common.system.service.TenantService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 系统设置控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2022-11-19 13:54:27
|
||||
*/
|
||||
@Api(tags = "系统设置管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/setting")
|
||||
public class SettingController extends BaseController {
|
||||
@Resource
|
||||
private SettingService settingService;
|
||||
@Resource
|
||||
private TenantService tenantService;
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:setting:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询系统设置")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<Setting>> page(SettingParam param) {
|
||||
PageParam<Setting, SettingParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("create_time desc");
|
||||
return success(settingService.page(page, page.getWrapper()));
|
||||
// 使用关联查询
|
||||
//return success(settingService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:setting:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部系统设置")
|
||||
@GetMapping()
|
||||
public ApiResult<List<Setting>> list(SettingParam param) {
|
||||
PageParam<Setting, SettingParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("create_time desc");
|
||||
return success(settingService.list(page.getOrderWrapper()));
|
||||
// 使用关联查询
|
||||
//return success(settingService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:setting:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询系统设置")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<Setting> get(@PathVariable("id") Integer id) {
|
||||
return success(settingService.getById(id));
|
||||
// 使用关联查询
|
||||
//return success(settingService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:setting:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加系统设置")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody Setting setting) {
|
||||
if (settingService.save(setting)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:setting:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改系统设置")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody Setting setting) {
|
||||
if (settingService.updateById(setting)) {
|
||||
// 更新系统设置信息到缓存
|
||||
String key = "setting:" + setting.getSettingKey() + ":" + getTenantId();
|
||||
System.out.println("key = " + key);
|
||||
redisUtil.set(key, JSON.parseObject(setting.getContent()));
|
||||
// 创建微信支付Bean
|
||||
// settingService.initConfig(setting);
|
||||
// 更新租户信息
|
||||
if (setting.getSettingKey().equals("setting")) {
|
||||
System.out.println("修改系统设置 = " + setting.getContent());
|
||||
final String content = setting.getContent();
|
||||
final JSONObject jsonObject = JSONObject.parseObject(content);
|
||||
final String siteName = jsonObject.getString("siteName");
|
||||
final String logo = jsonObject.getString("logo");
|
||||
System.out.println("siteName = " + siteName);
|
||||
final Tenant tenant = new Tenant();
|
||||
tenant.setTenantName(siteName);
|
||||
tenant.setTenantId(getTenantId());
|
||||
tenant.setLogo(logo);
|
||||
tenantService.updateById(tenant);
|
||||
}
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:setting:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除系统设置")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (settingService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:setting:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加系统设置")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<Setting> list) {
|
||||
if (settingService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:setting:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量修改系统设置")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<Setting> batchParam) {
|
||||
if (batchParam.update(settingService, "setting_id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:setting:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除系统设置")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (settingService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:setting:data')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询租户设置信息")
|
||||
@GetMapping("/data")
|
||||
public ApiResult<?> data() {
|
||||
return success(settingService.getData("setting"));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:setting:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("更新主题皮肤")
|
||||
@PutMapping("/theme")
|
||||
public ApiResult<?> theme(@RequestBody Setting setting) {
|
||||
String key = "theme:".concat(getTenantId().toString());
|
||||
// 新增
|
||||
final Setting one = settingService.getOne(new LambdaQueryWrapper<Setting>().eq(Setting::getSettingKey, setting.getSettingKey()));
|
||||
if(one == null){
|
||||
settingService.save(setting);
|
||||
redisUtil.set(key,setting.getContent());
|
||||
return success("保存成功");
|
||||
}
|
||||
// 更新
|
||||
final Setting update = settingService.getOne(new LambdaQueryWrapper<Setting>().eq(Setting::getSettingKey, setting.getSettingKey()));
|
||||
update.setContent(setting.getContent());
|
||||
if (settingService.updateById(update)) {
|
||||
redisUtil.set(key,setting.getContent());
|
||||
return success("更新成功");
|
||||
}
|
||||
return fail("更新失败");
|
||||
}
|
||||
|
||||
@ApiOperation("更新主题皮肤")
|
||||
@GetMapping("/getTheme")
|
||||
public ApiResult<?> getTheme() {
|
||||
String key = "theme:".concat(getTenantId().toString());
|
||||
return success("获取成功",redisUtil.get(key));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.system.entity.Menu;
|
||||
import com.gxwebsoft.common.system.entity.RoleMenu;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.service.MenuService;
|
||||
import com.gxwebsoft.common.system.service.RoleMenuService;
|
||||
import com.gxwebsoft.common.system.service.TenantService;
|
||||
import com.gxwebsoft.common.system.entity.Tenant;
|
||||
import com.gxwebsoft.common.system.param.TenantParam;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.core.web.PageParam;
|
||||
import com.gxwebsoft.common.core.web.BatchParam;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 租户控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2023-07-17 17:49:53
|
||||
*/
|
||||
@Api(tags = "租户管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/tenant")
|
||||
public class TenantController extends BaseController {
|
||||
@Resource
|
||||
private TenantService tenantService;
|
||||
@Resource
|
||||
private MenuService menuService;
|
||||
@Resource
|
||||
private RoleMenuService roleMenuService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:tenant:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询租户")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<Tenant>> page(TenantParam param) {
|
||||
// 使用关联查询
|
||||
return success(tenantService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:tenant:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部租户")
|
||||
@GetMapping()
|
||||
public ApiResult<List<Tenant>> list(TenantParam param) {
|
||||
// 使用关联查询
|
||||
return success(tenantService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:tenant:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询租户")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<Tenant> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(tenantService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:tenant:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加租户")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody Tenant tenant) {
|
||||
System.out.println("tenant = " + tenant);
|
||||
if (tenantService.save(tenant)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:tenant:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改租户")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody Tenant tenant) {
|
||||
if (tenantService.updateById(tenant)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:tenant:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除租户")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (tenantService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:tenant:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量添加租户")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<Tenant> list) {
|
||||
if (tenantService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:tenant:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量修改租户")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<Tenant> batchParam) {
|
||||
if (batchParam.update(tenantService, "tenant_id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:tenant:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除租户")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (tenantService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@ApiOperation("租户角色权限初始化")
|
||||
@GetMapping("/role-menu/{id}")
|
||||
public ApiResult<List<Menu>> initialization(@PathVariable("id") Integer roleId) {
|
||||
List<Menu> menus = menuService.list(new LambdaQueryWrapper<Menu>().orderByAsc(Menu::getSortNumber));
|
||||
List<RoleMenu> roleMenus = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>()
|
||||
.eq(RoleMenu::getRoleId, roleId));
|
||||
for (Menu menu : menus) {
|
||||
menu.setChecked(roleMenus.stream().anyMatch((d) -> d.getMenuId().equals(menu.getMenuId())));
|
||||
}
|
||||
List<Integer> menuIds = menus.stream().map(Menu::getMenuId).collect(Collectors.toList());
|
||||
roleMenuService.remove(new LambdaUpdateWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));
|
||||
if (menuIds.size() > 0) {
|
||||
List<RoleMenu> roleMenuList = new ArrayList<>();
|
||||
for (Integer menuId : menuIds) {
|
||||
RoleMenu roleMenu = new RoleMenu();
|
||||
roleMenu.setRoleId(roleId);
|
||||
roleMenu.setMenuId(menuId);
|
||||
roleMenuList.add(roleMenu);
|
||||
}
|
||||
if (!roleMenuService.saveBatch(roleMenuList)) {
|
||||
throw new BusinessException("保存失败");
|
||||
}
|
||||
}
|
||||
return success(menus);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import cn.afterturn.easypoi.excel.ExcelImportUtil;
|
||||
import cn.afterturn.easypoi.excel.entity.ImportParams;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.core.web.*;
|
||||
import com.gxwebsoft.common.system.entity.DictionaryData;
|
||||
import com.gxwebsoft.common.system.entity.Organization;
|
||||
import com.gxwebsoft.common.system.entity.Role;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.param.UserImportParam;
|
||||
import com.gxwebsoft.common.system.param.UserParam;
|
||||
import com.gxwebsoft.common.system.service.DictionaryDataService;
|
||||
import com.gxwebsoft.common.system.service.OrganizationService;
|
||||
import com.gxwebsoft.common.system.service.RoleService;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
import com.gxwebsoft.love.entity.UserProfile;
|
||||
import com.gxwebsoft.love.service.UserProfileService;
|
||||
import com.gxwebsoft.shop.entity.UserOauth;
|
||||
import com.gxwebsoft.shop.service.UserOauthService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiImplicitParams;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 用户控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:41
|
||||
*/
|
||||
@Api(tags = "用户管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/user")
|
||||
public class UserController extends BaseController {
|
||||
@Resource
|
||||
private UserService userService;
|
||||
@Resource
|
||||
private RoleService roleService;
|
||||
@Resource
|
||||
private OrganizationService organizationService;
|
||||
@Resource
|
||||
private DictionaryDataService dictionaryDataService;
|
||||
@Resource
|
||||
private UserOauthService userOauthService;
|
||||
@Resource
|
||||
private UserProfileService userProfileService;
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询用户")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<User>> page(UserParam param) {
|
||||
return success(userService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部用户")
|
||||
@GetMapping()
|
||||
public ApiResult<List<User>> list(UserParam param) {
|
||||
return success(userService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("根据id查询用户")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<User> get(@PathVariable("id") Integer id) {
|
||||
return success(userService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加用户")
|
||||
@PostMapping()
|
||||
public ApiResult<?> add(@RequestBody User user) {
|
||||
user.setStatus(0);
|
||||
user.setPassword(userService.encodePassword(user.getPassword()));
|
||||
if (userService.saveUser(user)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改用户")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody User user) {
|
||||
user.setStatus(null);
|
||||
user.setUsername(null);
|
||||
user.setPassword(null);
|
||||
// 前端请求限制仅可以修改自己的用户信息
|
||||
if (getAppId() != null) {
|
||||
user.setUserId(getLoginUserId());
|
||||
}
|
||||
// 保存详细资料
|
||||
if(user.getUserProfile() != null){
|
||||
userProfileService.update(user.getUserProfile(),new LambdaUpdateWrapper<UserProfile>().eq(UserProfile::getUserId,user.getUserId()));
|
||||
}
|
||||
if (userService.updateUser(user)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除用户")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (userService.removeById(id)) {
|
||||
QueryWrapper<UserOauth> userOauthQueryWrapper = new QueryWrapper<>();
|
||||
userOauthService.remove(userOauthQueryWrapper.eq("user_id",id));
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量修改用户")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<User> batchParam) {
|
||||
if (batchParam.update(userService, User::getUserId)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:remove')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除用户")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "ids", value = "id数组", required = true, dataType = "string", dataTypeClass = String.class)
|
||||
})
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> deleteBatch(@RequestBody List<Integer> ids) {
|
||||
ids.forEach(userId -> {
|
||||
QueryWrapper<UserOauth> userOauthQueryWrapper = new QueryWrapper<>();
|
||||
userOauthService.remove(userOauthQueryWrapper.eq("user_id",userId));
|
||||
});
|
||||
if (userService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改用户状态")
|
||||
@PutMapping("/status")
|
||||
public ApiResult<?> updateStatus(@RequestBody User user) {
|
||||
if (user.getUserId() == null || user.getStatus() == null || !Arrays.asList(0, 1).contains(user.getStatus())) {
|
||||
return fail("参数不正确");
|
||||
}
|
||||
User u = new User();
|
||||
u.setUserId(user.getUserId());
|
||||
u.setStatus(user.getStatus());
|
||||
if (userService.updateById(u)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改推荐状态")
|
||||
@PutMapping("/recommend")
|
||||
public ApiResult<?> updateRecommend(@RequestBody User user) {
|
||||
if (user.getUserId() == null || user.getRecommend() == null || !Arrays.asList(0, 1).contains(user.getRecommend())) {
|
||||
return fail("参数不正确");
|
||||
}
|
||||
User u = new User();
|
||||
u.setUserId(user.getUserId());
|
||||
u.setRecommend(user.getRecommend());
|
||||
// 同步修改资料表
|
||||
userProfileService.updateById(user.getUserProfile());
|
||||
if (userService.updateById(u)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量修改用户状态")
|
||||
@PutMapping("/status/batch")
|
||||
public ApiResult<?> updateStatusBatch(@RequestBody BatchParam<Integer> batchParam) {
|
||||
if (!Arrays.asList(0, 1).contains(batchParam.getData())) {
|
||||
return fail("状态值不正确");
|
||||
}
|
||||
if (userService.update(new LambdaUpdateWrapper<User>()
|
||||
.in(User::getUserId, batchParam.getIds())
|
||||
.set(User::getStatus, batchParam.getData()))) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("重置密码")
|
||||
@PutMapping("/password")
|
||||
public ApiResult<?> resetPassword(@RequestBody User user) {
|
||||
if (user.getUserId() == null || StrUtil.isBlank(user.getPassword())) {
|
||||
return fail("参数不正确");
|
||||
}
|
||||
User u = new User();
|
||||
u.setUserId(user.getUserId());
|
||||
u.setPassword(userService.encodePassword(user.getPassword()));
|
||||
if (userService.updateById(u)) {
|
||||
return success("重置成功");
|
||||
} else {
|
||||
return fail("重置失败");
|
||||
}
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:update')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量重置密码")
|
||||
@PutMapping("/password/batch")
|
||||
public ApiResult<?> resetPasswordBatch(@RequestBody BatchParam<String> batchParam) {
|
||||
if (batchParam.getIds() == null || batchParam.getIds().size() == 0) {
|
||||
return fail("请选择用户");
|
||||
}
|
||||
if (batchParam.getData() == null) {
|
||||
return fail("请输入密码");
|
||||
}
|
||||
if (userService.update(new LambdaUpdateWrapper<User>()
|
||||
.in(User::getUserId, batchParam.getIds())
|
||||
.set(User::getPassword, userService.encodePassword(batchParam.getData())))) {
|
||||
return success("重置成功");
|
||||
} else {
|
||||
return fail("重置失败");
|
||||
}
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("检查用户是否存在")
|
||||
@GetMapping("/existence")
|
||||
public ApiResult<?> existence(ExistenceParam<User> param) {
|
||||
if (param.isExistence(userService, User::getUserId)) {
|
||||
return success(param.getValue() + "已存在");
|
||||
}
|
||||
return fail(param.getValue() + "不存在");
|
||||
}
|
||||
|
||||
/**
|
||||
* excel导入用户
|
||||
*/
|
||||
@PreAuthorize("hasAuthority('sys:user:save')")
|
||||
@OperationLog
|
||||
@ApiOperation("导入用户")
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@PostMapping("/import")
|
||||
public ApiResult<List<String>> importBatch(MultipartFile file) {
|
||||
ImportParams importParams = new ImportParams();
|
||||
try {
|
||||
List<UserImportParam> list = ExcelImportUtil.importExcel(file.getInputStream(),
|
||||
UserImportParam.class, importParams);
|
||||
// 校验是否重复
|
||||
if (CommonUtil.checkRepeat(list, UserImportParam::getUsername)) {
|
||||
return fail("账号存在重复", null);
|
||||
}
|
||||
if (CommonUtil.checkRepeat(list, UserImportParam::getPhone)) {
|
||||
return fail("手机号存在重复", null);
|
||||
}
|
||||
// 校验是否存在
|
||||
List<User> usernameExists = userService.list(new LambdaQueryWrapper<User>().in(User::getUsername,
|
||||
list.stream().map(UserImportParam::getUsername).collect(Collectors.toList())));
|
||||
if (usernameExists.size() > 0) {
|
||||
return fail("账号已经存在",
|
||||
usernameExists.stream().map(User::getUsername).collect(Collectors.toList()));
|
||||
}
|
||||
List<User> phoneExists = userService.list(new LambdaQueryWrapper<User>().in(User::getPhone,
|
||||
list.stream().map(UserImportParam::getPhone).collect(Collectors.toList())));
|
||||
if (phoneExists.size() > 0) {
|
||||
return fail("手机号已经存在",
|
||||
phoneExists.stream().map(User::getPhone).collect(Collectors.toList()));
|
||||
}
|
||||
// 添加
|
||||
List<User> users = new ArrayList<>();
|
||||
for (UserImportParam one : list) {
|
||||
User u = new User();
|
||||
u.setStatus(0);
|
||||
u.setUsername(one.getUsername());
|
||||
u.setPassword(userService.encodePassword(one.getPassword()));
|
||||
u.setNickname(one.getNickname());
|
||||
u.setPhone(one.getPhone());
|
||||
Role role = roleService.getOne(new QueryWrapper<Role>()
|
||||
.eq("role_name", one.getRoleName()), false);
|
||||
if (role == null) {
|
||||
return fail("角色不存在", Collections.singletonList(one.getRoleName()));
|
||||
} else {
|
||||
u.setRoles(Collections.singletonList(role));
|
||||
}
|
||||
Organization organization = organizationService.getOne(new QueryWrapper<Organization>()
|
||||
.eq("organization_full_name", one.getOrganizationName()), false);
|
||||
if (organization == null) {
|
||||
return fail("机构不存在", Collections.singletonList(one.getOrganizationName()));
|
||||
} else {
|
||||
u.setOrganizationId(organization.getOrganizationId());
|
||||
}
|
||||
DictionaryData sex = dictionaryDataService.getByDictCodeAndName("sex", one.getSexName());
|
||||
if (sex == null) {
|
||||
return fail("性别不存在", Collections.singletonList(one.getSexName()));
|
||||
} else {
|
||||
u.setSex(sex.getDictDataCode());
|
||||
}
|
||||
}
|
||||
if (userService.saveBatch(users)) {
|
||||
return success("导入成功", null);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return fail("导入失败", null);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:auth:user')")
|
||||
@PostMapping("/getAvatarByMpWx")
|
||||
@ApiOperation("更新微信头像")
|
||||
public ApiResult<?> getAvatarByMpWx(@RequestBody User user){
|
||||
user.setAvatar("https://oa.gxwebsoft.com/assets/logo.7ccfefb9.svg");
|
||||
if (userService.updateUser(user)) {
|
||||
return success("更新成功");
|
||||
}
|
||||
return fail("更新失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:user:list')")
|
||||
@OperationLog
|
||||
@ApiOperation("统计用户余额")
|
||||
@GetMapping("/countUserBalance")
|
||||
public ApiResult<?> countUserBalance(User param) {
|
||||
final LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.gt(User::getBalance, 0);
|
||||
if (!param.getOrganizationId().equals(0)) {
|
||||
wrapper.eq(User::getOrganizationId,param.getOrganizationId());
|
||||
}
|
||||
final List<User> list = userService.list(wrapper);
|
||||
final BigDecimal totalBalance = list.stream().map(User::getBalance).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
// System.out.println("统计用户余额 = " + totalBalance);
|
||||
return success("统计成功",totalBalance);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.gxwebsoft.common.core.utils.FileServerUtil;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.system.service.UserFileService;
|
||||
import com.gxwebsoft.common.system.entity.UserFile;
|
||||
import com.gxwebsoft.common.system.param.UserFileParam;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.core.web.PageParam;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户文件控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2022-07-21 14:34:40
|
||||
*/
|
||||
@Api(tags = "用户文件管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/system/user-file")
|
||||
public class UserFileController extends BaseController {
|
||||
@Resource
|
||||
private UserFileService userFileService;
|
||||
|
||||
@OperationLog
|
||||
@ApiOperation("分页查询用户文件")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<UserFile>> page(UserFileParam param, HttpServletRequest request) {
|
||||
param.setUserId(getLoginUserId());
|
||||
PageParam<UserFile, UserFileParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("is_directory desc");
|
||||
PageParam<UserFile, UserFileParam> result = userFileService.page(page, page.getWrapper());
|
||||
List<UserFile> records = result.getRecords();
|
||||
String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/system/user-file") + "/file";
|
||||
for (UserFile record : records) {
|
||||
if (StrUtil.isNotBlank(record.getPath())) {
|
||||
record.setUrl(requestURL + "/" + record.getPath());
|
||||
if (FileServerUtil.isImage(record.getContentType())) {
|
||||
record.setThumbnail(requestURL + "/thumbnail/" + record.getPath());
|
||||
}
|
||||
record.setDownloadUrl(requestURL + "/download/" + record.getPath());
|
||||
}
|
||||
}
|
||||
return success(records, result.getTotal());
|
||||
}
|
||||
|
||||
@OperationLog
|
||||
@ApiOperation("查询全部用户文件")
|
||||
@GetMapping()
|
||||
public ApiResult<List<UserFile>> list(UserFileParam param, HttpServletRequest request) {
|
||||
param.setUserId(getLoginUserId());
|
||||
PageParam<UserFile, UserFileParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("is_directory desc");
|
||||
List<UserFile> records = userFileService.list(page.getOrderWrapper());
|
||||
String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/system/user-file") + "/file";
|
||||
for (UserFile record : records) {
|
||||
if (StrUtil.isNotBlank(record.getPath())) {
|
||||
record.setUrl(requestURL + "/" + record.getPath());
|
||||
if (FileServerUtil.isImage(record.getContentType())) {
|
||||
record.setThumbnail(requestURL + "/thumbnail/" + record.getPath());
|
||||
}
|
||||
record.setDownloadUrl(requestURL + "/download/" + record.getPath());
|
||||
}
|
||||
}
|
||||
return success(records);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:auth:user')")
|
||||
@OperationLog
|
||||
@ApiOperation("添加用户文件")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody UserFile userFile) {
|
||||
userFile.setUserId(getLoginUserId());
|
||||
if (userFile.getParentId() == null) {
|
||||
userFile.setParentId(0);
|
||||
}
|
||||
if (userFile.getIsDirectory() != null && userFile.getIsDirectory().equals(1)) {
|
||||
if (userFileService.count(new LambdaQueryWrapper<UserFile>()
|
||||
.eq(UserFile::getName, userFile.getName())
|
||||
.eq(UserFile::getParentId, userFile.getParentId())
|
||||
.eq(UserFile::getUserId, userFile.getUserId())) > 0) {
|
||||
return fail("文件夹名称已存在");
|
||||
}
|
||||
}
|
||||
if (userFileService.save(userFile)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:auth:user')")
|
||||
@OperationLog
|
||||
@ApiOperation("修改用户文件")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody UserFile userFile) {
|
||||
Integer loginUserId = getLoginUserId();
|
||||
UserFile old = userFileService.getById(userFile.getId());
|
||||
UserFile entity = new UserFile();
|
||||
if (StrUtil.isNotBlank(userFile.getName())) {
|
||||
entity.setName(userFile.getName());
|
||||
}
|
||||
if (userFile.getParentId() != null) {
|
||||
entity.setParentId(userFile.getParentId());
|
||||
}
|
||||
if (!old.getUserId().equals(loginUserId) ||
|
||||
(entity.getName() == null && entity.getParentId() == null)) {
|
||||
return fail("修改失败");
|
||||
}
|
||||
if (old.getIsDirectory() != null && old.getIsDirectory().equals(1)) {
|
||||
if (userFileService.count(new LambdaQueryWrapper<UserFile>()
|
||||
.eq(UserFile::getName, entity.getName() == null ? old.getName() : entity.getName())
|
||||
.eq(UserFile::getParentId, entity.getParentId() == null ? old.getParentId() : entity.getParentId())
|
||||
.eq(UserFile::getUserId, loginUserId)
|
||||
.ne(UserFile::getId, old.getId())) > 0) {
|
||||
return fail("文件夹名称已存在");
|
||||
}
|
||||
}
|
||||
if (userFileService.update(entity, new LambdaUpdateWrapper<UserFile>()
|
||||
.eq(UserFile::getId, userFile.getId())
|
||||
.eq(UserFile::getUserId, loginUserId))) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:auth:user')")
|
||||
@OperationLog
|
||||
@ApiOperation("删除用户文件")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (userFileService.remove(new LambdaUpdateWrapper<UserFile>()
|
||||
.eq(UserFile::getId, id)
|
||||
.eq(UserFile::getUserId, getLoginUserId()))) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('sys:auth:user')")
|
||||
@OperationLog
|
||||
@ApiOperation("批量删除用户文件")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (userFileService.remove(new LambdaUpdateWrapper<UserFile>()
|
||||
.in(UserFile::getId, ids)
|
||||
.eq(UserFile::getUserId, getLoginUserId()))) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.lang.Validator;
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.http.HttpRequest;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import com.gxwebsoft.common.core.security.JwtSubject;
|
||||
import com.gxwebsoft.common.core.security.JwtUtil;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.system.entity.LoginRecord;
|
||||
import com.gxwebsoft.common.system.entity.Role;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.entity.UserRole;
|
||||
import com.gxwebsoft.common.system.param.UserParam;
|
||||
import com.gxwebsoft.common.system.result.LoginResult;
|
||||
import com.gxwebsoft.common.system.service.*;
|
||||
import com.gxwebsoft.love.entity.UserProfile;
|
||||
import com.gxwebsoft.love.service.UserProfileService;
|
||||
import com.gxwebsoft.shop.entity.Merchant;
|
||||
import com.gxwebsoft.shop.entity.UserOauth;
|
||||
import com.gxwebsoft.shop.entity.UserReferee;
|
||||
import com.gxwebsoft.shop.service.MerchantService;
|
||||
import com.gxwebsoft.shop.service.UserOauthService;
|
||||
import com.gxwebsoft.shop.service.UserRefereeService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.File;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.gxwebsoft.common.core.constants.RedisConstants.ACCESS_TOKEN_KEY;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/wx-login")
|
||||
@Api(tags = "微信小程序登录API")
|
||||
public class WxLoginController extends BaseController {
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
@Resource
|
||||
private SettingService settingService;
|
||||
@Resource
|
||||
private UserService userService;
|
||||
@Resource
|
||||
private ConfigProperties configProperties;
|
||||
@Resource
|
||||
private UserRoleService userRoleService;
|
||||
@Resource
|
||||
private UserOauthService userOauthService;
|
||||
@Resource
|
||||
private LoginRecordService loginRecordService;
|
||||
@Resource
|
||||
private RoleService roleService;
|
||||
@Resource
|
||||
private ConfigProperties config;
|
||||
@Resource
|
||||
private UserRefereeService userRefereeService;
|
||||
@Resource
|
||||
private UserProfileService userProfileService;
|
||||
@Resource
|
||||
private MerchantService merchantService;
|
||||
|
||||
public WxLoginController(StringRedisTemplate redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
@ApiOperation("获取微信openId")
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@PostMapping("/getOpenId")
|
||||
public ApiResult<LoginResult> getOpenId(@RequestBody UserParam userParam, HttpServletRequest request) {
|
||||
// 1.获取openid
|
||||
JSONObject result = getOpenIdByCode(userParam);
|
||||
String openid = result.getString("openid");
|
||||
String unionid = result.getString("unionid");
|
||||
if (openid == null) {
|
||||
return fail("获取openid失败", null);
|
||||
}
|
||||
// 2.通过openid查询用户是否已存在
|
||||
User user = userService.getByOauthId(userParam);
|
||||
// 3.存在则签发token并返回登录成功,不存在则注册新用户
|
||||
if (user == null) {
|
||||
user = addUser(userParam);
|
||||
// 添加第三方用户信息
|
||||
UserOauth uo = new UserOauth();
|
||||
uo.setUserId(user.getUserId());
|
||||
uo.setTenantId(user.getTenantId());
|
||||
uo.setOauthType("MP-WEIXIN");
|
||||
uo.setOauthId(openid);
|
||||
uo.setUnionid(unionid);
|
||||
userOauthService.save(uo);
|
||||
}
|
||||
// 4.签发token
|
||||
loginRecordService.saveAsync(user.getUsername(), LoginRecord.TYPE_LOGIN, null, user.getTenantId(), request);
|
||||
String access_token = JwtUtil.buildToken(new JwtSubject(user.getUsername(), user.getTenantId()),
|
||||
configProperties.getTokenExpireTime(), configProperties.getTokenKey());
|
||||
return success("登录成功", new LoginResult(access_token, user));
|
||||
}
|
||||
|
||||
@ApiOperation("微信授权手机号码并登录")
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@PostMapping("/loginByMpWxPhone")
|
||||
public ApiResult<LoginResult> loginByMpWxPhone(@RequestBody UserParam userParam, HttpServletRequest request) {
|
||||
// 获取手机号码
|
||||
String phone = getPhoneByCode(userParam);
|
||||
if(phone == null){
|
||||
String key = ACCESS_TOKEN_KEY.concat(":").concat(getTenantId().toString());
|
||||
redisTemplate.delete(key);
|
||||
throw new BusinessException("授权失败,请重试");
|
||||
}
|
||||
// 查询是否存在
|
||||
User user = userService.getByPhone(phone);
|
||||
// 不存在则注册
|
||||
if (user == null) {
|
||||
userParam.setPhone(phone);
|
||||
user = addUser(userParam);
|
||||
user.setRecommend(1);
|
||||
}
|
||||
// 签发token
|
||||
String access_token = JwtUtil.buildToken(new JwtSubject(user.getUsername(), user.getTenantId()),
|
||||
configProperties.getTokenExpireTime(), configProperties.getTokenKey());
|
||||
loginRecordService.saveAsync(user.getUsername(), LoginRecord.TYPE_REGISTER, null, user.getTenantId(), request);
|
||||
return success("登录成功", new LoginResult(access_token, user));
|
||||
}
|
||||
|
||||
@ApiOperation("微信授权手机号码并更新")
|
||||
@Transactional(rollbackFor = {Exception.class})
|
||||
@PostMapping("/updatePhoneByMpWx")
|
||||
public ApiResult<?> updatePhoneByMpWx(@RequestBody UserParam userParam) {
|
||||
// 获取微信授权手机号
|
||||
String phone = getPhoneByCode(userParam);
|
||||
// 查询当前用户
|
||||
User user = userService.getById(userParam.getUserId());
|
||||
if (user != null && phone != null) {
|
||||
user.setPhone(phone);
|
||||
userService.updateUser(user);
|
||||
return success("更新成功",phone);
|
||||
}
|
||||
return fail("更新失败");
|
||||
}
|
||||
|
||||
/**
|
||||
* 新用户注册
|
||||
*/
|
||||
private User addUser(UserParam userParam) {
|
||||
User addUser = new User();
|
||||
// 注册用户
|
||||
addUser.setStatus(0);
|
||||
addUser.setUsername(createUsername("wx_"));
|
||||
addUser.setNickname("微信用户");
|
||||
addUser.setGradeId(2);
|
||||
if(userParam.getPhone() != null){
|
||||
addUser.setPhone(userParam.getPhone());
|
||||
}
|
||||
addUser.setPassword(userService.encodePassword(CommonUtil.randomUUID16()));
|
||||
addUser.setTenantId(getTenantId());
|
||||
addUser.setRecommend(1);
|
||||
Role role = roleService.getOne(new QueryWrapper<Role>().eq("role_code", "user"), false);
|
||||
addUser.setRoleId(role.getRoleId());
|
||||
if (userService.saveUser(addUser)) {
|
||||
// 添加用户角色
|
||||
final UserRole userRole = new UserRole();
|
||||
userRole.setUserId(addUser.getUserId());
|
||||
userRole.setTenantId(addUser.getTenantId());
|
||||
userRole.setRoleId(addUser.getRoleId());
|
||||
userRoleService.save(userRole);
|
||||
// 用户详细资料表
|
||||
final UserProfile profile = new UserProfile();
|
||||
profile.setUserId(addUser.getUserId());
|
||||
profile.setRecommend(1);
|
||||
profile.setWhenMarriedMate("想要二年内结婚");
|
||||
userProfileService.save(profile);
|
||||
// 添加门店
|
||||
final Merchant merchant = new Merchant();
|
||||
merchant.setUserId(addUser.getUserId());
|
||||
merchant.setMerchantOwner(addUser.getUserId());
|
||||
merchant.setMerchantCode(addUser.getUserId()+"");
|
||||
merchant.setMerchantName(addUser.getNickname());
|
||||
merchant.setLogo(addUser.getAvatar());
|
||||
merchant.setProvince(addUser.getProvince());
|
||||
merchant.setCity(addUser.getCity());
|
||||
merchant.setRegion(addUser.getRegion());
|
||||
merchant.setMerchantPhone(addUser.getPhone());
|
||||
merchant.setMerchantHours("8:30 - 22:30");
|
||||
merchant.setSortNumber(100);
|
||||
merchant.setStatus(0);
|
||||
merchant.setFirstRatio(new BigDecimal("0.1"));
|
||||
merchant.setSecondRatio(new BigDecimal("0.1"));
|
||||
merchant.setOnlineRatio(new BigDecimal("0.1"));
|
||||
merchant.setOfflineRatio(new BigDecimal("0"));
|
||||
merchant.setShopRatio(new BigDecimal("0"));
|
||||
merchant.setTenantId(addUser.getTenantId());
|
||||
merchantService.save(merchant);
|
||||
}
|
||||
// 绑定推荐关系
|
||||
if(userParam.getRefereeId() != null && userParam.getRefereeId() > 0){
|
||||
final Integer refereeId = userParam.getRefereeId();
|
||||
final UserReferee userReferee = new UserReferee();
|
||||
userReferee.setUserId(addUser.getUserId());
|
||||
userReferee.setDealerId(refereeId);
|
||||
userReferee.setLevel(1);
|
||||
userRefereeService.save(userReferee);
|
||||
}
|
||||
return addUser;
|
||||
}
|
||||
|
||||
// 获取openid
|
||||
private JSONObject getOpenIdByCode(UserParam userParam) {
|
||||
// 获取微信小程序配置信息
|
||||
JSONObject setting = settingService.getBySettingKey("mp-weixin");
|
||||
// 获取openId
|
||||
String apiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + setting.getString("appId") + "&secret=" + setting.getString("appSecret") + "&js_code=" + userParam.getCode() + "&grant_type=authorization_code";
|
||||
// 执行get请求
|
||||
String result = HttpUtil.get(apiUrl);
|
||||
// 解析access_token
|
||||
return JSON.parseObject(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取微信手机号码
|
||||
*
|
||||
* @param userParam 需要传微信凭证code
|
||||
*/
|
||||
private String getPhoneByCode(UserParam userParam) {
|
||||
// 获取手机号码
|
||||
String apiUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + getAccessToken();
|
||||
HashMap<String, Object> paramMap = new HashMap<>();
|
||||
if (StrUtil.isBlank(userParam.getCode())) {
|
||||
throw new BusinessException("code不能为空");
|
||||
}
|
||||
paramMap.put("code", userParam.getCode());
|
||||
// 执行post请求
|
||||
String post = HttpUtil.post(apiUrl, JSON.toJSONString(paramMap));
|
||||
JSONObject json = JSON.parseObject(post);
|
||||
if (json.get("errcode").equals(0)) {
|
||||
JSONObject phoneInfo = JSON.parseObject(json.getString("phone_info"));
|
||||
// 微信用户的手机号码
|
||||
final String phoneNumber = phoneInfo.getString("phoneNumber");
|
||||
// 验证手机号码
|
||||
if(!Validator.isMobile(phoneNumber)){
|
||||
String key = ACCESS_TOKEN_KEY.concat(":").concat(getTenantId().toString());
|
||||
redisTemplate.delete(key);
|
||||
throw new BusinessException("手机号码格式不正确");
|
||||
}
|
||||
return phoneNumber;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机账号
|
||||
*
|
||||
* @return username
|
||||
*/
|
||||
private String createUsername(String type) {
|
||||
return type.concat(RandomUtil.randomString(12));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取接口调用凭据AccessToken
|
||||
* https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html
|
||||
*/
|
||||
private String getAccessToken() {
|
||||
String key = ACCESS_TOKEN_KEY.concat(":").concat(getTenantId().toString());
|
||||
// 获取微信小程序配置信息
|
||||
JSONObject setting = settingService.getBySettingKey("mp-weixin");
|
||||
// 从缓存获取access_token
|
||||
String value = redisTemplate.opsForValue().get(key);
|
||||
if (value != null) {
|
||||
// 解析access_token
|
||||
JSONObject response = JSON.parseObject(value);
|
||||
return response.getString("access_token");
|
||||
}
|
||||
// 微信获取凭证接口
|
||||
String apiUrl = "https://api.weixin.qq.com/cgi-bin/token";
|
||||
// 组装url参数
|
||||
String url = apiUrl.concat("?grant_type=client_credential").concat("&appid=").concat(setting.getString("appId")).concat("&secret=").concat(setting.getString("appSecret"));
|
||||
// 执行get请求
|
||||
String result = HttpUtil.get(url);
|
||||
// 解析access_token
|
||||
JSONObject response = JSON.parseObject(result);
|
||||
if (response.getString("access_token") != null) {
|
||||
// 存入缓存
|
||||
redisTemplate.opsForValue().set(key, result,7000L, TimeUnit.SECONDS);
|
||||
return response.getString("access_token");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@ApiOperation("获取微信openId")
|
||||
@PostMapping("/getWxOpenId")
|
||||
public ApiResult<?> getWxOpenId(@RequestBody UserParam userParam) {
|
||||
final User loginUser = getLoginUser();
|
||||
if(loginUser.getUsername().equals("www")){
|
||||
return fail("游客");
|
||||
}
|
||||
String apiUrl = "https://api.weixin.qq.com/sns/jscode2session";
|
||||
final HashMap<String, Object> map = new HashMap<>();
|
||||
final JSONObject setting = settingService.getBySettingKey("mp-weixin");
|
||||
final String appId = setting.getString("appId");
|
||||
final String appSecret = setting.getString("appSecret");
|
||||
map.put("appid",appId);
|
||||
map.put("secret",appSecret);
|
||||
map.put("js_code",userParam.getCode());
|
||||
map.put("grant_type","authorization_code");
|
||||
final String response = HttpUtil.get(apiUrl,map);
|
||||
System.out.println("response = " + response);
|
||||
final JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
|
||||
// 保存openid
|
||||
final List<UserOauth> list = userOauthService.list(new LambdaQueryWrapper<UserOauth>().eq(UserOauth::getUserId, loginUser.getUserId()).eq(UserOauth::getOauthType,"MP-WEIXIN"));
|
||||
if (CollectionUtils.isEmpty(list)) {
|
||||
final UserOauth userOauth = new UserOauth();
|
||||
userOauth.setUserId(getLoginUserId());
|
||||
userOauth.setOauthId(jsonObject.getString("openid"));
|
||||
userOauth.setUnionid(jsonObject.getString("unionid"));
|
||||
userOauth.setOauthType("MP-WEIXIN");
|
||||
userOauthService.save(userOauth);
|
||||
return success("保存openid成功",jsonObject);
|
||||
}
|
||||
return fail("更新失败",null);
|
||||
}
|
||||
|
||||
@ApiOperation("获取微信小程序码")
|
||||
@GetMapping("/getQRCode")
|
||||
public ApiResult<?> getQRCode() {
|
||||
String apiUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + getAccessToken();
|
||||
final HashMap<String, Object> map = new HashMap<>();
|
||||
map.put("path","pages/flash/index?user_id="+getLoginUserId());
|
||||
// map.put("env_version","trial");
|
||||
// 获取图片 Buffer
|
||||
byte[] qrCode = HttpRequest.post(apiUrl)
|
||||
.body(JSON.toJSONString(map))
|
||||
.execute().bodyBytes();
|
||||
|
||||
// 保存的文件名称
|
||||
final String fileName = CommonUtil.randomUUID8().concat(".png");
|
||||
// 保存路径
|
||||
String filePath = getUploadDir().concat("qrcode/") + fileName;
|
||||
File file = FileUtil.writeBytes(qrCode, filePath);
|
||||
if(file != null){
|
||||
return success(config.getFileServer().concat("/qrcode/").concat(fileName));
|
||||
}
|
||||
return fail("获取失败",null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传位置(服务器)
|
||||
*/
|
||||
private String getUploadDir() {
|
||||
return config.getUploadPath() + "file/";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 访问凭证管理
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2023-05-16 19:19:55
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@ApiModel(value = "AccessKey对象", description = "访问凭证管理")
|
||||
@TableName("sys_access_key")
|
||||
public class AccessKey implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "字典项id")
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@ApiModelProperty(value = "字典id")
|
||||
private String accessKey;
|
||||
|
||||
@ApiModelProperty(value = "字典项标识")
|
||||
private String accessSecret;
|
||||
|
||||
@ApiModelProperty(value = "排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@ApiModelProperty(value = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty(value = "修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
}
|
||||
34
src/main/java/com/gxwebsoft/common/system/entity/Cache.java
Normal file
34
src/main/java/com/gxwebsoft/common/system/entity/Cache.java
Normal file
@@ -0,0 +1,34 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 缓存管理
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2022-11-19 13:54:27
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@ApiModel(value = "Setting对象", description = "缓存管理")
|
||||
public class Cache implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "key")
|
||||
private String key;
|
||||
|
||||
@ApiModelProperty(value = "设置内容(json格式)")
|
||||
private String content;
|
||||
|
||||
@ApiModelProperty(value = "过期时间(秒)")
|
||||
private Long expireTime;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
}
|
||||
158
src/main/java/com/gxwebsoft/common/system/entity/Company.java
Normal file
158
src/main/java/com/gxwebsoft/common/system/entity/Company.java
Normal file
@@ -0,0 +1,158 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import io.swagger.models.auth.In;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 企业信息
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2023-05-27 14:57:34
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@ApiModel(value = "Company对象", description = "企业信息")
|
||||
@TableName("sys_company")
|
||||
public class Company implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "企业id")
|
||||
@TableId(value = "company_id", type = IdType.AUTO)
|
||||
private Integer companyId;
|
||||
|
||||
@ApiModelProperty(value = "企业简称")
|
||||
private String shortName;
|
||||
|
||||
@ApiModelProperty(value = "企业全称")
|
||||
private String companyName;
|
||||
|
||||
@ApiModelProperty(value = "企业标识")
|
||||
private String companyCode;
|
||||
|
||||
@ApiModelProperty(value = "企业类型")
|
||||
private String companyType;
|
||||
|
||||
@ApiModelProperty(value = "企业类型 多选")
|
||||
private String companyTypeMultiple;
|
||||
|
||||
@ApiModelProperty(value = "应用标识")
|
||||
private String companyLogo;
|
||||
|
||||
@ApiModelProperty(value = "企业域名")
|
||||
private String domain;
|
||||
|
||||
@ApiModelProperty(value = "联系电话")
|
||||
private String phone;
|
||||
|
||||
@ApiModelProperty(value = "企业法人")
|
||||
private String businessEntity;
|
||||
|
||||
@ApiModelProperty(value = "发票抬头")
|
||||
@TableField("Invoice_header")
|
||||
private String invoiceHeader;
|
||||
|
||||
@ApiModelProperty(value = "服务开始时间")
|
||||
private Date startTime;
|
||||
|
||||
@ApiModelProperty(value = "服务到期时间")
|
||||
private Date expirationTime;
|
||||
|
||||
@ApiModelProperty(value = "应用版本 10体验版 20授权版 30旗舰版")
|
||||
private Integer version;
|
||||
|
||||
@ApiModelProperty(value = "企业成员(当前)")
|
||||
private Integer users;
|
||||
|
||||
@ApiModelProperty(value = "成员数量(上限)")
|
||||
private Integer members;
|
||||
|
||||
@ApiModelProperty(value = "存储空间")
|
||||
private Long storage;
|
||||
|
||||
@ApiModelProperty(value = "存储空间(上限)")
|
||||
private Long storageMax;
|
||||
|
||||
@ApiModelProperty(value = "行业类型(父级)")
|
||||
private String industryParent;
|
||||
|
||||
@ApiModelProperty(value = "行业类型(子级)")
|
||||
private String industryChild;
|
||||
|
||||
@ApiModelProperty(value = "部门数量")
|
||||
private Integer departments;
|
||||
|
||||
@ApiModelProperty(value = "所在国家")
|
||||
private String country;
|
||||
|
||||
@ApiModelProperty(value = "所在省份")
|
||||
private String province;
|
||||
|
||||
@ApiModelProperty(value = "所在城市")
|
||||
private String city;
|
||||
|
||||
@ApiModelProperty(value = "所在辖区")
|
||||
private String region;
|
||||
|
||||
@ApiModelProperty(value = "街道地址")
|
||||
private String address;
|
||||
|
||||
@ApiModelProperty(value = "经度")
|
||||
private String longitude;
|
||||
|
||||
@ApiModelProperty(value = "纬度")
|
||||
private String latitude;
|
||||
|
||||
@ApiModelProperty(value = "备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty(value = "是否实名认证")
|
||||
private Integer authentication;
|
||||
|
||||
@ApiModelProperty(value = "状态")
|
||||
private Integer status;
|
||||
|
||||
@ApiModelProperty(value = "排序")
|
||||
private Integer sortNumber;
|
||||
|
||||
@ApiModelProperty(value = "用户ID")
|
||||
private Integer userId;
|
||||
|
||||
@ApiModelProperty(value = "是否含税")
|
||||
private Boolean isTax;
|
||||
|
||||
@ApiModelProperty(value = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty(value = "修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty(value = "是否默认企业主体")
|
||||
private Boolean authoritative;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty(value = "租户名称")
|
||||
@TableField(exist = false)
|
||||
private String tenantName;
|
||||
|
||||
@ApiModelProperty(value = "租户编号")
|
||||
@TableField(exist = false)
|
||||
private String tenantCode;
|
||||
|
||||
@ApiModelProperty(value = "昵称")
|
||||
@TableField(exist = false)
|
||||
private String nickname;
|
||||
|
||||
}
|
||||
57
src/main/java/com/gxwebsoft/common/system/entity/Dict.java
Normal file
57
src/main/java/com/gxwebsoft/common/system/entity/Dict.java
Normal file
@@ -0,0 +1,57 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 字典
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-14 11:29:03
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "字典(业务类)")
|
||||
@TableName("sys_dict")
|
||||
public class Dict implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "字典id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer dictId;
|
||||
|
||||
@ApiModelProperty(value = "字典标识")
|
||||
private String dictCode;
|
||||
|
||||
@ApiModelProperty(value = "字典名称")
|
||||
private String dictName;
|
||||
|
||||
@ApiModelProperty(value = "排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@ApiModelProperty(value = "备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty(value = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty(value = "修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty(value = "字典项列表")
|
||||
@TableField(exist = false)
|
||||
private Set<Set<String>> items;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 字典数据
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-14 11:29:04
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "字典数据(业务类)")
|
||||
@TableName("sys_dict_data")
|
||||
public class DictData implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "字典数据id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer dictDataId;
|
||||
|
||||
@ApiModelProperty(value = "字典id")
|
||||
private Integer dictId;
|
||||
|
||||
@ApiModelProperty(value = "字典数据标识")
|
||||
private String dictDataCode;
|
||||
|
||||
@ApiModelProperty(value = "字典数据名称")
|
||||
private String dictDataName;
|
||||
|
||||
@ApiModelProperty(value = "排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@ApiModelProperty(value = "备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty(value = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty(value = "修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty(value = "字典代码")
|
||||
@TableField(exist = false)
|
||||
private String dictCode;
|
||||
|
||||
@ApiModelProperty(value = "字典名称")
|
||||
@TableField(exist = false)
|
||||
private String dictName;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
|
||||
import java.util.Date;
|
||||
import java.io.Serializable;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 字典
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-14 11:29:03
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "字典(系统类)")
|
||||
@TableName("sys_dictionary")
|
||||
public class Dictionary implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "字典id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer dictId;
|
||||
|
||||
@ApiModelProperty(value = "字典标识")
|
||||
private String dictCode;
|
||||
|
||||
@ApiModelProperty(value = "字典名称")
|
||||
private String dictName;
|
||||
|
||||
@ApiModelProperty(value = "排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@ApiModelProperty(value = "备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty(value = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty(value = "修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
|
||||
import java.util.Date;
|
||||
import java.io.Serializable;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 字典数据
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-14 11:29:04
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "字典数据(系统类)")
|
||||
@TableName("sys_dictionary_data")
|
||||
public class DictionaryData implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "字典数据id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer dictDataId;
|
||||
|
||||
@ApiModelProperty(value = "字典id")
|
||||
private Integer dictId;
|
||||
|
||||
@ApiModelProperty(value = "字典数据标识")
|
||||
private String dictDataCode;
|
||||
|
||||
@ApiModelProperty(value = "字典数据名称")
|
||||
private String dictDataName;
|
||||
|
||||
@ApiModelProperty(value = "排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@ApiModelProperty(value = "备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty(value = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty(value = "修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty(value = "字典代码")
|
||||
@TableField(exist = false)
|
||||
private String dictCode;
|
||||
|
||||
@ApiModelProperty(value = "字典名称")
|
||||
@TableField(exist = false)
|
||||
private String dictName;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 邮件发送记录
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-08-29 12:36:35
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "邮件发送记录")
|
||||
@TableName("sys_email_record")
|
||||
public class EmailRecord implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty("主键id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@ApiModelProperty("邮件标题")
|
||||
private String title;
|
||||
|
||||
@ApiModelProperty("邮件内容")
|
||||
private String content;
|
||||
|
||||
@ApiModelProperty("收件邮箱")
|
||||
private String receiver;
|
||||
|
||||
@ApiModelProperty("发件邮箱")
|
||||
private String sender;
|
||||
|
||||
@ApiModelProperty("创建人")
|
||||
private Integer createUserId;
|
||||
|
||||
@ApiModelProperty("备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty("创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty("修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 文件上传记录
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-08-29 12:36:32
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "文件上传记录")
|
||||
@TableName("sys_file_record")
|
||||
public class FileRecord implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty("主键id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@ApiModelProperty("分组ID")
|
||||
private Integer groupId;
|
||||
|
||||
@ApiModelProperty("文件名称")
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty("文件存储路径")
|
||||
private String path;
|
||||
|
||||
@ApiModelProperty("文件大小")
|
||||
private Long length;
|
||||
|
||||
@ApiModelProperty("文件类型")
|
||||
private String contentType;
|
||||
|
||||
@ApiModelProperty("备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty("创建人")
|
||||
private Integer createUserId;
|
||||
|
||||
@ApiModelProperty("是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty("商户编号")
|
||||
private String merchantCode;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty("创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty("修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty("文件访问地址")
|
||||
@TableField(exist = false)
|
||||
private String url;
|
||||
|
||||
@ApiModelProperty("文件缩略图访问地址")
|
||||
@TableField(exist = false)
|
||||
private String thumbnail;
|
||||
|
||||
@ApiModelProperty("文件下载地址")
|
||||
@TableField(exist = false)
|
||||
private String downloadUrl;
|
||||
|
||||
@ApiModelProperty("创建人账号")
|
||||
@TableField(exist = false)
|
||||
private String createUsername;
|
||||
|
||||
@ApiModelProperty("创建人名称")
|
||||
@TableField(exist = false)
|
||||
private String createNickname;
|
||||
|
||||
@ApiModelProperty("用户头像")
|
||||
@TableField(exist = false)
|
||||
private String avatar;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 租户
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-08-28 11:31:06
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "实体")
|
||||
public class KVEntity<K,V> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
protected K k;
|
||||
protected V v;
|
||||
public KVEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public KVEntity(K k, V v) {
|
||||
super();
|
||||
this.k = k;
|
||||
this.v = v;
|
||||
}
|
||||
|
||||
public static <K, V> KVEntity<K, V> build(K k, V v) {
|
||||
return new KVEntity<>(k, v);
|
||||
}
|
||||
|
||||
public K getK() {
|
||||
return k;
|
||||
}
|
||||
|
||||
public void setK(K k) {
|
||||
this.k = k;
|
||||
}
|
||||
|
||||
public V getV() {
|
||||
return v;
|
||||
}
|
||||
|
||||
public void setV(V v) {
|
||||
this.v = v;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 登录日志
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:41
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "登录日志")
|
||||
@TableName("sys_login_record")
|
||||
public class LoginRecord implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public static final int TYPE_LOGIN = 0; // 登录成功
|
||||
public static final int TYPE_ERROR = 1; // 登录失败
|
||||
public static final int TYPE_LOGOUT = 2; // 退出登录
|
||||
public static final int TYPE_REFRESH = 3; // 续签token
|
||||
public static final int TYPE_REGISTER = 4; // 注册成功
|
||||
|
||||
@ApiModelProperty("主键id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@ApiModelProperty("用户账号")
|
||||
private String username;
|
||||
|
||||
@ApiModelProperty("操作系统")
|
||||
private String os;
|
||||
|
||||
@ApiModelProperty("设备名称")
|
||||
private String device;
|
||||
|
||||
@ApiModelProperty("浏览器类型")
|
||||
private String browser;
|
||||
|
||||
@ApiModelProperty("ip地址")
|
||||
private String ip;
|
||||
|
||||
@ApiModelProperty("操作类型, 0登录成功, 1登录失败, 2退出登录, 3续签token")
|
||||
private Integer loginType;
|
||||
|
||||
@ApiModelProperty("备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty("操作时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty("修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty("用户id")
|
||||
@TableField(exist = false)
|
||||
private Integer userId;
|
||||
|
||||
@ApiModelProperty("用户昵称")
|
||||
@TableField(exist = false)
|
||||
private String nickname;
|
||||
|
||||
}
|
||||
84
src/main/java/com/gxwebsoft/common/system/entity/Menu.java
Normal file
84
src/main/java/com/gxwebsoft/common/system/entity/Menu.java
Normal file
@@ -0,0 +1,84 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 菜单
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:17
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "菜单")
|
||||
@TableName("sys_menu")
|
||||
public class Menu implements GrantedAuthority {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public static final int TYPE_MENU = 0; // 菜单类型
|
||||
public static final int TYPE_BTN = 1; // 按钮类型
|
||||
|
||||
@ApiModelProperty("菜单id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer menuId;
|
||||
|
||||
@ApiModelProperty("上级id, 0是顶级")
|
||||
private Integer parentId;
|
||||
|
||||
@ApiModelProperty("菜单名称")
|
||||
private String title;
|
||||
|
||||
@ApiModelProperty("菜单路由地址")
|
||||
private String path;
|
||||
|
||||
@ApiModelProperty("菜单组件地址")
|
||||
private String component;
|
||||
|
||||
@ApiModelProperty("菜单类型, 0菜单, 1按钮")
|
||||
private Integer menuType;
|
||||
|
||||
@ApiModelProperty("排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@ApiModelProperty("权限标识")
|
||||
private String authority;
|
||||
|
||||
@ApiModelProperty("菜单图标")
|
||||
private String icon;
|
||||
|
||||
@ApiModelProperty("是否隐藏, 0否, 1是(仅注册路由不显示左侧菜单)")
|
||||
private Integer hide;
|
||||
|
||||
@ApiModelProperty("路由元信息")
|
||||
private String meta;
|
||||
|
||||
@ApiModelProperty("是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty("关联应用")
|
||||
private Integer appId;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty("创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty("修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty("子菜单")
|
||||
@TableField(exist = false)
|
||||
private List<Menu> children;
|
||||
|
||||
@ApiModelProperty("角色权限树选中状态")
|
||||
@TableField(exist = false)
|
||||
private Boolean checked;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 操作日志
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:33
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "操作日志")
|
||||
@TableName("sys_operation_record")
|
||||
public class OperationRecord implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty("主键id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@ApiModelProperty("用户id")
|
||||
private Integer userId;
|
||||
|
||||
@ApiModelProperty("操作模块")
|
||||
private String module;
|
||||
|
||||
@ApiModelProperty("操作功能")
|
||||
private String description;
|
||||
|
||||
@ApiModelProperty("请求地址")
|
||||
private String url;
|
||||
|
||||
@ApiModelProperty("请求方式")
|
||||
private String requestMethod;
|
||||
|
||||
@ApiModelProperty("调用方法")
|
||||
private String method;
|
||||
|
||||
@ApiModelProperty("请求参数")
|
||||
private String params;
|
||||
|
||||
@ApiModelProperty("返回结果")
|
||||
private String result;
|
||||
|
||||
@ApiModelProperty("异常信息")
|
||||
private String error;
|
||||
|
||||
@ApiModelProperty("备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty("消耗时间, 单位毫秒")
|
||||
private Long spendTime;
|
||||
|
||||
@ApiModelProperty("操作系统")
|
||||
private String os;
|
||||
|
||||
@ApiModelProperty("设备名称")
|
||||
private String device;
|
||||
|
||||
@ApiModelProperty("浏览器类型")
|
||||
private String browser;
|
||||
|
||||
@ApiModelProperty("ip地址")
|
||||
private String ip;
|
||||
|
||||
@ApiModelProperty("状态, 0成功, 1异常")
|
||||
private Integer status;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty("操作时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty("修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty("用户昵称")
|
||||
@TableField(exist = false)
|
||||
private String nickname;
|
||||
|
||||
@ApiModelProperty("用户账号")
|
||||
@TableField(exist = false)
|
||||
private String username;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
|
||||
import java.util.Date;
|
||||
import java.io.Serializable;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 组织机构
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-14 11:29:04
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "组织机构")
|
||||
@TableName("sys_organization")
|
||||
public class Organization implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "机构id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer organizationId;
|
||||
|
||||
@ApiModelProperty(value = "上级id, 0是顶级")
|
||||
private Integer parentId;
|
||||
|
||||
@ApiModelProperty(value = "机构名称")
|
||||
private String organizationName;
|
||||
|
||||
@ApiModelProperty(value = "机构全称")
|
||||
private String organizationFullName;
|
||||
|
||||
@ApiModelProperty(value = "机构代码")
|
||||
private String organizationCode;
|
||||
|
||||
@ApiModelProperty(value = "机构类型, 字典标识")
|
||||
private String organizationType;
|
||||
|
||||
@ApiModelProperty(value = "负责人id")
|
||||
private Integer leaderId;
|
||||
|
||||
@ApiModelProperty(value = "排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@ApiModelProperty(value = "备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty(value = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty(value = "修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty(value = "机构类型名称")
|
||||
@TableField(exist = false)
|
||||
private String organizationTypeName;
|
||||
|
||||
@ApiModelProperty(value = "负责人姓名")
|
||||
@TableField(exist = false)
|
||||
private String leaderNickname;
|
||||
|
||||
@ApiModelProperty(value = "负责人账号")
|
||||
@TableField(exist = false)
|
||||
private String leaderUsername;
|
||||
|
||||
}
|
||||
141
src/main/java/com/gxwebsoft/common/system/entity/Plug.java
Normal file
141
src/main/java/com/gxwebsoft/common/system/entity/Plug.java
Normal file
@@ -0,0 +1,141 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 插件扩展
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2023-05-18 11:57:37
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@ApiModel(value = "Plug对象", description = "插件扩展")
|
||||
@TableName("sys_plug")
|
||||
public class Plug implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public static final int TYPE_MENU = 0; // 菜单类型
|
||||
public static final int TYPE_BTN = 1; // 按钮类型
|
||||
|
||||
@ApiModelProperty(value = "插件id")
|
||||
@TableId(value = "plug_id", type = IdType.AUTO)
|
||||
private Integer plugId;
|
||||
|
||||
@ApiModelProperty(value = "菜单ID")
|
||||
private Integer menuId;
|
||||
|
||||
@ApiModelProperty(value = "上级id, 0是顶级")
|
||||
private Integer parentId;
|
||||
|
||||
@ApiModelProperty(value = "菜单名称")
|
||||
private String title;
|
||||
|
||||
@ApiModelProperty(value = "菜单路由地址")
|
||||
private String path;
|
||||
|
||||
@ApiModelProperty(value = "菜单组件地址, 目录可为空")
|
||||
private String component;
|
||||
|
||||
@ApiModelProperty(value = "类型, 0菜单, 1按钮")
|
||||
private Integer menuType;
|
||||
|
||||
@ApiModelProperty(value = "排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@ApiModelProperty(value = "权限标识")
|
||||
private String authority;
|
||||
|
||||
@ApiModelProperty(value = "打开位置")
|
||||
private String target;
|
||||
|
||||
@ApiModelProperty(value = "菜单图标")
|
||||
private String icon;
|
||||
|
||||
@ApiModelProperty(value = "图标颜色")
|
||||
private String color;
|
||||
|
||||
@ApiModelProperty(value = "是否隐藏, 0否, 1是(仅注册路由不显示在左侧菜单)")
|
||||
private Integer hide;
|
||||
|
||||
@ApiModelProperty(value = "菜单侧栏选中的path")
|
||||
private String active;
|
||||
|
||||
@ApiModelProperty(value = "其它路由元信息")
|
||||
private String meta;
|
||||
|
||||
@ApiModelProperty(value = "插件描述")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty(value = "插件详情")
|
||||
private String content;
|
||||
|
||||
@ApiModelProperty("评分")
|
||||
private BigDecimal score;
|
||||
|
||||
@ApiModelProperty("插件价格")
|
||||
private BigDecimal price;
|
||||
|
||||
@ApiModelProperty("浏览次数")
|
||||
private Integer clicks;
|
||||
|
||||
@ApiModelProperty("安装次数")
|
||||
private Integer installs;
|
||||
|
||||
@ApiModelProperty(value = "关联应用ID")
|
||||
private Integer appId;
|
||||
|
||||
@ApiModelProperty(value = "用户ID")
|
||||
private Integer userId;
|
||||
|
||||
@ApiModelProperty(value = "状态")
|
||||
private Integer status;
|
||||
|
||||
@ApiModelProperty(value = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "商户编码")
|
||||
private String merchantCode;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty(value = "修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty("子菜单")
|
||||
@TableField(exist = false)
|
||||
private List<Menu> children;
|
||||
|
||||
@ApiModelProperty("角色权限树选中状态")
|
||||
@TableField(exist = false)
|
||||
private Boolean checked;
|
||||
|
||||
@ApiModelProperty("租户名称")
|
||||
@TableField(exist = false)
|
||||
private String tenantName;
|
||||
|
||||
@ApiModelProperty("企业名称")
|
||||
@TableField(exist = false)
|
||||
private String companyName;
|
||||
|
||||
@ApiModelProperty("企业简称")
|
||||
@TableField(exist = false)
|
||||
private String shortName;
|
||||
|
||||
@ApiModelProperty("企业域名")
|
||||
@TableField(exist = false)
|
||||
private String domain;
|
||||
}
|
||||
53
src/main/java/com/gxwebsoft/common/system/entity/Role.java
Normal file
53
src/main/java/com/gxwebsoft/common/system/entity/Role.java
Normal file
@@ -0,0 +1,53 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 角色
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:01
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "角色")
|
||||
@TableName("sys_role")
|
||||
public class Role implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty("角色id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer roleId;
|
||||
|
||||
@ApiModelProperty("角色标识")
|
||||
private String roleCode;
|
||||
|
||||
@ApiModelProperty("角色名称")
|
||||
private String roleName;
|
||||
|
||||
@ApiModelProperty("备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty("是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty("创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty("修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty(hidden = true)
|
||||
@TableField(exist = false)
|
||||
private Integer userId;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 角色菜单
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:54
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "角色权限")
|
||||
@TableName("sys_role_menu")
|
||||
public class RoleMenu implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty("主键id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@ApiModelProperty("角色id")
|
||||
private Integer roleId;
|
||||
|
||||
@ApiModelProperty("菜单id")
|
||||
private Integer menuId;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty("创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty("修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 系统设置
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2022-11-19 13:54:27
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@ApiModel(value = "Setting对象", description = "系统设置")
|
||||
@TableName("sys_setting")
|
||||
public class Setting implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "id")
|
||||
@TableId(value = "setting_id", type = IdType.AUTO)
|
||||
private Integer settingId;
|
||||
|
||||
@ApiModelProperty(value = "设置项标示")
|
||||
private String settingKey;
|
||||
|
||||
@ApiModelProperty(value = "设置内容(json格式)")
|
||||
private String content;
|
||||
|
||||
@ApiModelProperty(value = "排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@ApiModelProperty(value = "备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty(value = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty(value = "修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty(value = "修改租户名称")
|
||||
@TableField(exist = false)
|
||||
private String tenantName;
|
||||
|
||||
}
|
||||
59
src/main/java/com/gxwebsoft/common/system/entity/Tenant.java
Normal file
59
src/main/java/com/gxwebsoft/common/system/entity/Tenant.java
Normal file
@@ -0,0 +1,59 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import java.time.LocalDateTime;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import java.io.Serializable;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* 租户
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2023-07-17 17:49:53
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@ApiModel(value = "Tenant对象", description = "租户")
|
||||
@TableName("sys_tenant")
|
||||
public class Tenant implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
@TableId(value = "tenant_id", type = IdType.AUTO)
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty(value = "租户名称")
|
||||
private String tenantName;
|
||||
|
||||
@ApiModelProperty(value = "租户编号")
|
||||
private String tenantCode;
|
||||
|
||||
@ApiModelProperty(value = "logo")
|
||||
private String logo;
|
||||
|
||||
@ApiModelProperty(value = "备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty(value = "状态")
|
||||
private Integer status;
|
||||
|
||||
@ApiModelProperty(value = "用户ID")
|
||||
private Integer userId;
|
||||
|
||||
@ApiModelProperty(value = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@ApiModelProperty(value = "修改时间")
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
}
|
||||
317
src/main/java/com/gxwebsoft/common/system/entity/User.java
Normal file
317
src/main/java/com/gxwebsoft/common/system/entity/User.java
Normal file
@@ -0,0 +1,317 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import cn.hutool.core.util.DesensitizedUtil;
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.gxwebsoft.love.entity.UserPlanEquity;
|
||||
import com.gxwebsoft.love.entity.UserProfile;
|
||||
import com.gxwebsoft.oa.entity.App;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:13
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "用户")
|
||||
@TableName("sys_user")
|
||||
public class User implements UserDetails {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty("用户id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer userId;
|
||||
|
||||
@ApiModelProperty("用户类型, 0普通用户 6开发者 10企业用户")
|
||||
private Integer type;
|
||||
|
||||
@ApiModelProperty("用户编码")
|
||||
private String userCode;
|
||||
|
||||
@ApiModelProperty("账号")
|
||||
private String username;
|
||||
|
||||
@ApiModelProperty("密码")
|
||||
private String password;
|
||||
|
||||
@ApiModelProperty("昵称")
|
||||
private String nickname;
|
||||
|
||||
@ApiModelProperty("头像")
|
||||
private String avatar;
|
||||
|
||||
@ApiModelProperty("头像")
|
||||
private String bgImage;
|
||||
|
||||
@ApiModelProperty("性别, 字典标识")
|
||||
private String sex;
|
||||
|
||||
@ApiModelProperty("手机号")
|
||||
private String phone;
|
||||
|
||||
@ApiModelProperty("邮箱")
|
||||
private String email;
|
||||
|
||||
@ApiModelProperty("职务")
|
||||
private String position;
|
||||
|
||||
@ApiModelProperty("邮箱是否验证, 0否, 1是")
|
||||
private Integer emailVerified;
|
||||
|
||||
@ApiModelProperty("别名")
|
||||
private String alias;
|
||||
|
||||
@ApiModelProperty("真实姓名")
|
||||
private String realName;
|
||||
|
||||
@ApiModelProperty("身份证号")
|
||||
private String idCard;
|
||||
|
||||
@ApiModelProperty("出生日期")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private Date birthday;
|
||||
|
||||
@ApiModelProperty(value = "年龄")
|
||||
private Integer age;
|
||||
|
||||
@ApiModelProperty("所在国家")
|
||||
private String country;
|
||||
|
||||
@ApiModelProperty(value = "所在省份")
|
||||
private String province;
|
||||
|
||||
@ApiModelProperty(value = "所在城市")
|
||||
private String city;
|
||||
|
||||
@ApiModelProperty(value = "所在辖区")
|
||||
private String region;
|
||||
|
||||
@ApiModelProperty("街道地址")
|
||||
private String address;
|
||||
|
||||
@ApiModelProperty(value = "经度")
|
||||
private String longitude;
|
||||
|
||||
@ApiModelProperty(value = "纬度")
|
||||
private String latitude;
|
||||
|
||||
@ApiModelProperty("用户可用余额")
|
||||
private BigDecimal balance;
|
||||
|
||||
@ApiModelProperty("用户可用积分")
|
||||
private Integer points;
|
||||
|
||||
@ApiModelProperty("用户总支付的金额")
|
||||
private String payMoney;
|
||||
|
||||
@ApiModelProperty("实际消费的金额(不含退款)")
|
||||
private String expendMoney;
|
||||
|
||||
@ApiModelProperty("会员等级ID")
|
||||
private Integer gradeId;
|
||||
|
||||
@ApiModelProperty("个人简介")
|
||||
private String introduction;
|
||||
|
||||
@ApiModelProperty("机构ID")
|
||||
private Integer organizationId;
|
||||
|
||||
@ApiModelProperty("客户ID")
|
||||
private Integer customerId;
|
||||
|
||||
@ApiModelProperty("企业ID")
|
||||
private Integer companyId;
|
||||
|
||||
@ApiModelProperty("注册来源客户端")
|
||||
private String platform;
|
||||
|
||||
@ApiModelProperty("兴趣爱好")
|
||||
private String interest;
|
||||
|
||||
@ApiModelProperty("身高")
|
||||
private String height;
|
||||
|
||||
@ApiModelProperty("体重")
|
||||
private String weight;
|
||||
|
||||
@ApiModelProperty("学历")
|
||||
private String education;
|
||||
|
||||
@ApiModelProperty("月薪")
|
||||
private String monthlyPay;
|
||||
|
||||
@ApiModelProperty("是否下线会员")
|
||||
private Integer offline;
|
||||
|
||||
@ApiModelProperty("关注数")
|
||||
private Integer followers;
|
||||
|
||||
@ApiModelProperty("粉丝数")
|
||||
private Integer fans;
|
||||
|
||||
@ApiModelProperty("获赞数")
|
||||
private Integer likes;
|
||||
|
||||
@ApiModelProperty("评论数")
|
||||
private Integer commentNumbers;
|
||||
|
||||
@ApiModelProperty("是否推荐")
|
||||
private Integer recommend;
|
||||
|
||||
@ApiModelProperty("备注")
|
||||
private String comments;
|
||||
|
||||
@ApiModelProperty("状态, 0正常, 1冻结")
|
||||
private Integer status;
|
||||
|
||||
@ApiModelProperty("是否删除, 0否, 1是")
|
||||
// @TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty(value = "租户名称")
|
||||
@TableField(exist = false)
|
||||
private String tenantName;
|
||||
|
||||
@ApiModelProperty(value = "最后结算时间")
|
||||
private Date settlementTime;
|
||||
|
||||
@ApiModelProperty("注册时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty("修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty("公司名称")
|
||||
private String companyName;
|
||||
|
||||
@ApiModelProperty("是否已实名认证")
|
||||
private Integer certification;
|
||||
|
||||
@ApiModelProperty("机构名称")
|
||||
@TableField(exist = false)
|
||||
private String organizationName;
|
||||
|
||||
@ApiModelProperty("性别名称")
|
||||
@TableField(exist = false)
|
||||
private String sexName;
|
||||
|
||||
@ApiModelProperty("会员等级")
|
||||
@TableField(exist = false)
|
||||
private String gradeName;
|
||||
|
||||
@ApiModelProperty("默认注册的角色ID")
|
||||
@TableField(exist = false)
|
||||
private Integer roleId;
|
||||
|
||||
@ApiModelProperty("角色列表")
|
||||
@TableField(exist = false)
|
||||
private List<Role> roles;
|
||||
|
||||
@ApiModelProperty("详细资料")
|
||||
@TableField(exist = false)
|
||||
private UserProfile userProfile;
|
||||
|
||||
@ApiModelProperty("权限列表")
|
||||
@TableField(exist = false)
|
||||
private List<Menu> authorities;
|
||||
|
||||
@ApiModelProperty("微信凭证")
|
||||
@TableField(exist = false)
|
||||
private String code;
|
||||
|
||||
@ApiModelProperty("推荐人ID")
|
||||
@TableField(exist = false)
|
||||
private Integer dealerId;
|
||||
|
||||
@ApiModelProperty("微信openid")
|
||||
@TableField(exist = false)
|
||||
private String openid;
|
||||
|
||||
@ApiModelProperty("微信unionid")
|
||||
@TableField(exist = false)
|
||||
private String unionid;
|
||||
|
||||
@ApiModelProperty("所属商户的编号")
|
||||
@TableField(exist = false)
|
||||
private String merchantCode;
|
||||
|
||||
@ApiModelProperty("所属商户名称")
|
||||
@TableField(exist = false)
|
||||
private String merchantName;
|
||||
|
||||
@ApiModelProperty("ico文件")
|
||||
@TableField(exist = false)
|
||||
private String logo;
|
||||
|
||||
@ApiModelProperty("创建的应用数量")
|
||||
@TableField(exist = false)
|
||||
private Double apps;
|
||||
|
||||
@ApiModelProperty("租户设置信息")
|
||||
@TableField(exist = false)
|
||||
private String setting;
|
||||
|
||||
@ApiModelProperty("手机号(脱敏)")
|
||||
@TableField(exist = false)
|
||||
private String mobile;
|
||||
|
||||
@ApiModelProperty("应用信息")
|
||||
@TableField(exist = false)
|
||||
private App appInfo;
|
||||
|
||||
@ApiModelProperty("企业信息")
|
||||
@TableField(exist = false)
|
||||
private Company companyInfo;
|
||||
|
||||
@ApiModelProperty("权益列表")
|
||||
@TableField(exist = false)
|
||||
private List<UserPlanEquity> userPlanEquityList;
|
||||
|
||||
@ApiModelProperty("系统配置信息")
|
||||
@TableField(exist = false)
|
||||
private Object system;
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return this.status != null && this.status == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
//
|
||||
// public String getRealName(){
|
||||
// return DesensitizedUtil.chineseName(this.realName);
|
||||
// }
|
||||
//
|
||||
// public String getIdCard(){
|
||||
// return DesensitizedUtil.idCardNum(this.idCard,1,2);
|
||||
// }
|
||||
public String getMobile(){
|
||||
return DesensitizedUtil.mobilePhone(this.phone);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* 用户文件
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2022-07-21 14:34:40
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@ApiModel(value = "UserFile对象", description = "用户文件")
|
||||
@TableName("sys_user_file")
|
||||
public class UserFile implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "主键id")
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@ApiModelProperty(value = "用户id")
|
||||
private Integer userId;
|
||||
|
||||
@ApiModelProperty(value = "文件名称")
|
||||
private String name;
|
||||
|
||||
@ApiModelProperty(value = "是否是文件夹, 0否, 1是")
|
||||
private Integer isDirectory;
|
||||
|
||||
@ApiModelProperty(value = "上级id")
|
||||
private Integer parentId;
|
||||
|
||||
@ApiModelProperty(value = "文件路径")
|
||||
private String path;
|
||||
|
||||
@ApiModelProperty(value = "文件大小")
|
||||
private Integer length;
|
||||
|
||||
@ApiModelProperty("文件类型")
|
||||
private String contentType;
|
||||
|
||||
@ApiModelProperty(value = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@ApiModelProperty(value = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty(value = "创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty(value = "修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty("文件访问地址")
|
||||
@TableField(exist = false)
|
||||
private String url;
|
||||
|
||||
@ApiModelProperty("文件缩略图访问地址")
|
||||
@TableField(exist = false)
|
||||
private String thumbnail;
|
||||
|
||||
@ApiModelProperty("文件下载地址")
|
||||
@TableField(exist = false)
|
||||
private String downloadUrl;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.gxwebsoft.common.system.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 用户角色
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-24 16:10:23
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(description = "用户角色")
|
||||
@TableName("sys_user_role")
|
||||
public class UserRole implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty("主键id")
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@ApiModelProperty("用户id")
|
||||
private Integer userId;
|
||||
|
||||
@ApiModelProperty("角色id")
|
||||
private Integer roleId;
|
||||
|
||||
@ApiModelProperty("创建时间")
|
||||
private Date createTime;
|
||||
|
||||
@ApiModelProperty("修改时间")
|
||||
private Date updateTime;
|
||||
|
||||
@ApiModelProperty("角色名称")
|
||||
@TableField(exist = false)
|
||||
private String roleName;
|
||||
|
||||
@ApiModelProperty("租户ID")
|
||||
private Integer tenantId;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.gxwebsoft.common.system.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.gxwebsoft.common.system.entity.AccessKey;
|
||||
import com.gxwebsoft.common.system.param.AccessKeyParam;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 访问凭证管理Mapper
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2023-05-16 19:19:55
|
||||
*/
|
||||
public interface AccessKeyMapper extends BaseMapper<AccessKey> {
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
*
|
||||
* @param page 分页对象
|
||||
* @param param 查询参数
|
||||
* @return List<AccessKey>
|
||||
*/
|
||||
List<AccessKey> selectPageRel(@Param("page") IPage<AccessKey> page,
|
||||
@Param("param") AccessKeyParam param);
|
||||
|
||||
/**
|
||||
* 查询全部
|
||||
*
|
||||
* @param param 查询参数
|
||||
* @return List<User>
|
||||
*/
|
||||
List<AccessKey> selectListRel(@Param("param") AccessKeyParam param);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.gxwebsoft.common.system.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.gxwebsoft.common.system.entity.Company;
|
||||
import com.gxwebsoft.common.system.param.CompanyParam;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 企业信息Mapper
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2023-05-27 14:57:34
|
||||
*/
|
||||
public interface CompanyMapper extends BaseMapper<Company> {
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
*
|
||||
* @param page 分页对象
|
||||
* @param param 查询参数
|
||||
* @return List<Company>
|
||||
*/
|
||||
List<Company> selectPageRel(@Param("page") IPage<Company> page,
|
||||
@Param("param") CompanyParam param);
|
||||
|
||||
/**
|
||||
* 查询全部
|
||||
*
|
||||
* @param param 查询参数
|
||||
* @return List<User>
|
||||
*/
|
||||
List<Company> selectListRel(@Param("param") CompanyParam param);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.gxwebsoft.common.system.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.gxwebsoft.common.system.entity.DictData;
|
||||
import com.gxwebsoft.common.system.param.DictDataParam;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 字典数据Mapper
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-14 11:29:04
|
||||
*/
|
||||
public interface DictDataMapper extends BaseMapper<DictData> {
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
*
|
||||
* @param page 分页对象
|
||||
* @param param 查询参数
|
||||
* @return List<DictData>
|
||||
*/
|
||||
List<DictData> selectPageRel(@Param("page") IPage<DictData> page,
|
||||
@Param("param") DictDataParam param);
|
||||
|
||||
/**
|
||||
* 查询全部
|
||||
*
|
||||
* @param param 查询参数
|
||||
* @return List<DictData>
|
||||
*/
|
||||
List<DictData> selectListRel(@Param("param") DictDataParam param);
|
||||
|
||||
/**
|
||||
* 根据dictCode和dictDataName查询
|
||||
*
|
||||
* @param dictCode 字典标识
|
||||
* @param dictDataName 字典项名称
|
||||
* @return List<DictData>
|
||||
*/
|
||||
List<DictData> getByDictCodeAndName(@Param("dictCode") String dictCode,
|
||||
@Param("dictDataName") String dictDataName);
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user