修改异常返回错误

master
bynt 2 years ago
parent cbb5408850
commit 0d3c221d0b

@ -0,0 +1,23 @@
package com.baiye.core.base.api;
/**
*
*
* @author pangu
*/
public interface IResultCode {
/**
*
*
* @return int
*/
int getCode();
/**
*
*
* @return String
*/
String getMsg();
}

@ -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>  T
* @author pangu
*/
@Data
@Getter
@ApiModel(value = "统一响应消息报文")
public class Result<T> 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 <T>
* @return ApiResult
*/
public static <T> Result<T> success(IResultCode resultCode) {
return new Result<>(resultCode);
}
public static <T> Result<T> success(String msg) {
return new Result<>(ResultCode.SUCCESS, msg);
}
public static <T> Result<T> success(IResultCode resultCode, String msg) {
return new Result<>(resultCode, msg);
}
public static <T> Result<T> data(T data) {
return data(data, MessageConstant.DEFAULT_SUCCESS_MESSAGE);
}
public static <T> Result<T> data(T data, String msg) {
return data(ResultCode.SUCCESS.code, data, msg);
}
public static <T> Result<T> data(int code, T data, String msg) {
return new Result<>(code, data, data == null ? MessageConstant.DEFAULT_NULL_MESSAGE : msg);
}
public static <T> Result<T> fail() {
return new Result<>(ResultCode.FAILURE, ResultCode.FAILURE.getMsg());
}
public static <T> Result<T> fail(String msg) {
return new Result<>(ResultCode.FAILURE, msg);
}
public static <T> Result<T> fail(int code, String msg) {
return new Result<>(code, null, msg);
}
public static <T> Result<T> fail(IResultCode resultCode) {
return new Result<>(resultCode);
}
public static <T> Result<T> fail(IResultCode resultCode, String msg) {
return new Result<>(resultCode, msg);
}
public static <T> Result<T> condition(boolean flag) {
return flag ? success(MessageConstant.DEFAULT_SUCCESS_MESSAGE) : fail(MessageConstant.DEFAULT_FAIL_MESSAGE);
}
}

@ -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;
}

@ -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;
/**
* jsonUTF-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;
}

@ -0,0 +1,151 @@
package com.baiye.core.constant;
/**
*
*
* @author david
*/
public class WebConstant {
/**
* jsonUTF-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;
}
}
}

@ -25,7 +25,6 @@ import java.util.Objects;
* @date 2022-05-14
*/
@Slf4j
public final class RequestUtils {
private RequestUtils(){}

@ -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<Void>
*/
public static Mono<Void> 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));
}
}

@ -25,7 +25,7 @@ import java.time.LocalDateTime;
* @date 2018-11-23
*/
@Data
class ApiError {
public class ApiError {
private Integer status = 400;

@ -1,2 +0,0 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.baiye.exception.global.handle.GlobalExceptionHandler

@ -1,4 +1,4 @@
package com.baiye;
package com.baiye.annotation;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;

@ -1,4 +1,4 @@
package com.baiye;
package com.baiye.annotation;
import com.baiye.config.ResourceServerAutoConfiguration;
import com.baiye.component.PermissionComponent;

@ -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

@ -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<OAuth2Exception> 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));

@ -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;

@ -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<String> urls = new ArrayList<>();
private List<String> client = new ArrayList<>();
private List<String> ignoreSecurity = new ArrayList<>();
/**
* ENDPOINTS
*/
@PostConstruct
public void initIgnoreSecurity() {
Collections.addAll(ignoreSecurity, SECURITY_ENDPOINTS);
}
}

@ -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

@ -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

@ -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);
}
}

@ -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);
}

@ -1,3 +1,4 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.baiye.component.InnerAspect,\
com.baiye.service.UserDetailsServiceImpl
com.baiye.service.UserDetailsServiceImpl,\
com.baiye.config.IgnoreUrlPropsConfiguration

@ -26,10 +26,6 @@
<groupId>com.baiye</groupId>
<artifactId>cdp-common-security</artifactId>
<exclusions>
<exclusion>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
</exclusion>
<exclusion>
<artifactId>HdrHistogram</artifactId>
<groupId>org.hdrhistogram</groupId>
@ -57,6 +53,14 @@
<artifactId>jasypt-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baiye</groupId>
<artifactId>cdp-common-exception</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<!-- 配置插件 -->

@ -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();
}
}

@ -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<String, Object> additionalInformation = new LinkedHashMap<String, Object>(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<String, Object> additionalInformation = new LinkedHashMap<String, Object>(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;
};
}

@ -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, auth2WebSecurityConfigurerAdapterAuthorizationServerConfigurerAdapter
*
* @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<HttpSecurity>.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();
}
}

@ -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);

@ -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);
}
}
}

@ -62,16 +62,15 @@ public class OnlineServiceImpl implements IOnlineUserService {
public void saveOnlineUser(OAuth2AccessToken accessToken) {
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
Map<String, Object> 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);
}

@ -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<ApiError> buildResponseEntity(ApiError apiError) {
return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
}
}

@ -0,0 +1,19 @@
, \ / ,
/ \ )\__/( / \
/ \ (_\ /_) / \
__________________/_____\__\@ @/___/_____\_________________
| ______ |\../| |
| ''|| \\ _____ \VV/ _____ ____ |
| || || //|| || \\ //|| || \\ // \\ \\ // |
| ||=='' // || || || // || || || || || \\_// |
| || //==|| ||=='' //==|| || || || || // \\ |
| || // || || \\ // || ||__// \\__// // \\ |
|__________________________________________________________|
| /\ / \\ \ /\ |
| / V )) V \ |
|/ ` // ' \|
` V '
xx xx xx xx xx xx
xx xx xx xx xx xx xx xx
=========================================================================

