From 0d3c221d0bba60279458c22807487ad4994f9eca Mon Sep 17 00:00:00 2001 From: bynt Date: Tue, 17 May 2022 18:31:51 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=BC=82=E5=B8=B8=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/baiye/core/base/api/IResultCode.java | 23 ++ .../java/com/baiye/core/base/api/Result.java | 119 +++++++++ .../com/baiye/core/base/api/ResultCode.java | 245 ++++++++++++++++++ .../baiye/core/constant/MessageConstant.java | 103 ++++++++ .../com/baiye/core/constant/WebConstant.java | 151 +++++++++++ .../com/baiye/core/util/RequestUtils.java | 1 - .../com/baiye/core/util/ResponseUtil.java | 57 ++++ .../exception/global/handle/ApiError.java | 2 +- .../main/resources/META-INF/spring.factories | 2 - .../EnableCustomizeFeignClient.java | 2 +- .../EnableCustomizeResourceServer.java | 2 +- .../com/baiye/{ => annotation}/Inner.java | 4 +- ...stomizeWebResponseExceptionTranslator.java | 32 +-- .../java/com/baiye/component/InnerAspect.java | 2 +- .../config/IgnoreUrlPropsConfiguration.java | 54 ++++ .../java/com/baiye/config/PermitUrls.java | 4 +- .../com/baiye/config/RestTemplateConfig.java | 3 +- .../CustomAuthenticationFailureHandler.java | 62 +++++ .../baiye/service/UserDetailsServiceImpl.java | 4 +- .../main/resources/META-INF/spring.factories | 3 +- cdp-iaas/authorization-server/pom.xml | 12 +- .../java/com/baiye/auth/AuthApplication.java | 12 +- .../baiye/auth/config/AuthServerConfig.java | 46 ++-- .../baiye/auth/config/WebSecurityConfig.java | 44 +++- .../auth/controller/LogoutController.java | 11 +- .../auth/controller/OnlineController.java | 7 +- .../auth/service/impl/OnlineServiceImpl.java | 7 +- .../CustomWebRespExceptionTranslator.java | 71 +++++ .../src/main/resources/banner.txt | 19 ++ .../src/main/resources/config/bootstrap.yml | 2 + .../baiye/config/GatewayConfiguration.java | 13 +- .../com/baiye/filter/ValidateCodeFilter.java | 5 +- .../service/impl/ValidateCodeService.java | 12 +- .../src/main/resources/banner.txt | 19 ++ .../src/main/resources/config/application.yml | 4 +- cdp-iaas/pom.xml | 4 +- .../backstage-manger-server-service/pom.xml | 9 + .../com/baiye/SystemServiceApplication.java | 4 +- .../com/baiye/controller/DataController.java | 4 +- .../com/baiye/controller/DeptController.java | 4 +- .../com/baiye/controller/DictController.java | 4 + .../controller/DictDetailController.java | 4 + .../baiye/controller/PictureController.java | 47 ++++ ...serController.java => UserController.java} | 11 +- .../controller/UserDetailsController.java | 8 +- ...ISysUserService.java => IUserService.java} | 8 +- .../baiye/service/impl/DeptServiceImpl.java | 5 +- .../baiye/service/impl/JobServiceImpl.java | 3 +- .../baiye/service/impl/MenuServiceImpl.java | 3 +- ...rServiceImpl.java => UserServiceImpl.java} | 48 +++- .../src/main/resources/banner.txt | 27 +- .../src/main/resources/config/application.yml | 1 + 52 files changed, 1199 insertions(+), 154 deletions(-) create mode 100644 cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/IResultCode.java create mode 100644 cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/Result.java create mode 100644 cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/ResultCode.java create mode 100644 cdp-common/cdp-common-core/src/main/java/com/baiye/core/constant/MessageConstant.java create mode 100644 cdp-common/cdp-common-core/src/main/java/com/baiye/core/constant/WebConstant.java create mode 100644 cdp-common/cdp-common-core/src/main/java/com/baiye/core/util/ResponseUtil.java delete mode 100644 cdp-common/cdp-common-exception/src/main/resources/META-INF/spring.factories rename cdp-common/cdp-common-security/src/main/java/com/baiye/{ => annotation}/EnableCustomizeFeignClient.java (98%) rename cdp-common/cdp-common-security/src/main/java/com/baiye/{ => annotation}/EnableCustomizeResourceServer.java (97%) rename cdp-common/cdp-common-security/src/main/java/com/baiye/{ => annotation}/Inner.java (95%) create mode 100644 cdp-common/cdp-common-security/src/main/java/com/baiye/config/IgnoreUrlPropsConfiguration.java create mode 100644 cdp-common/cdp-common-security/src/main/java/com/baiye/handle/CustomAuthenticationFailureHandler.java create mode 100644 cdp-iaas/authorization-server/src/main/java/com/baiye/auth/translator/CustomWebRespExceptionTranslator.java create mode 100644 cdp-iaas/authorization-server/src/main/resources/banner.txt create mode 100644 cdp-iaas/gateway-server/src/main/resources/banner.txt create mode 100644 cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/PictureController.java rename cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/{SysUserController.java => UserController.java} (97%) rename cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/{ISysUserService.java => IUserService.java} (94%) rename cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/{SysUserServiceImpl.java => UserServiceImpl.java} (90%) diff --git a/cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/IResultCode.java b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/IResultCode.java new file mode 100644 index 0000000..20736ba --- /dev/null +++ b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/IResultCode.java @@ -0,0 +1,23 @@ +package com.baiye.core.base.api; + +/** + * 返回码接口 + * + * @author pangu + */ +public interface IResultCode { + + /** + * 返回码 + * + * @return int + */ + int getCode(); + + /** + * 返回消息 + * + * @return String + */ + String getMsg(); +} diff --git a/cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/Result.java b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/Result.java new file mode 100644 index 0000000..2349636 --- /dev/null +++ b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/Result.java @@ -0,0 +1,119 @@ +package com.baiye.core.base.api; + +import com.baiye.core.constant.MessageConstant; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import lombok.Getter; + +import java.io.Serializable; + +/** + * 统一响应消息报文 + * + * @param  T对象 + * @author pangu + */ +@Data +@Getter +@ApiModel(value = "统一响应消息报文") +public class Result implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "状态码", required = true) + private int code; + + @ApiModelProperty(value = "消息内容", required = true) + private String msg; + + @ApiModelProperty(value = "时间戳", required = true) + private long time; + + @ApiModelProperty(value = "业务数据") + @JsonInclude(JsonInclude.Include.NON_NULL) + private T data; + + private Result() { + this.time = System.currentTimeMillis(); + } + + private Result(IResultCode resultCode) { + this(resultCode, null, resultCode.getMsg()); + } + + private Result(IResultCode resultCode, String msg) { + this(resultCode, null, msg); + } + + private Result(IResultCode resultCode, T data) { + this(resultCode, data, resultCode.getMsg()); + } + + private Result(IResultCode resultCode, T data, String msg) { + this(resultCode.getCode(), data, msg); + } + + private Result(int code, T data, String msg) { + this.code = code; + this.data = data; + this.msg = msg; + this.time = System.currentTimeMillis(); + } + + /** + * 返回状态码 + * + * @param resultCode 状态码 + * @param 泛型标识 + * @return ApiResult + */ + public static Result success(IResultCode resultCode) { + return new Result<>(resultCode); + } + + public static Result success(String msg) { + return new Result<>(ResultCode.SUCCESS, msg); + } + + public static Result success(IResultCode resultCode, String msg) { + return new Result<>(resultCode, msg); + } + + public static Result data(T data) { + return data(data, MessageConstant.DEFAULT_SUCCESS_MESSAGE); + } + + public static Result data(T data, String msg) { + return data(ResultCode.SUCCESS.code, data, msg); + } + + public static Result data(int code, T data, String msg) { + return new Result<>(code, data, data == null ? MessageConstant.DEFAULT_NULL_MESSAGE : msg); + } + + public static Result fail() { + return new Result<>(ResultCode.FAILURE, ResultCode.FAILURE.getMsg()); + } + + public static Result fail(String msg) { + return new Result<>(ResultCode.FAILURE, msg); + } + + public static Result fail(int code, String msg) { + return new Result<>(code, null, msg); + } + + public static Result fail(IResultCode resultCode) { + return new Result<>(resultCode); + } + + public static Result fail(IResultCode resultCode, String msg) { + return new Result<>(resultCode, msg); + } + + public static Result condition(boolean flag) { + return flag ? success(MessageConstant.DEFAULT_SUCCESS_MESSAGE) : fail(MessageConstant.DEFAULT_FAIL_MESSAGE); + } +} diff --git a/cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/ResultCode.java b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/ResultCode.java new file mode 100644 index 0000000..a5de75e --- /dev/null +++ b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/base/api/ResultCode.java @@ -0,0 +1,245 @@ +package com.baiye.core.base.api; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * 返回码实现 + * + * @author pangu + */ + +@Getter +@AllArgsConstructor +public enum ResultCode implements IResultCode { + + /** + * 操作成功 + */ + SUCCESS(200, "操作成功"), + /** + * 业务异常 + */ + FAILURE(400, "业务异常"), + /** + * 服务未找到 + */ + NOT_FOUND(404, "服务未找到"), + /** + * 服务异常 + */ + ERROR(500, "服务异常"), + /** + * Too Many Requests + */ + TOO_MANY_REQUESTS(429, "Too Many Requests"), + + /** + * 服务不可用 + */ + SERVICE_UNAVAILABLE(503, "服务不可用"), + /** + * 参数错误 + */ + GLOBAL_PARAM_ERROR(4000, "参数错误"), + /** + * 获取当前用户失败 + */ + CURRENT_USER_FAIL(10001, "获取当前用户失败"), + /** + * 用户是超级管理员,不可以修改状态 + */ + UPDATE_USER_STATUS(10002, "用户是超级管理员,不可以修改状态"), + /** + * 用户是超级管理员,不可以修改密码 + */ + UPDATE_USER_PASSWORD(10003, "用户是超级管理员,不可以修改密码"), + /** + * 用户未登录,请登陆后进行访问 + */ + USER_NEED_LOGIN(11001, "用户未登录,请登陆后进行访问"), + /** + * 该用户已在其它地方登录 + */ + USER_MAX_LOGIN(11002, "该用户已在其它地方登录"), + /** + * 长时间未操作,自动退出 + */ + USER_LOGIN_TIMEOUT(11003, "长时间未操作,自动退出"), + /** + * 用户被禁11005用 + */ + USER_DISABLED(11004, "用户被禁11005用"), + /** + * 用户被锁定 + */ + USER_LOCKED(11005, "用户被锁定"), + /** + * 用户名或密码错误 + */ + USER_PASSWORD_ERROR(11006, "用户名或密码错误"), + /** + * 用户密码过期 + */ + USER_PASSWORD_EXPIRED(11007, "用户密码过期"), + /** + * 用户账号过期 + */ + USER_ACCOUNT_EXPIRED(11008, "用户账号过期"), + /** + * 没有该用户 + */ + USER_NOT_EXIST(11009, "没有该用户"), + /** + * 用户登录失败 + */ + USER_LOGIN_FAIL(11010, "用户登录失败"), + /** + * 验证码错误 + */ + VERIFY_CODE_ERROR(11011, "验证码错误"), + /** + * 用户已存在 + */ + USER_IS_EXIST(11012, "用户已存在"), + /** + * 无权访问 + */ + NO_AUTHENTICATION(1003006, "无权访问"), + /** + * 角色ID无效 + */ + ROLE_IS_NOT_EXIST(13001, "角色ID无效"), + /** + * 角色代码已存在 + */ + ROLE_IS_EXIST(13002, "角色代码已存在"), + /** + * 配置信息为空 + */ + CONFIG_ID_IS_NOT_EXIST(14001, "配置信息为空"), + /** + * 配置ID无效 + */ + CONFIG_IS_NOT_EXIST(14002, "配置ID无效"), + /** + * 配置ID已存在 + */ + CONFIG_IS_EXIST(14002, "配置ID已存在"), + /** + * 系统配置不允许修改 + */ + CONFIG_IS_SYSTEM(14003, "系统配置不允许修改"), + /** + * 系统配置不允许删除 + */ + CONFIG_IS_NOT_DELETE(14003, "系统配置不允许删除"), + /** + * 文件不存在 + */ + FILE_DOES_NOT_EXIST(16001, "文件不存在"), + /** + * 文件上传异常 + */ + FILE_UPLOAD_EXCEPTION(16002, "文件上传异常"), + /** + * 文件下载异常 + */ + FILE_DOWNLOAD_ABNORMAL(16003, "文件下载异常"), + /** + * 无效的资源ID + */ + RESOURCE_NOT_FIND(12001, "无效的资源ID"), + /** + * 资源ID已存在 + */ + RESOURCE_IS_EXIST(12001, "资源ID已存在"), + /** + * 无效资源父节点ID + */ + RESOURCE_PARENT_NOT_FIND(12002, "无效资源父节点ID"), + /** + * 无效资源父节点ID + */ + RESOURCE_PARENT_INVALID(12003, "无效资源父节点ID"), + /** + * 该资源下有子资源,不能删除 + */ + RESOURCE_HAVE_SUB(12004, "该资源下有子资源,不能删除"), + /** + * 机构已存在 + */ + ORG_IS_EXIST(17001, "机构已存在"), + /** + * 机构不存在 + */ + ORG_NOT_EXIST(17002, "机构不存在"), + /** + * 机构下存在用户 + */ + ORG_HAVE_USER(17003, "机构下存在用户"), + /** + * 无效机构父节点ID + */ + ORG_PID_ERROR(17004, "无效机构父节点ID"), + /** + * 父级节点禁止删除 + */ + ORG_TOP_FORBID(17005, "父级节点禁止删除"), + /** + * 机构下存在子机构 + */ + ORG_HAVE_BRANCH(17006, "机构下存在子机构"), + /** + * 停用原因不能为空 + */ + ORG_STOP_REASON(17007, "停用原因不能为空"), + + //字典管理 + /** + * 父级ID无效 + */ + DICT_PID_ERROR(18001, "父级ID无效"), + /** + * ID无效 + */ + DICT_ID_ERROR(18002, "ID无效"), + /** + * 字典code已存在 + */ + DICT_CODE_EXIST(18003, "字典code已存在"), + /** + * 字典name已存在 + */ + DICT_NAME_EXIST(18004, "字典name已存在"), + /** + * 字典下存在数据 + */ + DICT_HAVE_DATA(18005, "字典下存在数据"), + /** + * 字典不存在 + */ + DICT_NOT_EXIST(18006, "字典不存在"), + /** + * 存在子节点 + */ + DICT_HAVE_SON(18007, "存在子节点"), + //数据组 + /** + * 数据组信息不存在 + */ + GROUP_ID_ERROR(19001, "数据组信息不存在"), + /** + * 数据组初始化无机构信息 + */ + GROUP_INIT_DATA_ERROR(19002, "数据组初始化无机构信息"); + + /** + * 状态码 + */ + final int code; + /** + * 消息内容 + */ + final String msg; +} diff --git a/cdp-common/cdp-common-core/src/main/java/com/baiye/core/constant/MessageConstant.java b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/constant/MessageConstant.java new file mode 100644 index 0000000..dd7b5c2 --- /dev/null +++ b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/constant/MessageConstant.java @@ -0,0 +1,103 @@ +package com.baiye.core.constant; + +import lombok.experimental.UtilityClass; + +/** + * Mate基本常量 + * + * @author pangu + */ +@UtilityClass +public class MessageConstant { + + /** + * 应用版本号 + */ + public static final String MATE_APP_VERSION = "4.4.9-SNAPSHOT"; + + /** + * Spring 应用名 prop key + */ + public static final String SPRING_APP_NAME_KEY = "spring.application.name"; + + + /** + * 默认为空消息 + */ + public static final String DEFAULT_NULL_MESSAGE = "承载数据为空"; + /** + * 默认成功消息 + */ + public static final String DEFAULT_SUCCESS_MESSAGE = "处理成功"; + /** + * 默认失败消息 + */ + public static final String DEFAULT_FAIL_MESSAGE = "处理失败"; + /** + * 树的根节点值 + */ + public static final Long TREE_ROOT = -1L; + /** + * 允许的文件类型,可根据需求添加 + */ + public static final String[] VALID_FILE_TYPE = {"xlsx", "zip"}; + + public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + /** + * 微服务之间传递的唯一标识 + */ + public static final String MATE_TRACE_ID = "mate-trace-id"; + + /** + * 日志链路追踪id日志标志 + */ + public static final String LOG_TRACE_ID = "traceId"; + + /** + * Java默认临时目录 + */ + public static final String JAVA_TEMP_DIR = "java.io.tmpdir"; + + /** + * 版本 + */ + public static final String VERSION = "version"; + + /** + * 默认版本号 + */ + public static final String DEFAULT_VERSION = "v1"; + + /** + * 服务资源 + */ + public static final String MATE_SERVICE_RESOURCE = "mate-service-resource"; + + /** + * API资源 + */ + public static final String MATE_API_RESOURCE = "mate-api-resource"; + + /** + * 权限认证的排序 + */ + public static final int MATE_UAA_FILTER_ORDER = -200; + + /** + * 签名排序 + */ + public static final int MATE_SIGN_FILTER_ORDER = -300; + + /** + * json类型报文,UTF-8字符集 + */ + public static final String JSON_UTF8 = "application/json;charset=UTF-8"; + + + public static final String CONFIG_DATA_ID_DYNAMIC_ROUTES = "mate-dynamic-routes.yaml"; + public static final String CONFIG_GROUP = "DEFAULT_GROUP"; + public static final long CONFIG_TIMEOUT_MS = 5000; + + +} diff --git a/cdp-common/cdp-common-core/src/main/java/com/baiye/core/constant/WebConstant.java b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/constant/WebConstant.java new file mode 100644 index 0000000..702d7b0 --- /dev/null +++ b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/constant/WebConstant.java @@ -0,0 +1,151 @@ +package com.baiye.core.constant; + +/** + * 网络通信常量,包括枚举类 + * + * @author david + */ +public class WebConstant { + + /** + * json类型报文,UTF-8字符集 + */ + public static final String JSON_UTF8 = "application/json;charset=UTF-8"; + + /** + * ws请求匹配头 + */ + public static final String DEFAULT_FILTER_PATH = "ws"; + + /** + * ws请求端口偏移 + */ + public static final int WS_PORT = 10; + + /** + * 字符集 + */ + public enum Character { + + /** + * UTF-8 + */ + UTF8("UTF-8", "UTF-8"), + + /** + * GBK + */ + GBK("GBK", "GBK"); + + private final String code; + private final String info; + + Character(String code, String info) { + this.code = code; + this.info = info; + } + + public String getCode() { + return code; + } + + public String getInfo() { + return info; + } + } + + /** + * 返回类型 + */ + public enum ResultType { + + /** + * success + */ + SUCCESS("success", "操作成功"), + + /** + * error + */ + ERROR("error", "操作失败"), + + /** + * warning + */ + WARNING("warning", "操作异常"); + + private final String code; + private final String info; + + ResultType(String code, String info) { + this.code = code; + this.info = info; + } + + public String getCode() { + return code; + } + + public String getInfo() { + return info; + } + } + + /** + * 请求类型 + */ + public enum Type { + + /** + * rmi + */ + LOOKUP_RMI("rmi:", "RMI 远程方法调用"), + + /** + * ldap + */ + LOOKUP_LDAP("ldap:", "LDAP 远程方法调用"), + + /** + * ldaps + */ + LOOKUP_LDAPS("ldaps:", "LDAPS 远程方法调用"), + + /** + * http + */ + HTTP("http://", "http请求"), + + /** + * https + */ + HTTPS("https://", "https请求"), + + /** + * ws + */ + WS("ws://", "ws请求"), + + /** + * wss + */ + WSS("wss://", "wss请求"); + + private final String code; + private final String info; + + Type(String code, String info) { + this.code = code; + this.info = info; + } + + public String getCode() { + return code; + } + + public String getInfo() { + return info; + } + } + +} diff --git a/cdp-common/cdp-common-core/src/main/java/com/baiye/core/util/RequestUtils.java b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/util/RequestUtils.java index 3295100..5e10289 100644 --- a/cdp-common/cdp-common-core/src/main/java/com/baiye/core/util/RequestUtils.java +++ b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/util/RequestUtils.java @@ -25,7 +25,6 @@ import java.util.Objects; * @date 2022-05-14 */ @Slf4j - public final class RequestUtils { private RequestUtils(){} diff --git a/cdp-common/cdp-common-core/src/main/java/com/baiye/core/util/ResponseUtil.java b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/util/ResponseUtil.java new file mode 100644 index 0000000..0ebfd14 --- /dev/null +++ b/cdp-common/cdp-common-core/src/main/java/com/baiye/core/util/ResponseUtil.java @@ -0,0 +1,57 @@ +package com.baiye.core.util; + +import com.alibaba.fastjson.JSON; +import com.baiye.core.base.api.Result; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.server.reactive.ServerHttpResponse; +import reactor.core.publisher.Mono; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * 响应工具 + * + * @author pangu + */ +public class ResponseUtil { + + private ResponseUtil() { + } + + /** + * 设置响应 + * + * @param response HttpServletResponse + * @param contentType content-type + * @param status http状态码 + * @param value 响应内容 + * @throws IOException IOException + */ + public static void responseWriter(HttpServletResponse response, String contentType, + int status, Object value) throws IOException { + response.setContentType(contentType); + response.setStatus(status); + response.getOutputStream().write(JSON.toJSONString(value).getBytes()); + } + + /** + * 设置webflux模型响应 + * + * @param response ServerHttpResponse + * @param contentType content-type + * @param status http状态码 + * @param value 响应内容 + * @return Mono + */ + public static Mono webFluxResponseWriter(ServerHttpResponse response, String contentType, + HttpStatus status, Object value) { + response.setStatusCode(status); + response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType); + Result result = Result.fail(status.value(), value.toString()); + DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes()); + return response.writeWith(Mono.just(dataBuffer)); + } +} diff --git a/cdp-common/cdp-common-exception/src/main/java/com/baiye/exception/global/handle/ApiError.java b/cdp-common/cdp-common-exception/src/main/java/com/baiye/exception/global/handle/ApiError.java index 1fd1695..0350d37 100644 --- a/cdp-common/cdp-common-exception/src/main/java/com/baiye/exception/global/handle/ApiError.java +++ b/cdp-common/cdp-common-exception/src/main/java/com/baiye/exception/global/handle/ApiError.java @@ -25,7 +25,7 @@ import java.time.LocalDateTime; * @date 2018-11-23 */ @Data -class ApiError { +public class ApiError { private Integer status = 400; diff --git a/cdp-common/cdp-common-exception/src/main/resources/META-INF/spring.factories b/cdp-common/cdp-common-exception/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 922f97d..0000000 --- a/cdp-common/cdp-common-exception/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - com.baiye.exception.global.handle.GlobalExceptionHandler diff --git a/cdp-common/cdp-common-security/src/main/java/com/baiye/EnableCustomizeFeignClient.java b/cdp-common/cdp-common-security/src/main/java/com/baiye/annotation/EnableCustomizeFeignClient.java similarity index 98% rename from cdp-common/cdp-common-security/src/main/java/com/baiye/EnableCustomizeFeignClient.java rename to cdp-common/cdp-common-security/src/main/java/com/baiye/annotation/EnableCustomizeFeignClient.java index 222a889..fe257ae 100644 --- a/cdp-common/cdp-common-security/src/main/java/com/baiye/EnableCustomizeFeignClient.java +++ b/cdp-common/cdp-common-security/src/main/java/com/baiye/annotation/EnableCustomizeFeignClient.java @@ -1,4 +1,4 @@ -package com.baiye; +package com.baiye.annotation; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClientsConfiguration; diff --git a/cdp-common/cdp-common-security/src/main/java/com/baiye/EnableCustomizeResourceServer.java b/cdp-common/cdp-common-security/src/main/java/com/baiye/annotation/EnableCustomizeResourceServer.java similarity index 97% rename from cdp-common/cdp-common-security/src/main/java/com/baiye/EnableCustomizeResourceServer.java rename to cdp-common/cdp-common-security/src/main/java/com/baiye/annotation/EnableCustomizeResourceServer.java index 6420b16..06700e3 100644 --- a/cdp-common/cdp-common-security/src/main/java/com/baiye/EnableCustomizeResourceServer.java +++ b/cdp-common/cdp-common-security/src/main/java/com/baiye/annotation/EnableCustomizeResourceServer.java @@ -1,4 +1,4 @@ -package com.baiye; +package com.baiye.annotation; import com.baiye.config.ResourceServerAutoConfiguration; import com.baiye.component.PermissionComponent; diff --git a/cdp-common/cdp-common-security/src/main/java/com/baiye/Inner.java b/cdp-common/cdp-common-security/src/main/java/com/baiye/annotation/Inner.java similarity index 95% rename from cdp-common/cdp-common-security/src/main/java/com/baiye/Inner.java rename to cdp-common/cdp-common-security/src/main/java/com/baiye/annotation/Inner.java index 1a13434..019215d 100644 --- a/cdp-common/cdp-common-security/src/main/java/com/baiye/Inner.java +++ b/cdp-common/cdp-common-security/src/main/java/com/baiye/annotation/Inner.java @@ -1,4 +1,4 @@ -package com.baiye; +package com.baiye.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -6,7 +6,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * + * * @description 被该注解注解的类或者方法,在服务之间访问的时候不进行鉴权操作 * @author Enzo * @date 2020-08-04 14:42 diff --git a/cdp-common/cdp-common-security/src/main/java/com/baiye/component/CustomizeWebResponseExceptionTranslator.java b/cdp-common/cdp-common-security/src/main/java/com/baiye/component/CustomizeWebResponseExceptionTranslator.java index 663b010..dc41c67 100644 --- a/cdp-common/cdp-common-security/src/main/java/com/baiye/component/CustomizeWebResponseExceptionTranslator.java +++ b/cdp-common/cdp-common-security/src/main/java/com/baiye/component/CustomizeWebResponseExceptionTranslator.java @@ -13,14 +13,16 @@ import org.springframework.security.oauth2.common.exceptions.InvalidGrantExcepti import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; import org.springframework.security.web.util.ThrowableAnalyzer; +import org.springframework.stereotype.Component; import org.springframework.web.HttpRequestMethodNotSupportedException; /** - * @description 自定义异常返回信息 * @author Enzo - * @date 2022-05-16 + * @description 自定义异常返回信息 + * @date 2022-05-16 */ @SuppressWarnings("rawtypes") +@Component("customizeWebResponseExceptionTranslator") public class CustomizeWebResponseExceptionTranslator implements WebResponseExceptionTranslator { private final ThrowableAnalyzer throwableAnalyzer = new ThrowableAnalyzer(); @@ -30,54 +32,41 @@ public class CustomizeWebResponseExceptionTranslator implements WebResponseExcep public ResponseEntity translate(Exception e) { // 获取栈堆中的错误链信息 Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(e); - - /** - * 如果出现认证异常 - */ + // 如果出现认证异常 Exception ase = (UnauthorizedException) this.throwableAnalyzer. getFirstThrowableOfType(UnauthorizedException.class, causeChain); if (ase != null) { return this.handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e)); } - /** - * 权限不足异常 - */ + // 权限不足异常 ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain); if (ase != null) { return this.handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase)); } - /** - * 无效的grantType异常 - */ + // 无效的grantType异常 ase = (InvalidGrantException) throwableAnalyzer.getFirstThrowableOfType(InvalidGrantException.class, causeChain); if (ase != null) { return this.handleOAuth2Exception(new InvalidException(ase.getMessage(), ase)); } - /** - * 请求方法异常,登录只能为post请求 - */ + // 请求方法异常,登录只能为post请求 ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer .getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain); if (ase != null) { return this.handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase)); } - /** - * OAuth2的异常,包含多种异常 - */ + // OAuth2的异常,包含多种异常 ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain); if (ase != null) { return this.handleOAuth2Exception((OAuth2Exception) ase); } - /** - * 不是上述异常则服务发生异常 - */ + // 不是上述异常则服务发生异常 return this.handleOAuth2Exception(new ServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e)); } @@ -98,7 +87,6 @@ public class CustomizeWebResponseExceptionTranslator implements WebResponseExcep headers.set(HttpHeaders.WWW_AUTHENTICATE, String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary())); } - // 客户端异常直接返回客户端,不然无法解析 if (e instanceof ClientAuthenticationException) { return new ResponseEntity<>(e, headers, HttpStatus.valueOf(status)); diff --git a/cdp-common/cdp-common-security/src/main/java/com/baiye/component/InnerAspect.java b/cdp-common/cdp-common-security/src/main/java/com/baiye/component/InnerAspect.java index 2e1e418..1c08a1c 100644 --- a/cdp-common/cdp-common-security/src/main/java/com/baiye/component/InnerAspect.java +++ b/cdp-common/cdp-common-security/src/main/java/com/baiye/component/InnerAspect.java @@ -2,7 +2,7 @@ package com.baiye.component; import cn.hutool.core.util.StrUtil; import com.baiye.core.constant.SecurityConstants; -import com.baiye.Inner; +import com.baiye.annotation.Inner; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; diff --git a/cdp-common/cdp-common-security/src/main/java/com/baiye/config/IgnoreUrlPropsConfiguration.java b/cdp-common/cdp-common-security/src/main/java/com/baiye/config/IgnoreUrlPropsConfiguration.java new file mode 100644 index 0000000..4628e1d --- /dev/null +++ b/cdp-common/cdp-common-security/src/main/java/com/baiye/config/IgnoreUrlPropsConfiguration.java @@ -0,0 +1,54 @@ +package com.baiye.config; + +import lombok.Data; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * 忽略URL属性配置 + * + * @author pangu + */ +@Data +@RefreshScope +@Component +public class IgnoreUrlPropsConfiguration { + + /** + * 认证中心默认忽略验证地址 + */ + private static final String[] SECURITY_ENDPOINTS = { + "/auth/**", + "/actuator/**", + "/oauth/**", + "/auth/**", + "/token/**", + "/login/*", + "/actuator/**", + "/v2/api-docs", + "/doc.html", + "/webjars/**", + "**/favicon.ico", + "/swagger-resources/**" + }; + + private List urls = new ArrayList<>(); + + private List client = new ArrayList<>(); + + private List ignoreSecurity = new ArrayList<>(); + + /** + * 首次加载合并ENDPOINTS + */ + @PostConstruct + public void initIgnoreSecurity() { + Collections.addAll(ignoreSecurity, SECURITY_ENDPOINTS); + } + +} diff --git a/cdp-common/cdp-common-security/src/main/java/com/baiye/config/PermitUrls.java b/cdp-common/cdp-common-security/src/main/java/com/baiye/config/PermitUrls.java index 98eea38..9a748e1 100644 --- a/cdp-common/cdp-common-security/src/main/java/com/baiye/config/PermitUrls.java +++ b/cdp-common/cdp-common-security/src/main/java/com/baiye/config/PermitUrls.java @@ -1,7 +1,7 @@ package com.baiye.config; import cn.hutool.core.util.ReUtil; -import com.baiye.Inner; +import com.baiye.annotation.Inner; import lombok.Getter; import lombok.Setter; import org.springframework.beans.BeansException; @@ -23,7 +23,7 @@ import java.util.Optional; import java.util.regex.Pattern; /** - * + * * @description 允许不用鉴权直接访问的url * @author Enzo * @create 2022-05-16 diff --git a/cdp-common/cdp-common-security/src/main/java/com/baiye/config/RestTemplateConfig.java b/cdp-common/cdp-common-security/src/main/java/com/baiye/config/RestTemplateConfig.java index 86b3f1d..149c9cf 100644 --- a/cdp-common/cdp-common-security/src/main/java/com/baiye/config/RestTemplateConfig.java +++ b/cdp-common/cdp-common-security/src/main/java/com/baiye/config/RestTemplateConfig.java @@ -22,8 +22,8 @@ import java.util.Collections; @Configuration public class RestTemplateConfig { - @Primary @Bean + @Primary @LoadBalanced public RestTemplate lbRestTemplate() { RestTemplate restTemplate = new RestTemplate(); @@ -32,7 +32,6 @@ public class RestTemplateConfig { request.getHeaders().set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); return execution.execute(request, body); })); - // 处理400 异常 restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { @Override diff --git a/cdp-common/cdp-common-security/src/main/java/com/baiye/handle/CustomAuthenticationFailureHandler.java b/cdp-common/cdp-common-security/src/main/java/com/baiye/handle/CustomAuthenticationFailureHandler.java new file mode 100644 index 0000000..4f8b309 --- /dev/null +++ b/cdp-common/cdp-common-security/src/main/java/com/baiye/handle/CustomAuthenticationFailureHandler.java @@ -0,0 +1,62 @@ +package com.baiye.handle; + +import com.baiye.core.base.api.Result; +import com.baiye.core.base.api.ResultCode; +import com.baiye.core.util.ResponseUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.*; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.stereotype.Component; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * 登录失败的回调 + * @author pangu + */ +@Slf4j +@Component +public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { + @Override + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { + Result result; + String username = request.getParameter("username"); + if (exception instanceof AccountExpiredException) { + // 账号过期 + log.info("[登录失败] - 用户[{}]账号过期", username); + result = Result.fail(ResultCode.USER_ACCOUNT_EXPIRED); + } else if (exception instanceof BadCredentialsException) { + // 密码错误 + log.info("[登录失败] - 用户[{}]密码错误", username); + result = Result.fail(ResultCode.USER_PASSWORD_ERROR); + } else if (exception instanceof CredentialsExpiredException) { + // 密码过期 + log.info("[登录失败] - 用户[{}]密码过期", username); + result = Result.fail(ResultCode.USER_PASSWORD_EXPIRED); + } else if (exception instanceof DisabledException) { + // 用户被禁用 + log.info("[登录失败] - 用户[{}]被禁用", username); + result = Result.fail(ResultCode.USER_DISABLED); + + } else if (exception instanceof LockedException) { + // 用户被锁定 + log.info("[登录失败] - 用户[{}]被锁定", username); + result = Result.fail(ResultCode.USER_LOCKED); + + } else if (exception instanceof InternalAuthenticationServiceException) { + // 内部错误 + log.error(String.format("[登录失败] - [%s]内部错误", username)); + result = Result.fail(ResultCode.USER_LOGIN_FAIL); + } else { + // 其他错误 + log.error(String.format("[登录失败] - [%s]其他错误", username), exception); + result = Result.fail(ResultCode.USER_LOGIN_FAIL); + } + ResponseUtil.responseWriter(response, "UTF-8", HttpStatus.UNAUTHORIZED.value(), result); + } +} diff --git a/cdp-common/cdp-common-security/src/main/java/com/baiye/service/UserDetailsServiceImpl.java b/cdp-common/cdp-common-security/src/main/java/com/baiye/service/UserDetailsServiceImpl.java index d10e662..c269d0d 100644 --- a/cdp-common/cdp-common-security/src/main/java/com/baiye/service/UserDetailsServiceImpl.java +++ b/cdp-common/cdp-common-security/src/main/java/com/baiye/service/UserDetailsServiceImpl.java @@ -25,7 +25,7 @@ import java.util.List; import java.util.Set; /** - * + * * @description 用户详细信息 * @author Enzo * @date 2020-08-05 17:35 @@ -78,7 +78,7 @@ public class UserDetailsServiceImpl implements UserDetailsService { UserSmallDto result = this.remoteUserService.getUserDetails(username, SecurityConstants.FROM_IN); UserDetails userDetails = this.getUserDetails(result); // 放入缓存 - if (loginProperties.getCacheEnable()) { + if (Boolean.TRUE.equals(loginProperties.getCacheEnable())) { assert cache != null; cache.put(username, userDetails); } diff --git a/cdp-common/cdp-common-security/src/main/resources/META-INF/spring.factories b/cdp-common/cdp-common-security/src/main/resources/META-INF/spring.factories index cc2268b..8c930e1 100644 --- a/cdp-common/cdp-common-security/src/main/resources/META-INF/spring.factories +++ b/cdp-common/cdp-common-security/src/main/resources/META-INF/spring.factories @@ -1,3 +1,4 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.baiye.component.InnerAspect,\ - com.baiye.service.UserDetailsServiceImpl \ No newline at end of file + com.baiye.service.UserDetailsServiceImpl,\ + com.baiye.config.IgnoreUrlPropsConfiguration diff --git a/cdp-iaas/authorization-server/pom.xml b/cdp-iaas/authorization-server/pom.xml index 3c40082..01eb0c2 100644 --- a/cdp-iaas/authorization-server/pom.xml +++ b/cdp-iaas/authorization-server/pom.xml @@ -26,10 +26,6 @@ com.baiye cdp-common-security - - org.lionsoul - ip2region - HdrHistogram org.hdrhistogram @@ -57,6 +53,14 @@ jasypt-spring-boot-starter + + + com.baiye + cdp-common-exception + 1.0-SNAPSHOT + compile + + diff --git a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/AuthApplication.java b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/AuthApplication.java index 39fcfb3..182c12c 100644 --- a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/AuthApplication.java +++ b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/AuthApplication.java @@ -1,6 +1,6 @@ package com.baiye.auth; -import com.baiye.EnableCustomizeFeignClient; +import com.baiye.annotation.EnableCustomizeFeignClient; import com.baiye.config.LoginProperties; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -10,20 +10,22 @@ import org.springframework.context.annotation.Bean; /** - * - * @description 认证服务启动类 * @author Enzo + * @description 认证服务启动类 * @date 2020-08-03 16:12 */ @EnableCustomizeFeignClient(basePackages = "com.baiye") @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class AuthApplication { public static void main(String[] args) { - SpringApplication.run(AuthApplication.class,args); + SpringApplication.run(AuthApplication.class, args); } + @Bean @ConditionalOnMissingBean - public LoginProperties loginProperties(){ + public LoginProperties loginProperties() { return new LoginProperties(); } + + } diff --git a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/config/AuthServerConfig.java b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/config/AuthServerConfig.java index 78354dd..1f9fbfb 100644 --- a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/config/AuthServerConfig.java +++ b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/config/AuthServerConfig.java @@ -1,5 +1,6 @@ package com.baiye.auth.config; +import com.baiye.auth.translator.CustomWebRespExceptionTranslator; import com.baiye.auth.service.IOnlineUserService; import com.baiye.core.constant.CacheKey; import com.baiye.core.constant.SecurityConstants; @@ -33,7 +34,7 @@ import java.util.Map; import java.util.stream.Collectors; /** - * + * * @description 授权服务配置 * @author Enzo * @date 2020-08-03 16:14 @@ -113,9 +114,9 @@ public class AuthServerConfig extends AuthorizationServerConfigurerAdapter { .authenticationManager(authenticationManager) // 是否重复使用refreshToken .reuseRefreshTokens(false) - .pathMapping("/oauth/confirm_access", "/token/confirm_access"); + .pathMapping("/oauth/confirm_access", "/token/confirm_access") // 自定义异常处理 - // .exceptionTranslator(new CustomizeWebResponseExceptionTranslator()); + .exceptionTranslator(new CustomWebRespExceptionTranslator()); } /** @@ -124,28 +125,25 @@ public class AuthServerConfig extends AuthorizationServerConfigurerAdapter { */ @Bean public TokenEnhancer tokenEnhancer() { - return new TokenEnhancer() { - @Override - public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { - if (accessToken instanceof DefaultOAuth2AccessToken){ - LoginUser loginUser = (LoginUser) authentication.getUserAuthentication().getPrincipal(); - // TODO: 2020/8/5 在token中后续添加权限信息 - /* - * 获取权限列表 - */ - String authorities = authentication.getAuthorities().stream() - .map(GrantedAuthority::getAuthority) - .collect(Collectors.joining(",")); - Map additionalInformation = new LinkedHashMap(4); - additionalInformation.put(SecurityConstants.DETAILS_USER_ID,loginUser.getUserId()); - additionalInformation.put(SecurityConstants.DETAILS_USERNAME, loginUser.getUsername()); - additionalInformation.put(SecurityConstants.DATA_SCOPES, loginUser.getDataScopes()); - additionalInformation.put(SecurityConstants.AUTHORITIES_KEY,authorities); - ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation); - onlineUserService.saveOnlineUser(accessToken); - } - return accessToken; + return (accessToken, authentication) -> { + if (accessToken instanceof DefaultOAuth2AccessToken){ + LoginUser loginUser = (LoginUser) authentication.getUserAuthentication().getPrincipal(); + // TODO: 2020/8/5 在token中后续添加权限信息 + /* + * 获取权限列表 + */ + String authorities = authentication.getAuthorities().stream() + .map(GrantedAuthority::getAuthority) + .collect(Collectors.joining(",")); + Map additionalInformation = new LinkedHashMap(4); + additionalInformation.put(SecurityConstants.DETAILS_USER_ID,loginUser.getUserId()); + additionalInformation.put(SecurityConstants.DETAILS_USERNAME, loginUser.getUsername()); + additionalInformation.put(SecurityConstants.DATA_SCOPES, loginUser.getDataScopes()); + additionalInformation.put(SecurityConstants.AUTHORITIES_KEY,authorities); + ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation); + onlineUserService.saveOnlineUser(accessToken); } + return accessToken; }; } diff --git a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/config/WebSecurityConfig.java b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/config/WebSecurityConfig.java index 83703c0..d685f9e 100644 --- a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/config/WebSecurityConfig.java +++ b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/config/WebSecurityConfig.java @@ -1,5 +1,7 @@ package com.baiye.auth.config; +import com.baiye.config.IgnoreUrlPropsConfiguration; +import com.baiye.handle.CustomAuthenticationFailureHandler; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -8,15 +10,16 @@ import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; /** - * + * @author Enzo * @description webSecurity配置, auth2依赖于WebSecurityConfigurerAdapter配置,且该配置要比AuthorizationServerConfigurerAdapter * 先运行 - * @author Enzo * @date 2020-08-03 17:25 */ @Order(99) @@ -26,6 +29,8 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private final UserDetailsService userDetailsService; + private final IgnoreUrlPropsConfiguration ignoreUrlPropsConfig; + @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); @@ -42,16 +47,33 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } + @Bean + public AuthenticationFailureHandler mateAuthenticationFailureHandler() { + return new CustomAuthenticationFailureHandler(); + } + @Override protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers( - "/actuator/**", - "/oauth/**", - "/auth/**", - "/token/**").permitAll() - .anyRequest().authenticated() - .and().csrf().disable(); + AuthenticationFailureHandler authenticationFailureHandler = mateAuthenticationFailureHandler(); + ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry config + = http.requestMatchers().anyRequest() + .and() + .formLogin() + .failureHandler(authenticationFailureHandler) + .and() + .authorizeRequests(); + config.antMatchers("/actuator/**", "/oauth/**", "/auth/**", "/token/**").permitAll(); + ignoreUrlPropsConfig.getUrls().forEach(url -> config.antMatchers(url).permitAll()); + ignoreUrlPropsConfig.getIgnoreSecurity().forEach(url -> config.antMatchers(url).permitAll()); + config + //任何请求 + .anyRequest() + //都需要身份认证 + .authenticated() + //csrf跨站请求 + .and() + .csrf() + .disable(); } + } diff --git a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/controller/LogoutController.java b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/controller/LogoutController.java index 3075b68..4b9e922 100644 --- a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/controller/LogoutController.java +++ b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/controller/LogoutController.java @@ -1,5 +1,6 @@ package com.baiye.auth.controller; +import cn.hutool.core.text.CharSequenceUtil; import com.baiye.auth.service.ILogoutService; import com.baiye.core.util.StringUtils; import lombok.RequiredArgsConstructor; @@ -12,7 +13,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** - * + * * @description tokenController主要用来处理注销逻辑 * @author Enzo * @date 2020-08-03 17:58 @@ -21,21 +22,17 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/token") @RequiredArgsConstructor public class LogoutController { - - private final ILogoutService tokenService; - - @DeleteMapping("/logout") public ResponseEntity logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) { - if (StringUtils.isEmpty(authHeader)) { + if (CharSequenceUtil.isEmpty(authHeader)) { // 没有token信息,表示已经是注销状态,直接返回ok return ResponseEntity.ok().build(); } // 进行注销操作 Boolean isSuccess = this.tokenService.logout(authHeader); - if (isSuccess) { + if (Boolean.TRUE.equals(isSuccess)) { return ResponseEntity.ok().build(); } return new ResponseEntity<>("注销失败", HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/controller/OnlineController.java b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/controller/OnlineController.java index eadcf14..ca4e7d0 100644 --- a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/controller/OnlineController.java +++ b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/controller/OnlineController.java @@ -12,6 +12,11 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Set; +/** + * @author Enzo + * @date 2022-5-17 + * 在线用户 + */ @RestController @RequiredArgsConstructor @RequestMapping("/oauth/online") @@ -40,4 +45,4 @@ public class OnlineController { } return new ResponseEntity<>(HttpStatus.OK); } -} \ No newline at end of file +} diff --git a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/service/impl/OnlineServiceImpl.java b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/service/impl/OnlineServiceImpl.java index a063cb7..a5d1d55 100644 --- a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/service/impl/OnlineServiceImpl.java +++ b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/service/impl/OnlineServiceImpl.java @@ -62,16 +62,15 @@ public class OnlineServiceImpl implements IOnlineUserService { public void saveOnlineUser(OAuth2AccessToken accessToken) { HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); Map additionalInfo = accessToken.getAdditionalInformation(); - // TODO 需初始化util - /*String browser = RequestUtils.getBrowser(request); + String browser = RequestUtils.getBrowser(request); String ip = RequestUtils.getIp(request); - String cityInfo = RequestUtils.getCityInfo(ip);*/ + String cityInfo = RequestUtils.getCityInfo(ip); Long userId = (Long) additionalInfo.get(SecurityConstants.DETAILS_USER_ID); String username = (String) additionalInfo.get(SecurityConstants.DETAILS_USERNAME); String tokenValue = accessToken.getValue(); int expiresIn = accessToken.getExpiresIn(); String refreshToken = accessToken.getRefreshToken().getValue(); - OnlineUser onlineUser = new OnlineUser(userId, username, "browser", "ip", "cityInfo", + OnlineUser onlineUser = new OnlineUser(userId, username, browser, ip, cityInfo, LocalDateTime.now(ZoneId.systemDefault()), tokenValue, refreshToken, expiresIn); this.redisUtils.set(CacheKey.ONLINE_USER + userId, onlineUser, expiresIn, TimeUnit.SECONDS); } diff --git a/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/translator/CustomWebRespExceptionTranslator.java b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/translator/CustomWebRespExceptionTranslator.java new file mode 100644 index 0000000..1d3327e --- /dev/null +++ b/cdp-iaas/authorization-server/src/main/java/com/baiye/auth/translator/CustomWebRespExceptionTranslator.java @@ -0,0 +1,71 @@ +package com.baiye.auth.translator; + +import com.baiye.exception.global.handle.ApiError; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; +import org.springframework.security.oauth2.common.exceptions.InvalidScopeException; +import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; +import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException; +import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; +import org.springframework.stereotype.Component; + +/** + * WEB响应异常处理类 + * + * @author pangu + */ +@Slf4j +@Component("customWebRespExceptionTranslator") +public class CustomWebRespExceptionTranslator implements WebResponseExceptionTranslator { + + @Override + public ResponseEntity translate(Exception e) { + ResponseEntity.BodyBuilder status = ResponseEntity.status(HttpStatus.UNAUTHORIZED); + String message = "认证失败"; + log.error(message, e); + if (e instanceof UnsupportedGrantTypeException) { + message = "不支持该认证类型"; + return buildResponseEntity(ApiError.error(message)); + } + if (e instanceof InvalidTokenException + && StringUtils.containsIgnoreCase(e.getMessage(), "Invalid refresh token (expired)")) { + message = "刷新令牌已过期,请重新登录"; + return buildResponseEntity(ApiError.error(message)); + } + if (e instanceof InvalidScopeException) { + message = "不是有效的scope值"; + return buildResponseEntity(ApiError.error(message)); + } + if (e instanceof InvalidGrantException) { + if (StringUtils.containsIgnoreCase(e.getMessage(), "Invalid refresh token")) { + message = "refresh token无效"; + return buildResponseEntity(ApiError.error(message)); + } + if (StringUtils.containsIgnoreCase(e.getMessage(), "Invalid authorization code")) { + message = "authorization code无效"; + return buildResponseEntity(ApiError.error(message)); + + } + if (StringUtils.containsIgnoreCase(e.getMessage(), "locked")) { + message = "用户已被锁定,请联系管理员"; + return buildResponseEntity(ApiError.error(message)); + } + message = "用户名或密码错误"; + return buildResponseEntity(ApiError.error(message)); + } + return buildResponseEntity(ApiError.error(message)); + } + + + /** + * 统一返回 + */ + private ResponseEntity buildResponseEntity(ApiError apiError) { + return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus())); + } + + +} diff --git a/cdp-iaas/authorization-server/src/main/resources/banner.txt b/cdp-iaas/authorization-server/src/main/resources/banner.txt new file mode 100644 index 0000000..b6cabaf --- /dev/null +++ b/cdp-iaas/authorization-server/src/main/resources/banner.txt @@ -0,0 +1,19 @@ + , \ / , + / \ )\__/( / \ + / \ (_\ /_) / \ + __________________/_____\__\@ @/___/_____\_________________ + | ______ |\../| | + | ''|| \\ _____ \VV/ _____ ____ | + | || || //|| || \\ //|| || \\ // \\ \\ // | + | ||=='' // || || || // || || || || || \\_// | + | || //==|| ||=='' //==|| || || || || // \\ | + | || // || || \\ // || ||__// \\__// // \\ | + |__________________________________________________________| + | /\ / \\ \ /\ | + | / V )) V \ | + |/ ` // ' \| + ` V ' + + xx xx xx xx xx xx + xx xx xx xx xx xx xx xx +========================================================================= \ No newline at end of file diff --git a/cdp-iaas/authorization-server/src/main/resources/config/bootstrap.yml b/cdp-iaas/authorization-server/src/main/resources/config/bootstrap.yml index 58650a3..69a42e0 100644 --- a/cdp-iaas/authorization-server/src/main/resources/config/bootstrap.yml +++ b/cdp-iaas/authorization-server/src/main/resources/config/bootstrap.yml @@ -30,3 +30,5 @@ spring: - application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension} profiles: active: dev +ip: + local-parsing: true diff --git a/cdp-iaas/gateway-server/src/main/java/com/baiye/config/GatewayConfiguration.java b/cdp-iaas/gateway-server/src/main/java/com/baiye/config/GatewayConfiguration.java index 1e77c41..6c24cbb 100644 --- a/cdp-iaas/gateway-server/src/main/java/com/baiye/config/GatewayConfiguration.java +++ b/cdp-iaas/gateway-server/src/main/java/com/baiye/config/GatewayConfiguration.java @@ -1,7 +1,10 @@ package com.baiye.config; import org.springframework.beans.factory.ObjectProvider; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.web.reactive.result.view.ViewResolver; @@ -10,8 +13,11 @@ import java.util.List; /** * 网关限流配置 + * * @author Enzo */ +// TODO 后续添加 sentinel 触发限流后执行的方法 +/* @Configuration public class GatewayConfiguration { @@ -24,8 +30,8 @@ public class GatewayConfiguration { this.serverCodecConfigurer = serverCodecConfigurer; } - // TODO 后续添加 sentinel 触发限流后执行的方法 - /*@Bean + + @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public JsonSentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() { // Register the block exception handler for Spring Cloud Gateway. @@ -37,5 +43,6 @@ public class GatewayConfiguration { @Order(Ordered.HIGHEST_PRECEDENCE) public GlobalFilter sentinelGatewayFilter() { return new SentinelGatewayFilter(); - }*/ + } } +*/ diff --git a/cdp-iaas/gateway-server/src/main/java/com/baiye/filter/ValidateCodeFilter.java b/cdp-iaas/gateway-server/src/main/java/com/baiye/filter/ValidateCodeFilter.java index de79df5..9a6b875 100644 --- a/cdp-iaas/gateway-server/src/main/java/com/baiye/filter/ValidateCodeFilter.java +++ b/cdp-iaas/gateway-server/src/main/java/com/baiye/filter/ValidateCodeFilter.java @@ -1,5 +1,6 @@ package com.baiye.filter; +import cn.hutool.core.date.DateUtil; import cn.hutool.core.text.CharSequenceUtil; import com.alibaba.fastjson.JSON; import com.baiye.config.IgnoreClientConfiguration; @@ -69,14 +70,16 @@ public class ValidateCodeFilter extends AbstractGatewayFilterFactory { try { validateCodeService.checkCapcha(uuid,code); } catch (CaptchaException e) { + log.info("验证码有误"); ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); return response.writeWith(Mono.create(monoSink->{ Map resultMap = Maps.newHashMapWithExpectedSize(2); + resultMap.put("timestamp", DateUtil.now()); resultMap.put("message",e.getMessage()); - resultMap.put("code","400"); + resultMap.put("status","400"); byte[] bytes = JSON.toJSONBytes(resultMap); DataBuffer wrap = response.bufferFactory().wrap(bytes); monoSink.success(wrap); diff --git a/cdp-iaas/gateway-server/src/main/java/com/baiye/service/impl/ValidateCodeService.java b/cdp-iaas/gateway-server/src/main/java/com/baiye/service/impl/ValidateCodeService.java index c0cb1ba..9b92b97 100644 --- a/cdp-iaas/gateway-server/src/main/java/com/baiye/service/impl/ValidateCodeService.java +++ b/cdp-iaas/gateway-server/src/main/java/com/baiye/service/impl/ValidateCodeService.java @@ -2,8 +2,6 @@ package com.baiye.service.impl; import cn.hutool.core.text.CharSequenceUtil; import cn.hutool.core.util.IdUtil; -import cn.hutool.core.util.StrUtil; -import com.baiye.config.CaptchaConfig; import com.baiye.config.KaptchaTextCreator; import com.baiye.core.constant.CaptchaConstants; import com.baiye.core.util.RedisUtils; @@ -14,14 +12,12 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; /** * @author Enzo - * * @description 验证码业务处理实现类 * @date 2020-07-29 17:22 */ @@ -31,13 +27,15 @@ import java.util.concurrent.TimeUnit; public class ValidateCodeService implements IValidateCodeService { + + private final RedisUtils redisUtils; private final KaptchaTextCreator kaptchaTextCreator; @Override - public Map createCapcha() throws IOException, CaptchaException { + public Map createCapcha() throws CaptchaException { // 获取验证码 Captcha captcha = this.kaptchaTextCreator.getCaptcha(); // 生成一个唯一的id @@ -55,10 +53,10 @@ public class ValidateCodeService implements IValidateCodeService { if (CharSequenceUtil.isBlank(code)) { throw new CaptchaException("验证码不能为空"); } - if (CharSequenceUtil.isBlank(key)) { + String captcha = (String) redisUtils.get(key); + if (CharSequenceUtil.isBlank(captcha)) { throw new CaptchaException("验证码已失效"); } - String captcha = (String) redisUtils.get(key); redisUtils.del(key); if (!code.equalsIgnoreCase(captcha)) { throw new CaptchaException("验证码错误"); diff --git a/cdp-iaas/gateway-server/src/main/resources/banner.txt b/cdp-iaas/gateway-server/src/main/resources/banner.txt new file mode 100644 index 0000000..b6cabaf --- /dev/null +++ b/cdp-iaas/gateway-server/src/main/resources/banner.txt @@ -0,0 +1,19 @@ + , \ / , + / \ )\__/( / \ + / \ (_\ /_) / \ + __________________/_____\__\@ @/___/_____\_________________ + | ______ |\../| | + | ''|| \\ _____ \VV/ _____ ____ | + | || || //|| || \\ //|| || \\ // \\ \\ // | + | ||=='' // || || || // || || || || || \\_// | + | || //==|| ||=='' //==|| || || || || // \\ | + | || // || || \\ // || ||__// \\__// // \\ | + |__________________________________________________________| + | /\ / \\ \ /\ | + | / V )) V \ | + |/ ` // ' \| + ` V ' + + xx xx xx xx xx xx + xx xx xx xx xx xx xx xx +========================================================================= \ No newline at end of file diff --git a/cdp-iaas/gateway-server/src/main/resources/config/application.yml b/cdp-iaas/gateway-server/src/main/resources/config/application.yml index 1a69e19..ef8191b 100644 --- a/cdp-iaas/gateway-server/src/main/resources/config/application.yml +++ b/cdp-iaas/gateway-server/src/main/resources/config/application.yml @@ -6,9 +6,9 @@ spring: redis: #数据库索引 database: 0 - host: 8.130.96.163 + host: 127.0.0.1 port: 6379 - password: + password: '012099' datasource: url: jdbc:mysql://${MYSQL_HOST:8.130.96.163}:${MYSQL_PORT:3306}/${MYSQL_DB:gateway}?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true driver-class-name: com.mysql.jdbc.Driver diff --git a/cdp-iaas/pom.xml b/cdp-iaas/pom.xml index 8193486..59ccda1 100644 --- a/cdp-iaas/pom.xml +++ b/cdp-iaas/pom.xml @@ -21,4 +21,6 @@ 8 - \ No newline at end of file + + + diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/pom.xml b/cdp-manager/backstage-manger-server/backstage-manger-server-service/pom.xml index 0c8c02f..0af51cc 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/pom.xml +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/pom.xml @@ -56,6 +56,8 @@ 1.0-SNAPSHOT + + com.alibaba druid-spring-boot-starter @@ -111,6 +113,13 @@ + + + com.baiye + cdp-common-exception + 1.0-SNAPSHOT + + diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/SystemServiceApplication.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/SystemServiceApplication.java index da37acb..cdd5101 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/SystemServiceApplication.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/SystemServiceApplication.java @@ -1,10 +1,12 @@ package com.baiye; +import com.baiye.annotation.EnableCustomizeFeignClient; +import com.baiye.annotation.EnableCustomizeResourceServer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** - * + * * @description 系统服务启动类 * @author Enzo * @date 2020-08-06 17:49 diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DataController.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DataController.java index 6631dd0..e1fb6a9 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DataController.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DataController.java @@ -4,8 +4,6 @@ import com.baiye.dto.UserDto; import com.baiye.service.IDataService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; - -import lombok.extern.java.Log; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; @@ -15,7 +13,7 @@ import org.springframework.web.bind.annotation.RestController; import java.util.List; /** - * + * * @description 数据权限前端视图控制器 * @author Enzo * @create: 2020-08-13 14:22 diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DeptController.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DeptController.java index 8189250..afc99ee 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DeptController.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DeptController.java @@ -9,8 +9,6 @@ import com.baiye.service.IDeptService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; - -import lombok.extern.java.Log; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; @@ -25,7 +23,7 @@ import java.util.List; import java.util.Map; /** - * + * * @description 部门前端控制器 * @author Enzo * @create: 2020-08-07 13:01 diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DictController.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DictController.java index a741427..cb71bc4 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DictController.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DictController.java @@ -22,6 +22,10 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; +/** + * @author Enzo + * @date 2022-5-17 + */ @RestController @RequiredArgsConstructor @Api(tags = "系统:字典管理") diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DictDetailController.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DictDetailController.java index 9d23e94..80503b1 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DictDetailController.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/DictDetailController.java @@ -24,6 +24,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +/** + * @author Enzo + * @date 2022-5-17 + */ @RestController @RequiredArgsConstructor @Api(tags = "系统:字典详情管理") diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/PictureController.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/PictureController.java new file mode 100644 index 0000000..9d7802b --- /dev/null +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/PictureController.java @@ -0,0 +1,47 @@ +package com.baiye.controller; + +import cn.hutool.core.text.CharSequenceUtil; +import com.baiye.exception.global.BadRequestException; +import com.baiye.properties.FileProperties; +import com.baiye.util.FileUtil; +import com.google.common.collect.ImmutableMap; +import io.swagger.annotations.ApiOperation; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; + +/** + * @author Enzo + * @date : 2022/1/25 + */ +@RestController +@RequestMapping("/pictures") +@RequiredArgsConstructor +public class PictureController { + private final FileProperties properties; + + @ApiOperation("修改头像") + @PostMapping(value = "/upload") + public ResponseEntity updateAvatar(@RequestParam("file") MultipartFile uploadFile) { + String image = "gif jpg png jpeg"; + String fileType = FileUtil.getExtensionName + (uploadFile.getOriginalFilename()); + if (fileType != null && !image.contains(fileType)) { + throw new BadRequestException("文件格式错误!, 仅支持 " + image + " 格式"); + } + // 应改为File路径 + File file = FileUtil.upload + (uploadFile, properties.getPath().getAvatar()); + ImmutableMap picture = ImmutableMap.of + ("picture", file != null + ? file.getName() : CharSequenceUtil.SPACE); + return new ResponseEntity<>(picture, HttpStatus.OK); + } +} diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/SysUserController.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/UserController.java similarity index 97% rename from cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/SysUserController.java rename to cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/UserController.java index 0b59afd..c193038 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/SysUserController.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/UserController.java @@ -31,15 +31,19 @@ import java.io.IOException; import java.util.*; import java.util.stream.Collectors; +/** + * @author Enzo + * @date 2022-5-17 + */ @Api(tags = "系统:用户管理") @Slf4j @RestController @RequestMapping("/users") @RequiredArgsConstructor -public class SysUserController { +public class UserController { private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); - private final ISysUserService userService; + private final IUserService userService; private final IDataService dataService; private final IDeptService deptService; private final IRoleService roleService; @@ -51,7 +55,6 @@ public class SysUserController { this.userService.download(this.userService.queryAll(queryCriteria), response); } - // @Log("获取当前的用户信息") @ApiOperation("获取当前的用户信息") @GetMapping(value = "/info") @PreAuthorize("@el.check('user:list')") @@ -92,7 +95,7 @@ public class SysUserController { queryCriteria.getDeptIds().addAll(dataScopes); return new ResponseEntity<>(userService.queryAll(queryCriteria,pageable),HttpStatus.OK); } - return new ResponseEntity<>(null,HttpStatus.OK); + return new ResponseEntity<>(null, HttpStatus.OK); } @ApiOperation("新增用户") diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/UserDetailsController.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/UserDetailsController.java index f4a2821..043ca63 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/UserDetailsController.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/controller/UserDetailsController.java @@ -1,8 +1,8 @@ package com.baiye.controller; -import com.baiye.Inner; +import com.baiye.annotation.Inner; import com.baiye.dto.UserSmallDto; -import com.baiye.service.ISysUserService; +import com.baiye.service.IUserService; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; @@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** - * + * * @description 内部接口, 根据用户名加载用户信息,仅供feigin调用 * @author Enzo * @create: 2020-08-16 19:42 @@ -22,7 +22,7 @@ import org.springframework.web.bind.annotation.RestController; @RequiredArgsConstructor public class UserDetailsController { - private final ISysUserService userService; + private final IUserService userService; diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/ISysUserService.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/IUserService.java similarity index 94% rename from cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/ISysUserService.java rename to cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/IUserService.java index 497cdbe..8a33876 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/ISysUserService.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/IUserService.java @@ -15,12 +15,12 @@ import java.util.Map; import java.util.Set; /** - * + * * @description * @author Enzo * @create: 2020-08-10 21:26 */ -public interface ISysUserService extends IService { +public interface IUserService extends IService { /** * 查询所有,不进行分页 * @param queryCriteria @@ -90,10 +90,10 @@ public interface ISysUserService extends IService { /** * 修改用户的头像 - * @param avatar + * @param multipartFile * @return */ - Map updateAvatar(MultipartFile avatar); + Map updateAvatar(MultipartFile multipartFile); /** * 更新邮箱信息 diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/DeptServiceImpl.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/DeptServiceImpl.java index 403c539..7b805d2 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/DeptServiceImpl.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/DeptServiceImpl.java @@ -42,7 +42,7 @@ import java.util.*; import java.util.stream.Collectors; /** - * + * * @description 部门业务实现类 * @author Enzo * @create: 2020-08-07 14:18 @@ -285,7 +285,6 @@ public class DeptServiceImpl extends ServiceImpl implements ID */ @Override public void delCaches(Long id, Long oldDeptPid, Long newDeptPid) { - // TODO: 2020/8/8 删除用户拥有的部门权限,后续处理(已处理) List relations = this.userRoleMapper.selectByDeptId(id); Set userIds = relations.stream().map(UserRoleRelation::getUserId).collect(Collectors.toSet()); // 删除数据权限 @@ -368,7 +367,7 @@ public class DeptServiceImpl extends ServiceImpl implements ID * @param deptDtos */ private void verification(List deptDtos) { - // TODO: 2020/8/8 对部门与用户进行验证,看是否有部门与用户绑定或者与某个角色绑定(已解决) + // 查询是否与用户绑定,即该部门下是否存在用户 Set deptIds = deptDtos.stream().map(DeptDto::getId).collect(Collectors.toSet()); Integer count = this.userMapper.selectCount(Wrappers.lambdaQuery().in(User::getDeptId, deptIds)); diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/JobServiceImpl.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/JobServiceImpl.java index 3c9221f..c54137d 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/JobServiceImpl.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/JobServiceImpl.java @@ -36,7 +36,7 @@ import java.util.Objects; import java.util.Set; /** - * + * * @description 职位业务实现类 * @author Enzo * @create: 2020-08-10 16:30 @@ -148,7 +148,6 @@ public class JobServiceImpl extends ServiceImpl implements IJobS */ @Override public void verification(Set ids) { - // TODO: 2020/8/10 需要UserMapper,后续添加(已解决) Integer count = this.userJobMapper.selectCount(Wrappers.lambdaQuery() .in(UserJobRelation::getJobId, ids)); if (!count.equals(0)){ diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/MenuServiceImpl.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/MenuServiceImpl.java index 867bf98..aa6b15a 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/MenuServiceImpl.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/MenuServiceImpl.java @@ -44,7 +44,7 @@ import java.util.*; import java.util.stream.Collectors; /** - * + * * @description 菜单业务实现类 * @author Enzo * @create: 2020-08-12 18:24 @@ -319,7 +319,6 @@ public class MenuServiceImpl extends ServiceImpl implements IM } menuVos.add(menuVo); } - }); return menuVos; } diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/SysUserServiceImpl.java b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/UserServiceImpl.java similarity index 90% rename from cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/SysUserServiceImpl.java rename to cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/UserServiceImpl.java index 70edf17..21430ab 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/SysUserServiceImpl.java +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/java/com/baiye/service/impl/UserServiceImpl.java @@ -2,7 +2,9 @@ package com.baiye.service.impl; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.text.CharSequenceUtil; import com.baiye.*; +import com.baiye.core.base.api.ResultCode; import com.baiye.core.constant.CacheKey; import com.baiye.core.page.PageResult; import com.baiye.core.util.FileUtils; @@ -10,17 +12,16 @@ import com.baiye.core.util.RedisUtils; import com.baiye.core.util.StringUtils; import com.baiye.dto.UserDto; import com.baiye.dto.UserSmallDto; -import com.baiye.exception.global.CreateFailException; -import com.baiye.exception.global.DeleteFailException; -import com.baiye.exception.global.EntityExistException; -import com.baiye.exception.global.UpdateFailException; +import com.baiye.exception.global.*; import com.baiye.feign.IRemoteAuthService; import com.baiye.mapper.UserMapper; import com.baiye.mapper.UserJobMapper; import com.baiye.mapper.UserRoleMapper; import com.baiye.mapstruct.UserMapStruct; +import com.baiye.properties.FileProperties; import com.baiye.query.UserQueryCriteria; -import com.baiye.service.ISysUserService; +import com.baiye.service.IUserService; +import com.baiye.util.FileUtil; import com.baiye.util.PageUtils; import com.baiye.util.QueryHelpUtils; import com.baiye.util.SecurityUtils; @@ -28,6 +29,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; @@ -44,13 +46,15 @@ import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; +import javax.validation.constraints.NotBlank; +import java.io.File; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.*; import java.util.stream.Collectors; /** - * + * * @description 用户业务实现类 * @author Enzo * @create: 2020-08-11 16:17 @@ -59,10 +63,11 @@ import java.util.stream.Collectors; @Slf4j @CacheConfig(cacheNames = "user") @RequiredArgsConstructor -public class SysUserServiceImpl extends ServiceImpl implements ISysUserService { +public class UserServiceImpl extends ServiceImpl implements IUserService { private final UserMapper userMapper; + private final FileProperties properties; private final UserMapStruct userMapStruct; private final RedisUtils redisUtils; @@ -193,7 +198,7 @@ public class SysUserServiceImpl extends ServiceImpl implements try { this.remoteAuthService.delete(Collections.singleton(resources.getId())); } catch (Exception e) { - throw new RuntimeException(e); + throw new BadRequestException(ResultCode.FAILURE.getMsg()); } } /** @@ -376,14 +381,33 @@ public class SysUserServiceImpl extends ServiceImpl implements /** * 修改用户的头像 * - * @param avatar + * @param multipartFile * @return */ @Override @Transactional(rollbackFor = Exception.class) - public Map updateAvatar(MultipartFile avatar) { - // TODO: 2020/8/12 后续搭建文件上传微服务进行操作 - return null; + public Map updateAvatar(MultipartFile multipartFile) { + + // 文件大小验证 + FileUtil.checkSize(properties.getAvatarMaxSize(), multipartFile.getSize()); + // 验证文件上传的格式 + String image = "gif jpg png jpeg"; + String fileType = FileUtil.getExtensionName(multipartFile.getOriginalFilename()); + if (fileType != null && !image.contains(fileType)) { + throw new BadRequestException("文件格式错误!, 仅支持 " + image + " 格式"); + } + User user = userMapper.queryByUsername(SecurityUtils.getCurrentUsername()); + String oldPath = user.getAvatarPath(); + File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar()); + user.setAvatarPath(Objects.requireNonNull(file).getPath()); + user.setAvatarName(file.getName()); + userMapper.updateById(user); + if (CharSequenceUtil.isNotBlank(oldPath)) { + FileUtil.del(oldPath); + } + @NotBlank String username = user.getUsername(); + this.delCaches(user.getId(), username); + return ImmutableMap.of("avatar", file.getName()); } /** diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/resources/banner.txt b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/resources/banner.txt index d0f401a..b6cabaf 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/resources/banner.txt +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/resources/banner.txt @@ -1,8 +1,19 @@ - _ _ _ - | | | | (_) - ___| |______ __ _ __| |_ __ ___ _ _ __ - / _ | |______/ _` |/ _` | '_ ` _ \| | '_ \ - | __| | | (_| | (_| | | | | | | | | | | - \___|_| \__,_|\__,_|_| |_| |_|_|_| |_| - - :: Spring Boot :: (v2.1.0.RELEASE) \ No newline at end of file + , \ / , + / \ )\__/( / \ + / \ (_\ /_) / \ + __________________/_____\__\@ @/___/_____\_________________ + | ______ |\../| | + | ''|| \\ _____ \VV/ _____ ____ | + | || || //|| || \\ //|| || \\ // \\ \\ // | + | ||=='' // || || || // || || || || || \\_// | + | || //==|| ||=='' //==|| || || || || // \\ | + | || // || || \\ // || ||__// \\__// // \\ | + |__________________________________________________________| + | /\ / \\ \ /\ | + | / V )) V \ | + |/ ` // ' \| + ` V ' + + xx xx xx xx xx xx + xx xx xx xx xx xx xx xx +========================================================================= \ No newline at end of file diff --git a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/resources/config/application.yml b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/resources/config/application.yml index dc95aec..4326042 100644 --- a/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/resources/config/application.yml +++ b/cdp-manager/backstage-manger-server/backstage-manger-server-service/src/main/resources/config/application.yml @@ -61,3 +61,4 @@ snowflake: datacenterId: 9 +