@ -30,3 +30,5 @@ spring:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
profiles:
active: dev
ip:
local-parsing: true

@ -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();
}*/
}
}
*/

@ -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<Object> {
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<String, String> 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);

@ -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<String, Object> createCapcha() throws IOException, CaptchaException {
public Map<String, Object> 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("验证码错误");

@ -0,0 +1,19 @@
, \ / ,
/ \ )\__/( / \
/ \ (_\ /_) / \
__________________/_____\__\@ @/___/_____\_________________
| ______ |\../| |
| ''|| \\ _____ \VV/ _____ ____ |
| || || //|| || \\ //|| || \\ // \\ \\ // |
| ||=='' // || || || // || || || || || \\_// |
| || //==|| ||=='' //==|| || || || || // \\ |
| || // || || \\ // || ||__// \\__// // \\ |
|__________________________________________________________|
| /\ / \\ \ /\ |
| / V )) V \ |
|/ ` // ' \|
` V '
xx xx xx xx xx xx
xx xx xx xx xx xx xx xx
=========================================================================

@ -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

@ -21,4 +21,6 @@
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
</project>

@ -56,6 +56,8 @@
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
@ -111,6 +113,13 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.baiye</groupId>
<artifactId>cdp-common-exception</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<!-- 配置插件 -->

@ -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

@ -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

@ -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

@ -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 = "系统:字典管理")

@ -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 = "系统:字典详情管理")

@ -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<Object> 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<String, String> picture = ImmutableMap.of
("picture", file != null
? file.getName() : CharSequenceUtil.SPACE);
return new ResponseEntity<>(picture, HttpStatus.OK);
}
}

@ -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("新增用户")

@ -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;

@ -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<User> {
public interface IUserService extends IService<User> {
/**
*
* @param queryCriteria
@ -90,10 +90,10 @@ public interface ISysUserService extends IService<User> {
/**
*
* @param avatar
* @param multipartFile
* @return
*/
Map<String,String> updateAvatar(MultipartFile avatar);
Map<String,String> updateAvatar(MultipartFile multipartFile);
/**
*

@ -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<DeptMapper, Dept> implements ID
*/
@Override
public void delCaches(Long id, Long oldDeptPid, Long newDeptPid) {
// TODO: 2020/8/8 删除用户拥有的部门权限,后续处理(已处理)
List<UserRoleRelation> relations = this.userRoleMapper.selectByDeptId(id);
Set<Long> userIds = relations.stream().map(UserRoleRelation::getUserId).collect(Collectors.toSet());
// 删除数据权限
@ -368,7 +367,7 @@ public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements ID
* @param deptDtos
*/
private void verification(List<DeptDto> deptDtos) {
// TODO: 2020/8/8 对部门与用户进行验证,看是否有部门与用户绑定或者与某个角色绑定(已解决)
// 查询是否与用户绑定,即该部门下是否存在用户
Set<Long> deptIds = deptDtos.stream().map(DeptDto::getId).collect(Collectors.toSet());
Integer count = this.userMapper.selectCount(Wrappers.<User>lambdaQuery().in(User::getDeptId, deptIds));

@ -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<JobMapper, Job> implements IJobS
*/
@Override
public void verification(Set<Long> ids) {
// TODO: 2020/8/10 需要UserMapper后续添加(已解决)
Integer count = this.userJobMapper.selectCount(Wrappers.<UserJobRelation>lambdaQuery()
.in(UserJobRelation::getJobId, ids));
if (!count.equals(0)){

@ -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<MenuMapper, Menu> implements IM
}
menuVos.add(menuVo);
}
});
return menuVos;
}

@ -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<UserMapper, User> implements ISysUserService {
public class UserServiceImpl extends ServiceImpl<UserMapper, User> 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<UserMapper, User> 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<UserMapper, User> implements
/**
*
*
* @param avatar
* @param multipartFile
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Map<String, String> updateAvatar(MultipartFile avatar) {
// TODO: 2020/8/12 后续搭建文件上传微服务进行操作
return null;
public Map<String, String> 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());
}
/**

@ -1,8 +1,19 @@
_ _ _
| | | | (_)
___| |______ __ _ __| |_ __ ___ _ _ __
/ _ | |______/ _` |/ _` | '_ ` _ \| | '_ \
| __| | | (_| | (_| | | | | | | | | | |
\___|_| \__,_|\__,_|_| |_| |_|_|_| |_|
:: Spring Boot :: (v2.1.0.RELEASE)
, \ / ,
/ \ )\__/( / \
/ \ (_\ /_) / \
__________________/_____\__\@ @/___/_____\_________________
| ______ |\../| |
| ''|| \\ _____ \VV/ _____ ____ |
| || || //|| || \\ //|| || \\ // \\ \\ // |
| ||=='' // || || || // || || || || || \\_// |
| || //==|| ||=='' //==|| || || || || // \\ |
| || // || || \\ // || ||__// \\__// // \\ |
|__________________________________________________________|
| /\ / \\ \ /\ |
| / V )) V \ |
|/ ` // ' \|
` V '
xx xx xx xx xx xx
xx xx xx xx xx xx xx xx
=========================================================================
Loading…
Cancel
Save