From adbf6e6e8eeb6caaa0afa7af4057c4fedaa0e781 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 14 May 2018 10:17:52 +0800 Subject: [PATCH 01/18] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E7=A0=81=E5=A4=A7=E5=B0=8F=EF=BC=8C=E8=A7=A3=E5=86=B3=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E4=B8=8D=E5=85=A8=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/pig/common/constant/SecurityConstants.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pig-common/src/main/java/com/github/pig/common/constant/SecurityConstants.java b/pig-common/src/main/java/com/github/pig/common/constant/SecurityConstants.java index e763d5dd..a3fe13dc 100644 --- a/pig-common/src/main/java/com/github/pig/common/constant/SecurityConstants.java +++ b/pig-common/src/main/java/com/github/pig/common/constant/SecurityConstants.java @@ -62,12 +62,12 @@ public interface SecurityConstants { /** * 默认生成图形验证码宽度 */ - String DEFAULT_IMAGE_WIDTH = "150"; + String DEFAULT_IMAGE_WIDTH = "100"; /** * 默认生成图像验证码高度 */ - String DEFAULT_IMAGE_HEIGHT = "32"; + String DEFAULT_IMAGE_HEIGHT = "40"; /** * 默认生成图形验证码长度 From 30561b89467cb6bf9e2dee4cdacd2f72b318fb5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A6=82=E6=A2=A6=E6=8A=80=E6=9C=AF?= <596392912@qq.com> Date: Mon, 14 May 2018 13:57:51 +0800 Subject: [PATCH 02/18] =?UTF-8?q?feat:=20=E4=BF=AE=E6=94=B9=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E7=A0=81=20security.validate.code.enabled=20=E5=BC=80?= =?UTF-8?q?=E5=90=AF=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../component/filter/ValidateCodeFilter.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java b/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java index 3b349b55..bcb46d40 100644 --- a/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java +++ b/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java @@ -11,8 +11,10 @@ import com.xiaoleilu.hutool.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; +import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; @@ -21,17 +23,19 @@ import javax.servlet.http.HttpServletRequest; /** * @author lengleng * @date 2018/5/10 + * + * security.validate.code.enabled 默认 为false,开启需要设置为true + * * 验证码校验,true开启,false关闭校验 * 更细化可以 clientId 进行区分 */ @Slf4j @RefreshScope -@Component("validateCodeFilter") +@Configuration("validateCodeFilter") +@ConditionalOnProperty(value = "security.validate.code.enabled", havingValue = "true") public class ValidateCodeFilter extends ZuulFilter { private static final String EXPIRED_CAPTCHA_ERROR = "验证码已过期,请重新获取"; - @Value("${security.validate.code:true}") - private boolean isValidate; @Autowired private RedisTemplate redisTemplate; @@ -48,8 +52,8 @@ public class ValidateCodeFilter extends ZuulFilter { @Override public boolean shouldFilter() { HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); - if (isValidate && (StrUtil.containsIgnoreCase(request.getRequestURI(), SecurityConstants.OAUTH_TOKEN_URL) - || StrUtil.containsIgnoreCase(request.getRequestURI(), SecurityConstants.MOBILE_TOKEN_URL))) { + if (StrUtil.containsIgnoreCase(request.getRequestURI(), SecurityConstants.OAUTH_TOKEN_URL) + || StrUtil.containsIgnoreCase(request.getRequestURI(), SecurityConstants.MOBILE_TOKEN_URL)) { return true; } return false; From ff9ea3f0dda11492169ef9c9fef2cf9c49857dce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=AF=BB=E6=AC=A2?= Date: Mon, 14 May 2018 18:47:05 +0800 Subject: [PATCH 03/18] =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=9F=AD=E4=BF=A1?= =?UTF-8?q?=E6=8F=90=E9=86=92=E7=9B=B8=E5=85=B3=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../enums/EnumSmsChannelTemplate.java | 39 +++++++++++++++++ .../util/template/MobileMsgTemplate.java | 27 +++++++++--- .../mc/handler/SmsAliyunMessageHandler.java | 20 ++++----- .../listener/MobileCodeReceiveListener.java | 2 +- .../MobileServiceChangeReceiveListener.java | 2 +- .../constant/SmsChannelTemplateConstant.java | 13 ------ .../mc/utils/sms/EnumSmsChannelTemplate.java | 42 ------------------- .../service/impl/SysUserServiceImpl.java | 15 ++++++- .../monitor/filter/StatusChangeNotifier.java | 16 +++++-- 9 files changed, 98 insertions(+), 78 deletions(-) create mode 100644 pig-common/src/main/java/com/github/pig/common/constant/enums/EnumSmsChannelTemplate.java delete mode 100644 pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/utils/constant/SmsChannelTemplateConstant.java delete mode 100644 pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/utils/sms/EnumSmsChannelTemplate.java diff --git a/pig-common/src/main/java/com/github/pig/common/constant/enums/EnumSmsChannelTemplate.java b/pig-common/src/main/java/com/github/pig/common/constant/enums/EnumSmsChannelTemplate.java new file mode 100644 index 00000000..1e641a1e --- /dev/null +++ b/pig-common/src/main/java/com/github/pig/common/constant/enums/EnumSmsChannelTemplate.java @@ -0,0 +1,39 @@ +package com.github.pig.common.constant.enums; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author LiXunHuan + * @date 2018/1/16 + * 短信通道模板 + */ +public enum EnumSmsChannelTemplate { + /** + * 登录验证 + */ + LOGIN_NAME_LOGIN("loginCodeChannel", "登录验证"), + /** + * 服务异常提醒 + */ + SERVICE_STATUS_CHANGE("serviceStatusChange", "Pig4Cloud"); + + + /** + * 模板名称 + */ + @Getter + @Setter + private String template; + /** + * 模板签名 + */ + @Getter + @Setter + private String signName; + + EnumSmsChannelTemplate(String template, String signName) { + this.template = template; + this.signName = signName; + } +} diff --git a/pig-common/src/main/java/com/github/pig/common/util/template/MobileMsgTemplate.java b/pig-common/src/main/java/com/github/pig/common/util/template/MobileMsgTemplate.java index 64d1204d..1ddd8007 100644 --- a/pig-common/src/main/java/com/github/pig/common/util/template/MobileMsgTemplate.java +++ b/pig-common/src/main/java/com/github/pig/common/util/template/MobileMsgTemplate.java @@ -16,17 +16,32 @@ public class MobileMsgTemplate implements Serializable { */ private String mobile; /** - * 文本 + * 组装后的模板内容JSON字符串 */ - private String text; + private String context; /** - * 类型(通道) + * 短信通道 + */ + private String channel; + /** + * 短信类型(验证码或者通知短信) + * 暂时不用,留着后面存数据库备用吧 */ private String type; + /** + * 短信签名 + */ + private String signName; + /** + * 短信模板 + */ + private String template; - public MobileMsgTemplate(String mobile, String text, String type) { + public MobileMsgTemplate(String mobile, String context, String channel, String signName, String template){ this.mobile = mobile; - this.text = text; - this.type = type; + this.context = context; + this.channel = channel; + this.signName = signName; + this.template = template; } } diff --git a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/handler/SmsAliyunMessageHandler.java b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/handler/SmsAliyunMessageHandler.java index 32412e03..16bab146 100644 --- a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/handler/SmsAliyunMessageHandler.java +++ b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/handler/SmsAliyunMessageHandler.java @@ -1,6 +1,5 @@ package com.github.pig.mc.handler; -import com.alibaba.fastjson.JSONObject; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; @@ -12,8 +11,6 @@ import com.github.pig.common.constant.CommonConstant; import com.github.pig.common.util.Assert; import com.github.pig.common.util.template.MobileMsgTemplate; import com.github.pig.mc.config.SmsAliyunPropertiesConfig; -import com.github.pig.mc.utils.constant.SmsChannelTemplateConstant; -import com.github.pig.mc.utils.sms.EnumSmsChannelTemplate; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -39,7 +36,7 @@ public class SmsAliyunMessageHandler extends AbstractMessageHandler { @Override public void check(MobileMsgTemplate mobileMsgTemplate) { Assert.isBlank(mobileMsgTemplate.getMobile(), "手机号不能为空"); - Assert.isBlank(mobileMsgTemplate.getText(), "验证码不能为空"); + Assert.isBlank(mobileMsgTemplate.getContext(), "短信内容不能为空"); } /** @@ -67,20 +64,21 @@ public class SmsAliyunMessageHandler extends AbstractMessageHandler { SendSmsRequest request = new SendSmsRequest(); //必填:待发送手机号 request.setPhoneNumbers(mobileMsgTemplate.getMobile()); + //必填:短信签名-可在短信控制台中找到 - request.setSignName(EnumSmsChannelTemplate.LOGIN_NAME_LOGIN.getDescription()); + request.setSignName(mobileMsgTemplate.getSignName()); + //必填:短信模板-可在短信控制台中找到 - request.setTemplateCode(smsAliyunPropertiesConfig.getChannels().get(SmsChannelTemplateConstant.LOGIN_NAME_LOGIN)); - //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 - JSONObject jsonObject = new JSONObject(); - jsonObject.put("product", "pig_cloud"); - jsonObject.put("code", mobileMsgTemplate.getText()); - request.setTemplateParam(jsonObject.toJSONString()); + request.setTemplateCode(smsAliyunPropertiesConfig.getChannels().get(mobileMsgTemplate.getTemplate())); + + //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}" + request.setTemplateParam(mobileMsgTemplate.getContext()); request.setOutId(mobileMsgTemplate.getMobile()); //hint 此处可能会抛出异常,注意catch try { SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); + log.info("短信发送完毕,手机号:{},返回状态:{}", mobileMsgTemplate.getMobile(), sendSmsResponse.getCode()); } catch (ClientException e) { log.error("发送异常"); e.printStackTrace(); diff --git a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileCodeReceiveListener.java b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileCodeReceiveListener.java index 302a5460..4c6b427b 100644 --- a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileCodeReceiveListener.java +++ b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileCodeReceiveListener.java @@ -26,7 +26,7 @@ public class MobileCodeReceiveListener { @RabbitHandler public void receive(MobileMsgTemplate mobileMsgTemplate) { long startTime = System.currentTimeMillis(); - log.info("消息中心接收到短信发送请求-> 手机号:{} -> 验证码: {} ", mobileMsgTemplate.getMobile(), mobileMsgTemplate.getText()); + log.info("消息中心接收到短信发送请求-> 手机号:{} -> 验证码: {} ", mobileMsgTemplate.getMobile(), mobileMsgTemplate.getContext()); String type = mobileMsgTemplate.getType(); SmsMessageHandler messageHandler = messageHandlerMap.get(type); messageHandler.execute(mobileMsgTemplate); diff --git a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileServiceChangeReceiveListener.java b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileServiceChangeReceiveListener.java index 49911677..6b8f9f3a 100644 --- a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileServiceChangeReceiveListener.java +++ b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileServiceChangeReceiveListener.java @@ -19,7 +19,7 @@ public class MobileServiceChangeReceiveListener { @RabbitHandler public void receive(MobileMsgTemplate mobileMsgTemplate) { long startTime = System.currentTimeMillis(); - log.info("消息中心接收到短信发送请求-> 手机号:{} -> 验证码: {} ", mobileMsgTemplate.getMobile(), mobileMsgTemplate.getText()); + log.info("消息中心接收到短信发送请求-> 手机号:{} -> 验证码: {} ", mobileMsgTemplate.getMobile(), mobileMsgTemplate.getContext()); long useTime = System.currentTimeMillis() - startTime; log.info("调用 {} 短信网关处理完毕,耗时 {}毫秒", mobileMsgTemplate.getType(), useTime); } diff --git a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/utils/constant/SmsChannelTemplateConstant.java b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/utils/constant/SmsChannelTemplateConstant.java deleted file mode 100644 index 6feb7b28..00000000 --- a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/utils/constant/SmsChannelTemplateConstant.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.github.pig.mc.utils.constant; - -/** - * @author lengleng - * @date 2018/1/16 - * 短信通道模板常量 - */ -public interface SmsChannelTemplateConstant { - /** - * 登录验证码 - */ - String LOGIN_NAME_LOGIN = "loginCodeChannel"; -} diff --git a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/utils/sms/EnumSmsChannelTemplate.java b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/utils/sms/EnumSmsChannelTemplate.java deleted file mode 100644 index b0072c2e..00000000 --- a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/utils/sms/EnumSmsChannelTemplate.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.github.pig.mc.utils.sms; - -/** - * @author lengleng - * @date 2018/1/16 - * 短信通道模板 - */ -public enum EnumSmsChannelTemplate { - /** - * 登录验证 - */ - LOGIN_NAME_LOGIN("loginCodeChannel", "登录验证"); - /** - * 模板名称 - */ - private String name; - /** - * 模板签名 - */ - private String description; - - EnumSmsChannelTemplate(String name, String description) { - this.name = name; - this.description = description; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysUserServiceImpl.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysUserServiceImpl.java index 7eb13bcc..a17e57f3 100644 --- a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysUserServiceImpl.java +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysUserServiceImpl.java @@ -1,5 +1,6 @@ package com.github.pig.admin.service.impl; +import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.impl.ServiceImpl; @@ -17,6 +18,8 @@ import com.github.pig.common.bean.interceptor.DataScope; import com.github.pig.common.constant.CommonConstant; import com.github.pig.common.constant.MqQueueConstant; import com.github.pig.common.constant.SecurityConstants; +import com.github.pig.common.constant.enums.EnumSmsChannel; +import com.github.pig.common.constant.enums.EnumSmsChannelTemplate; import com.github.pig.common.util.Query; import com.github.pig.common.util.R; import com.github.pig.common.util.UserUtils; @@ -181,8 +184,18 @@ public class SysUserServiceImpl extends ServiceImpl impl } String code = RandomUtil.randomNumbers(4); + JSONObject contextJson = new JSONObject(); + contextJson.put("code", code); + contextJson.put("product", "Pig4Cloud"); log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code); - rabbitTemplate.convertAndSend(MqQueueConstant.MOBILE_CODE_QUEUE, new MobileMsgTemplate(mobile, code, CommonConstant.ALIYUN_SMS)); + rabbitTemplate.convertAndSend(MqQueueConstant.MOBILE_CODE_QUEUE, + new MobileMsgTemplate( + mobile, + contextJson.toJSONString(), + EnumSmsChannel.ALIYUN.getName(), + EnumSmsChannelTemplate.LOGIN_NAME_LOGIN.getSignName(), + EnumSmsChannelTemplate.LOGIN_NAME_LOGIN.getTemplate() + )); redisTemplate.opsForValue().set(SecurityConstants.DEFAULT_CODE_KEY + mobile, code, SecurityConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS); return new R<>(true); } diff --git a/pig-visual/pig-monitor/src/main/java/com/github/pig/monitor/filter/StatusChangeNotifier.java b/pig-visual/pig-monitor/src/main/java/com/github/pig/monitor/filter/StatusChangeNotifier.java index 43e044dc..18b9b484 100644 --- a/pig-visual/pig-monitor/src/main/java/com/github/pig/monitor/filter/StatusChangeNotifier.java +++ b/pig-visual/pig-monitor/src/main/java/com/github/pig/monitor/filter/StatusChangeNotifier.java @@ -3,7 +3,7 @@ package com.github.pig.monitor.filter; import com.alibaba.fastjson.JSONObject; import com.github.pig.common.constant.MqQueueConstant; import com.github.pig.common.constant.enums.EnumSmsChannel; -import com.github.pig.common.util.template.DingTalkMsgTemplate; +import com.github.pig.common.constant.enums.EnumSmsChannelTemplate; import com.github.pig.common.util.template.MobileMsgTemplate; import com.github.pig.monitor.config.MonitorPropertiesConfig; import com.xiaoleilu.hutool.collection.CollectionUtil; @@ -60,12 +60,22 @@ public class StatusChangeNotifier extends AbstractStatusChangeNotifier { event.getApplication().getId(), ((ClientApplicationStatusChangedEvent) event).getTo().getStatus()); String text = String.format("应用:%s 服务ID:%s 下线,时间:%s", event.getApplication().getName(), event.getApplication().getId(), DateUtil.date(event.getTimestamp()).toString()); + JSONObject contextJson = new JSONObject(); + contextJson.put("name", event.getApplication().getName()); + contextJson.put("seid", event.getApplication().getId()); + contextJson.put("time", DateUtil.date(event.getTimestamp()).toString()); + //开启短信通知 if (monitorMobilePropertiesConfig.getMobile().getEnabled()) { log.info("开始短信通知,内容:{}", text); rabbitTemplate.convertAndSend(MqQueueConstant.MOBILE_SERVICE_STATUS_CHANGE, - new MobileMsgTemplate(CollectionUtil.join(monitorMobilePropertiesConfig.getMobile().getMobiles(), ","), - text, EnumSmsChannel.ALIYUN.getName())); + new MobileMsgTemplate( + CollectionUtil.join(monitorMobilePropertiesConfig.getMobile().getMobiles(), ","), + contextJson.toJSONString(), + EnumSmsChannel.ALIYUN.getName(), + EnumSmsChannelTemplate.SERVICE_STATUS_CHANGE.getSignName(), + EnumSmsChannelTemplate.SERVICE_STATUS_CHANGE.getTemplate() + )); } if (monitorMobilePropertiesConfig.getDingTalk().getEnabled()) { From b8a509105d502d9d75811596b79481e7f6a1f452 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=AF=BB=E6=AC=A2?= Date: Mon, 14 May 2018 18:49:44 +0800 Subject: [PATCH 04/18] =?UTF-8?q?=E4=BC=98=E5=8C=96=E7=9F=AD=E4=BF=A1?= =?UTF-8?q?=E6=8F=90=E9=86=92=E7=9B=B8=E5=85=B3=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MobileServiceChangeReceiveListener.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileServiceChangeReceiveListener.java b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileServiceChangeReceiveListener.java index 6b8f9f3a..883ee76d 100644 --- a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileServiceChangeReceiveListener.java +++ b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/listener/MobileServiceChangeReceiveListener.java @@ -2,11 +2,15 @@ package com.github.pig.mc.listener; import com.github.pig.common.constant.MqQueueConstant; import com.github.pig.common.util.template.MobileMsgTemplate; +import com.github.pig.mc.handler.SmsMessageHandler; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.Map; + /** * @author lengleng * @date 2018年01月25日15:59:00 @@ -16,10 +20,17 @@ import org.springframework.stereotype.Component; @Component @RabbitListener(queues = MqQueueConstant.MOBILE_SERVICE_STATUS_CHANGE) public class MobileServiceChangeReceiveListener { + @Autowired + private Map messageHandlerMap; + + @RabbitHandler public void receive(MobileMsgTemplate mobileMsgTemplate) { long startTime = System.currentTimeMillis(); - log.info("消息中心接收到短信发送请求-> 手机号:{} -> 验证码: {} ", mobileMsgTemplate.getMobile(), mobileMsgTemplate.getContext()); + log.info("消息中心接收到短信发送请求-> 手机号:{} -> 信息体:{} ", mobileMsgTemplate.getMobile(), mobileMsgTemplate.getContext()); + String type = mobileMsgTemplate.getType(); + SmsMessageHandler messageHandler = messageHandlerMap.get(type); + messageHandler.execute(mobileMsgTemplate); long useTime = System.currentTimeMillis() - startTime; log.info("调用 {} 短信网关处理完毕,耗时 {}毫秒", mobileMsgTemplate.getType(), useTime); } From c6e983d1ffd1679f4a6d77c0c620fb3525bcf02a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=86=B7=E5=86=B7?= Date: Mon, 14 May 2018 21:22:12 +0800 Subject: [PATCH 05/18] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pig-auth/pom.xml | 21 +++++ .../mobile/MobileLoginSuccessHandler.java | 30 +------ .../pig/auth/config/AuthServerConfig.java | 38 +++------ .../auth/config/PigAuthorizationConfig.java | 15 ++-- .../config/PigSecurityConfigurerAdapter.java | 8 +- pig-auth/src/main/resources/bootstrap.yml | 1 - ...java => FilterIgnorePropertiesConfig.java} | 18 ++-- .../common/constant/SecurityConstants.java | 24 ++++++ .../com/github/pig/common/util/AuthUtils.java | 82 +++++++++++++++++++ .../java/com/github/pig/common/vo/UserVO.java | 2 +- .../src/main/resources/logback-spring.xml | 2 +- pig-config/src/main/resources/bootstrap.yml | 4 +- pig-gateway/pom.xml | 5 -- .../config/ResourceServerConfiguration.java | 12 +-- .../component/filter/PreviewFilter.java | 14 ++-- .../component/filter/ValidateCodeFilter.java | 45 +++++++--- pig-modules/pig-mc-service/pom.xml | 5 -- .../mc/handler/SmsAliyunMessageHandler.java | 6 +- pig-modules/pig-upms-service/pom.xml | 5 -- .../pig/admin/model/entity/SysUser.java | 3 + pig-visual/pig-monitor/pom.xml | 4 - .../monitor/filter/StatusChangeNotifier.java | 6 +- 22 files changed, 214 insertions(+), 136 deletions(-) rename pig-common/src/main/java/com/github/pig/common/bean/config/{FilterUrlsPropertiesConfig.java => FilterIgnorePropertiesConfig.java} (53%) create mode 100644 pig-common/src/main/java/com/github/pig/common/util/AuthUtils.java diff --git a/pig-auth/pom.xml b/pig-auth/pom.xml index 63472227..cbb9f896 100644 --- a/pig-auth/pom.xml +++ b/pig-auth/pom.xml @@ -37,6 +37,27 @@ org.springframework.boot spring-boot-starter-freemarker + + + mysql + mysql-connector-java + + + + org.springframework.boot + spring-boot-starter-jdbc + + + org.apache.tomcat + tomcat-jdbc + + + + + + com.zaxxer + HikariCP + diff --git a/pig-auth/src/main/java/com/github/pig/auth/component/mobile/MobileLoginSuccessHandler.java b/pig-auth/src/main/java/com/github/pig/auth/component/mobile/MobileLoginSuccessHandler.java index 50240e0f..6347bd89 100644 --- a/pig-auth/src/main/java/com/github/pig/auth/component/mobile/MobileLoginSuccessHandler.java +++ b/pig-auth/src/main/java/com/github/pig/auth/component/mobile/MobileLoginSuccessHandler.java @@ -2,6 +2,7 @@ package com.github.pig.auth.component.mobile; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.pig.common.constant.CommonConstant; +import com.github.pig.common.util.AuthUtils; import com.xiaoleilu.hutool.map.MapUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,7 +55,7 @@ public class MobileLoginSuccessHandler implements AuthenticationSuccessHandler { } try { - String[] tokens = extractAndDecodeHeader(header); + String[] tokens = AuthUtils.extractAndDecodeHeader(header); assert tokens.length == 2; String clientId = tokens[0]; @@ -76,33 +77,6 @@ public class MobileLoginSuccessHandler implements AuthenticationSuccessHandler { } } - /** - * Decodes the header into a username and password. - * - * @throws BadCredentialsException if the Basic header is not present or is not valid - * Base64 - */ - private String[] extractAndDecodeHeader(String header) - throws IOException { - - byte[] base64Token = header.substring(6).getBytes("UTF-8"); - byte[] decoded; - try { - decoded = Base64.decode(base64Token); - } catch (IllegalArgumentException e) { - throw new BadCredentialsException( - "Failed to decode basic authentication token"); - } - - String token = new String(decoded, CommonConstant.UTF8); - - int delim = token.indexOf(":"); - - if (delim == -1) { - throw new BadCredentialsException("Invalid basic authentication token"); - } - return new String[]{token.substring(0, delim), token.substring(delim + 1)}; - } } diff --git a/pig-auth/src/main/java/com/github/pig/auth/config/AuthServerConfig.java b/pig-auth/src/main/java/com/github/pig/auth/config/AuthServerConfig.java index 8a41021b..b6a80626 100644 --- a/pig-auth/src/main/java/com/github/pig/auth/config/AuthServerConfig.java +++ b/pig-auth/src/main/java/com/github/pig/auth/config/AuthServerConfig.java @@ -1,40 +1,26 @@ package com.github.pig.auth.config; +import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; +import java.util.ArrayList; +import java.util.List; + /** * @author lengleng * @date 2017/10/28 */ +@Data @Configuration -@ConfigurationProperties(prefix = "pig.auth") +@ConfigurationProperties(prefix = "auth") public class AuthServerConfig { - private String clientId; - private String clientSecret; - private String scope; + private List clients = new ArrayList<>(); - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - - public String getClientSecret() { - return clientSecret; - } - - public void setClientSecret(String clientSecret) { - this.clientSecret = clientSecret; - } - - public String getScope() { - return scope; - } - - public void setScope(String scope) { - this.scope = scope; + @Data + class AuthServer { + private String clientId; + private String clientSecret; + private String scope; } } diff --git a/pig-auth/src/main/java/com/github/pig/auth/config/PigAuthorizationConfig.java b/pig-auth/src/main/java/com/github/pig/auth/config/PigAuthorizationConfig.java index 7fe11f89..c83de767 100644 --- a/pig-auth/src/main/java/com/github/pig/auth/config/PigAuthorizationConfig.java +++ b/pig-auth/src/main/java/com/github/pig/auth/config/PigAuthorizationConfig.java @@ -17,12 +17,14 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.A import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; import org.springframework.security.oauth2.provider.token.TokenEnhancer; import org.springframework.security.oauth2.provider.token.TokenEnhancerChain; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; +import javax.sql.DataSource; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -37,9 +39,8 @@ import java.util.Map; @Order(Integer.MIN_VALUE) @EnableAuthorizationServer public class PigAuthorizationConfig extends AuthorizationServerConfigurerAdapter { - @Autowired - private AuthServerConfig authServerConfig; + private DataSource dataSource; @Autowired private AuthenticationManager authenticationManager; @@ -52,12 +53,10 @@ public class PigAuthorizationConfig extends AuthorizationServerConfigurerAdapter @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { - clients.inMemory() - .withClient(authServerConfig.getClientId()) - .secret(authServerConfig.getClientSecret()) - .authorizedGrantTypes(SecurityConstants.REFRESH_TOKEN, SecurityConstants.PASSWORD, SecurityConstants.AUTHORIZATION_CODE) - .scopes(authServerConfig.getScope()) - .autoApprove(true); + JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource); + clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT); + clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT); + clients.withClientDetails(clientDetailsService); } @Override diff --git a/pig-auth/src/main/java/com/github/pig/auth/config/PigSecurityConfigurerAdapter.java b/pig-auth/src/main/java/com/github/pig/auth/config/PigSecurityConfigurerAdapter.java index 125935fc..bbdda151 100644 --- a/pig-auth/src/main/java/com/github/pig/auth/config/PigSecurityConfigurerAdapter.java +++ b/pig-auth/src/main/java/com/github/pig/auth/config/PigSecurityConfigurerAdapter.java @@ -1,7 +1,7 @@ package com.github.pig.auth.config; import com.github.pig.auth.component.mobile.MobileSecurityConfigurer; -import com.github.pig.common.bean.config.FilterUrlsPropertiesConfig; +import com.github.pig.common.bean.config.FilterIgnorePropertiesConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.context.annotation.Configuration; @@ -20,7 +20,7 @@ import org.springframework.security.config.annotation.web.configurers.Expression @EnableWebSecurity public class PigSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Autowired - private FilterUrlsPropertiesConfig filterUrlsPropertiesConfig; + private FilterIgnorePropertiesConfig filterIgnorePropertiesConfig; @Autowired private MobileSecurityConfigurer mobileSecurityConfigurer; @@ -31,9 +31,7 @@ public class PigSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { .loginProcessingUrl("/authentication/form") .and() .authorizeRequests(); - for (String url : filterUrlsPropertiesConfig.getAnon()) { - registry.antMatchers(url).permitAll(); - } + filterIgnorePropertiesConfig.getUrls().forEach(url -> registry.antMatchers(url).permitAll()); registry.anyRequest().authenticated() .and() .csrf().disable(); diff --git a/pig-auth/src/main/resources/bootstrap.yml b/pig-auth/src/main/resources/bootstrap.yml index 5ebd1749..499d3b78 100644 --- a/pig-auth/src/main/resources/bootstrap.yml +++ b/pig-auth/src/main/resources/bootstrap.yml @@ -11,7 +11,6 @@ spring: enabled: true profile: ${spring.profiles.active} label: ${spring.profiles.active} - --- spring: profiles: dev diff --git a/pig-common/src/main/java/com/github/pig/common/bean/config/FilterUrlsPropertiesConfig.java b/pig-common/src/main/java/com/github/pig/common/bean/config/FilterIgnorePropertiesConfig.java similarity index 53% rename from pig-common/src/main/java/com/github/pig/common/bean/config/FilterUrlsPropertiesConfig.java rename to pig-common/src/main/java/com/github/pig/common/bean/config/FilterIgnorePropertiesConfig.java index a161a387..1f50740d 100644 --- a/pig-common/src/main/java/com/github/pig/common/bean/config/FilterUrlsPropertiesConfig.java +++ b/pig-common/src/main/java/com/github/pig/common/bean/config/FilterIgnorePropertiesConfig.java @@ -1,5 +1,6 @@ package com.github.pig.common.bean.config; +import lombok.Data; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @@ -11,17 +12,12 @@ import java.util.List; * @author lengleng * @date 2018/1/9 */ +@Data @Configuration -@ConditionalOnExpression("!'${urls}'.isEmpty()") -@ConfigurationProperties(prefix = "urls") -public class FilterUrlsPropertiesConfig { - private List anon = new ArrayList<>(); +@ConditionalOnExpression("!'${ignore}'.isEmpty()") +@ConfigurationProperties(prefix = "ignore") +public class FilterIgnorePropertiesConfig { + private List urls = new ArrayList<>(); - public List getAnon() { - return anon; - } - - public void setAnon(List anon) { - this.anon = anon; - } + private List clients = new ArrayList<>(); } diff --git a/pig-common/src/main/java/com/github/pig/common/constant/SecurityConstants.java b/pig-common/src/main/java/com/github/pig/common/constant/SecurityConstants.java index a3fe13dc..35f338b3 100644 --- a/pig-common/src/main/java/com/github/pig/common/constant/SecurityConstants.java +++ b/pig-common/src/main/java/com/github/pig/common/constant/SecurityConstants.java @@ -114,4 +114,28 @@ public interface SecurityConstants { * 默认的social的注册地址 */ String DEFAULT_SOCIAL_SIGNUP_URL = "/social/signup"; + + /** + * sys_oauth_client_details 表的字段,不包括client_id、client_secret + */ + String CLIENT_FIELDS = "client_id, client_secret, resource_ids, scope, " + + "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, " + + "refresh_token_validity, additional_information, autoapprove"; + + /** + *JdbcClientDetailsService 查询语句 + */ + String BASE_FIND_STATEMENT = "select " + CLIENT_FIELDS + + " from sys_oauth_client_details"; + + /** + * 默认的查询语句 + */ + String DEFAULT_FIND_STATEMENT = BASE_FIND_STATEMENT + " order by client_id"; + + /** + * 按条件client_id 查询 + */ + String DEFAULT_SELECT_STATEMENT = BASE_FIND_STATEMENT + " where client_id = ?"; + } diff --git a/pig-common/src/main/java/com/github/pig/common/util/AuthUtils.java b/pig-common/src/main/java/com/github/pig/common/util/AuthUtils.java new file mode 100644 index 00000000..778730fa --- /dev/null +++ b/pig-common/src/main/java/com/github/pig/common/util/AuthUtils.java @@ -0,0 +1,82 @@ +package com.github.pig.common.util; + +import com.github.pig.common.constant.CommonConstant; +import com.github.pig.common.util.exception.CheckedException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.crypto.codec.Base64; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +/** + * @author lengleng + * @date 2018/5/13 + * 认证授权相关工具类 + */ +@Slf4j +public class AuthUtils { + private static final String BASIC_ = "Basic "; + + /** + * 从header 请求中的clientId/clientsecect + * + * @param header header中的参数 + * @throws CheckedException if the Basic header is not present or is not valid + * Base64 + */ + public static String[] extractAndDecodeHeader(String header) + throws IOException { + + byte[] base64Token = header.substring(6).getBytes("UTF-8"); + byte[] decoded; + try { + decoded = Base64.decode(base64Token); + } catch (IllegalArgumentException e) { + throw new CheckedException( + "Failed to decode basic authentication token"); + } + + String token = new String(decoded, CommonConstant.UTF8); + + int delim = token.indexOf(":"); + + if (delim == -1) { + throw new CheckedException("Invalid basic authentication token"); + } + return new String[]{token.substring(0, delim), token.substring(delim + 1)}; + } + + /** + * *从header 请求中的clientId/clientsecect + * + * @param request + * @return + * @throws IOException + */ + public static String[] extractAndDecodeHeader(HttpServletRequest request) + throws IOException { + String header = request.getHeader("Authorization"); + + if (header == null || !header.startsWith(BASIC_)) { + throw new CheckedException("请求头中client信息为空"); + } + + byte[] base64Token = header.substring(6).getBytes("UTF-8"); + byte[] decoded; + try { + decoded = Base64.decode(base64Token); + } catch (IllegalArgumentException e) { + throw new CheckedException( + "Failed to decode basic authentication token"); + } + + String token = new String(decoded, CommonConstant.UTF8); + + int delim = token.indexOf(":"); + + if (delim == -1) { + throw new CheckedException("Invalid basic authentication token"); + } + return new String[]{token.substring(0, delim), token.substring(delim + 1)}; + } +} diff --git a/pig-common/src/main/java/com/github/pig/common/vo/UserVO.java b/pig-common/src/main/java/com/github/pig/common/vo/UserVO.java index a03cb571..088fc041 100644 --- a/pig-common/src/main/java/com/github/pig/common/vo/UserVO.java +++ b/pig-common/src/main/java/com/github/pig/common/vo/UserVO.java @@ -64,5 +64,5 @@ public class UserVO implements Serializable { /** * 角色列表 */ - private List roleList = new ArrayList<>(); + private List roleList; } diff --git a/pig-common/src/main/resources/logback-spring.xml b/pig-common/src/main/resources/logback-spring.xml index 9dcc51b3..70528488 100644 --- a/pig-common/src/main/resources/logback-spring.xml +++ b/pig-common/src/main/resources/logback-spring.xml @@ -39,7 +39,7 @@ - + diff --git a/pig-config/src/main/resources/bootstrap.yml b/pig-config/src/main/resources/bootstrap.yml index e04a573d..d54aef06 100644 --- a/pig-config/src/main/resources/bootstrap.yml +++ b/pig-config/src/main/resources/bootstrap.yml @@ -10,7 +10,7 @@ spring: config: server: git: - uri: https://gitee.com/cqzqxq_lxh/pig-config.git + uri: https://gitee.com/hsLeng/pig-config.git default-label: ${spring.profiles.active} #解决监控down # 关闭安全管理 @@ -24,7 +24,7 @@ endpoints: spring: profiles: dev rabbitmq: - host: 127.0.0.1 + host: 139.224.200.249 port: 5682 username: pig password: lengleng diff --git a/pig-gateway/pom.xml b/pig-gateway/pom.xml index c7094539..01edf536 100644 --- a/pig-gateway/pom.xml +++ b/pig-gateway/pom.xml @@ -44,11 +44,6 @@ org.springframework.cloud spring-cloud-starter-feign - - - org.springframework.boot - spring-boot-starter-amqp - io.springfox diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java index 9aa3967d..185e83c5 100644 --- a/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java +++ b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java @@ -1,6 +1,6 @@ package com.github.pig.gateway.component.config; -import com.github.pig.common.bean.config.FilterUrlsPropertiesConfig; +import com.github.pig.common.bean.config.FilterIgnorePropertiesConfig; import com.github.pig.gateway.component.filter.ValidateCodeFilter; import com.github.pig.gateway.component.handler.PigAccessDeniedHandler; import org.springframework.beans.factory.annotation.Autowired; @@ -15,7 +15,6 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.E import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /** * @author lengleng * @date 2017/10/27 @@ -24,24 +23,19 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic @EnableResourceServer public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Autowired - private FilterUrlsPropertiesConfig filterUrlsPropertiesConfig; + private FilterIgnorePropertiesConfig filterIgnorePropertiesConfig; @Autowired private OAuth2WebSecurityExpressionHandler expressionHandler; @Autowired private PigAccessDeniedHandler pigAccessDeniedHandler; - @Autowired - private ValidateCodeFilter validateCodeFilter; @Override public void configure(HttpSecurity http) throws Exception { - //http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class); //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题 http.headers().frameOptions().disable(); ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry registry = http .authorizeRequests(); - for (String url : filterUrlsPropertiesConfig.getAnon()) { - registry.antMatchers(url).permitAll(); - } + filterIgnorePropertiesConfig.getUrls().forEach(url -> registry.antMatchers(url).permitAll()); registry.anyRequest() .access("@permissionService.hasPermission(request,authentication)"); } diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/PreviewFilter.java b/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/PreviewFilter.java index 058e6cb5..08d391dd 100644 --- a/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/PreviewFilter.java +++ b/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/PreviewFilter.java @@ -15,8 +15,10 @@ import com.xiaoleilu.hutool.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; +import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; @@ -32,12 +34,11 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst * 演示环境控制 */ @Slf4j -@Component @RefreshScope +@Configuration +@ConditionalOnProperty(value = "security.validate.preview", havingValue = "true") public class PreviewFilter extends ZuulFilter { private static final String TOKEN = "token"; - @Value("${security.validate.preview:true}") - private boolean isPreview; @Override public String filterType() { @@ -53,15 +54,14 @@ public class PreviewFilter extends ZuulFilter { public boolean shouldFilter() { HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); if (StrUtil.equalsIgnoreCase(request.getMethod(), HttpMethod.GET.name()) || - StrUtil.containsIgnoreCase(request.getRequestURI(), TOKEN)) { - return false; + StrUtil.containsIgnoreCase(request.getRequestURI(), TOKEN)){ + return false; } - return isPreview; + return true; } @Override public Object run() { - log.warn("演示环境,没有权限操作 -> {}", isPreview); RequestContext ctx = RequestContext.getCurrentContext(); R result = new R<>(); result.setCode(479); diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java b/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java index bcb46d40..459eeb73 100644 --- a/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java +++ b/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java @@ -1,43 +1,44 @@ package com.github.pig.gateway.component.filter; import com.alibaba.fastjson.JSONObject; -import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.pig.common.bean.config.FilterIgnorePropertiesConfig; import com.github.pig.common.constant.SecurityConstants; +import com.github.pig.common.util.AuthUtils; import com.github.pig.common.util.R; import com.github.pig.common.util.exception.ValidateCodeException; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; +import com.xiaoleilu.hutool.collection.CollUtil; import com.xiaoleilu.hutool.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.Arrays; /** * @author lengleng * @date 2018/5/10 - * + *

* security.validate.code.enabled 默认 为false,开启需要设置为true - * - * 验证码校验,true开启,false关闭校验 - * 更细化可以 clientId 进行区分 */ @Slf4j @RefreshScope @Configuration("validateCodeFilter") -@ConditionalOnProperty(value = "security.validate.code.enabled", havingValue = "true") +@ConditionalOnProperty(value = "security.validate.code", havingValue = "true") public class ValidateCodeFilter extends ZuulFilter { private static final String EXPIRED_CAPTCHA_ERROR = "验证码已过期,请重新获取"; @Autowired private RedisTemplate redisTemplate; + @Autowired + private FilterIgnorePropertiesConfig filterIgnorePropertiesConfig; @Override public String filterType() { @@ -49,14 +50,33 @@ public class ValidateCodeFilter extends ZuulFilter { return FilterConstants.SEND_ERROR_FILTER_ORDER + 1; } + /** + * 是否校验验证码 + * 1. 判断验证码开关是否开启 + * 2. 判断请求是否登录请求 + * 3. 判断终端是否支持 + * + * @return true/false + */ @Override public boolean shouldFilter() { HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); - if (StrUtil.containsIgnoreCase(request.getRequestURI(), SecurityConstants.OAUTH_TOKEN_URL) - || StrUtil.containsIgnoreCase(request.getRequestURI(), SecurityConstants.MOBILE_TOKEN_URL)) { - return true; + + if (!StrUtil.containsAnyIgnoreCase(request.getRequestURI(), + SecurityConstants.OAUTH_TOKEN_URL, SecurityConstants.MOBILE_TOKEN_URL)) { + return false; } - return false; + + try { + String[] clientInfos = AuthUtils.extractAndDecodeHeader(request); + if (CollUtil.containsAny(filterIgnorePropertiesConfig.getClients(), Arrays.asList(clientInfos))) { + return false; + } + } catch (IOException e) { + log.error("解析终端信息失败", e); + } + + return true; } @Override @@ -67,7 +87,6 @@ public class ValidateCodeFilter extends ZuulFilter { RequestContext ctx = RequestContext.getCurrentContext(); R result = new R<>(e); result.setCode(478); - result.setMsg("演示环境,没有权限操作"); ctx.setResponseStatusCode(478); ctx.setSendZuulResponse(false); diff --git a/pig-modules/pig-mc-service/pom.xml b/pig-modules/pig-mc-service/pom.xml index b892335a..8aa9b55c 100644 --- a/pig-modules/pig-mc-service/pom.xml +++ b/pig-modules/pig-mc-service/pom.xml @@ -23,11 +23,6 @@ pig-common ${pig.version} - - - org.springframework.boot - spring-boot-starter-amqp - com.aliyun diff --git a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/handler/SmsAliyunMessageHandler.java b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/handler/SmsAliyunMessageHandler.java index 16bab146..90a085d7 100644 --- a/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/handler/SmsAliyunMessageHandler.java +++ b/pig-modules/pig-mc-service/src/main/java/com/github/pig/mc/handler/SmsAliyunMessageHandler.java @@ -25,8 +25,8 @@ import org.springframework.stereotype.Component; public class SmsAliyunMessageHandler extends AbstractMessageHandler { @Autowired private SmsAliyunPropertiesConfig smsAliyunPropertiesConfig; - private static final String product = "Dysmsapi"; - private static final String domain = "dysmsapi.aliyuncs.com"; + private static final String PRODUCT = "Dysmsapi"; + private static final String DOMAIN = "dysmsapi.aliyuncs.com"; /** * 数据校验 @@ -53,7 +53,7 @@ public class SmsAliyunMessageHandler extends AbstractMessageHandler { //初始化acsClient,暂不支持region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsAliyunPropertiesConfig.getAccessKey(), smsAliyunPropertiesConfig.getSecretKey()); try { - DefaultProfile.addEndpoint("cn-hou", "cn-hangzhou", product, domain); + DefaultProfile.addEndpoint("cn-hou", "cn-hangzhou", PRODUCT, DOMAIN); } catch (ClientException e) { log.error("初始化SDK 异常", e); e.printStackTrace(); diff --git a/pig-modules/pig-upms-service/pom.xml b/pig-modules/pig-upms-service/pom.xml index e8837e99..2eb97fca 100644 --- a/pig-modules/pig-upms-service/pom.xml +++ b/pig-modules/pig-upms-service/pom.xml @@ -57,11 +57,6 @@ ${velocity-engine-core.version} - - - org.springframework.boot - spring-boot-starter-amqp - com.qiniu diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/entity/SysUser.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/entity/SysUser.java index bd868b99..20d438a2 100644 --- a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/entity/SysUser.java +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/entity/SysUser.java @@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.enums.IdType; +import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import java.io.Serializable; @@ -34,10 +35,12 @@ public class SysUser extends Model { */ private String username; + @JsonIgnore private String password; /** * 随机盐 */ + @JsonIgnore private String salt; /** * 创建时间 diff --git a/pig-visual/pig-monitor/pom.xml b/pig-visual/pig-monitor/pom.xml index 5cb577ae..cf939bc5 100644 --- a/pig-visual/pig-monitor/pom.xml +++ b/pig-visual/pig-monitor/pom.xml @@ -34,10 +34,6 @@ spring-boot-admin-server-ui ${spring-boot-admin-server-ui.version} - - org.springframework.boot - spring-boot-starter-amqp - org.springframework.cloud spring-cloud-starter-turbine diff --git a/pig-visual/pig-monitor/src/main/java/com/github/pig/monitor/filter/StatusChangeNotifier.java b/pig-visual/pig-monitor/src/main/java/com/github/pig/monitor/filter/StatusChangeNotifier.java index 18b9b484..7aa4f842 100644 --- a/pig-visual/pig-monitor/src/main/java/com/github/pig/monitor/filter/StatusChangeNotifier.java +++ b/pig-visual/pig-monitor/src/main/java/com/github/pig/monitor/filter/StatusChangeNotifier.java @@ -6,7 +6,7 @@ import com.github.pig.common.constant.enums.EnumSmsChannel; import com.github.pig.common.constant.enums.EnumSmsChannelTemplate; import com.github.pig.common.util.template.MobileMsgTemplate; import com.github.pig.monitor.config.MonitorPropertiesConfig; -import com.xiaoleilu.hutool.collection.CollectionUtil; +import com.xiaoleilu.hutool.collection.CollUtil; import com.xiaoleilu.hutool.date.DateUtil; import de.codecentric.boot.admin.event.ClientApplicationEvent; import de.codecentric.boot.admin.event.ClientApplicationStatusChangedEvent; @@ -14,6 +14,8 @@ import de.codecentric.boot.admin.notify.AbstractStatusChangeNotifier; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.core.RabbitTemplate; +import java.nio.file.Paths; + /** * @author lengleng * @date 2018/4/22 @@ -70,7 +72,7 @@ public class StatusChangeNotifier extends AbstractStatusChangeNotifier { log.info("开始短信通知,内容:{}", text); rabbitTemplate.convertAndSend(MqQueueConstant.MOBILE_SERVICE_STATUS_CHANGE, new MobileMsgTemplate( - CollectionUtil.join(monitorMobilePropertiesConfig.getMobile().getMobiles(), ","), + CollUtil.join(monitorMobilePropertiesConfig.getMobile().getMobiles(), ","), contextJson.toJSONString(), EnumSmsChannel.ALIYUN.getName(), EnumSmsChannelTemplate.SERVICE_STATUS_CHANGE.getSignName(), From ae26f4150881d9b1e2dc5cdc7ced353704aa3839 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=AF=BB=E6=AC=A2?= Date: Mon, 14 May 2018 21:47:26 +0800 Subject: [PATCH 06/18] =?UTF-8?q?=E6=B8=85=E6=A5=9A=E6=97=A0=E7=94=A8?= =?UTF-8?q?=E5=BC=95=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pig/gateway/component/filter/ValidateCodeFilter.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java b/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java index bcb46d40..fb66c2dc 100644 --- a/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java +++ b/pig-gateway/src/main/java/com/github/pig/gateway/component/filter/ValidateCodeFilter.java @@ -1,7 +1,6 @@ package com.github.pig.gateway.component.filter; import com.alibaba.fastjson.JSONObject; -import com.fasterxml.jackson.databind.ObjectMapper; import com.github.pig.common.constant.SecurityConstants; import com.github.pig.common.util.R; import com.github.pig.common.util.exception.ValidateCodeException; @@ -10,13 +9,11 @@ import com.netflix.zuul.context.RequestContext; import com.xiaoleilu.hutool.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; From ca084859fa1ef27459e45629bbff0c2387335070 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=86=B7=E5=86=B7?= Date: Wed, 16 May 2018 20:47:07 +0800 Subject: [PATCH 07/18] =?UTF-8?q?feat:=20=E5=8A=A8=E6=80=81=E8=B7=AF?= =?UTF-8?q?=E7=94=B1=E3=80=81=E5=AE=A2=E6=88=B7=E7=AB=AF=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pig/auth/config/AuthServerConfig.java | 26 --- .../config/FilterIgnorePropertiesConfig.java | 2 + .../pig/common/entity/SysZuulRoute.java | 85 ++++++++++ .../com/github/pig/common/vo/ZuulRouteVO.java | 55 +++++++ .../gateway/DynamicRouteConfiguration.java | 43 +++++ .../pig/gateway/PigGatewayApplication.java | 8 + .../component/config/DynamicRouteLocator.java | 114 +++++++++++++ .../config/ResourceServerConfiguration.java | 9 +- .../github/pig/gateway/feign/UserService.java | 23 --- .../pig/gateway/feign/ZuulRouteService.java | 26 +++ .../fallback/MenuServiceFallbackImpl.java | 8 +- .../fallback/UserServiceFallbackImpl.java | 23 --- .../ZuulRouteServiceFallbackImpl.java | 35 ++++ .../common/util/PigResourcesGenerator.java | 4 +- .../OauthClientDetailsController.java | 86 ++++++++++ .../admin/controller/ZuulRouteController.java | 102 ++++++++++++ .../mapper/SysOauthClientDetailsMapper.java | 17 ++ .../pig/admin/mapper/SysZuulRouteMapper.java | 16 ++ .../github/pig/admin/model/dto/MenuTree.java | 2 + .../model/entity/SysOauthClientDetails.java | 154 ++++++++++++++++++ .../pig/admin/service/SysMenuService.java | 2 - .../service/SysOauthClientDetailsService.java | 16 ++ .../admin/service/SysZuulRouteService.java | 16 ++ .../service/impl/SysMenuServiceImpl.java | 9 +- .../SysOauthClientDetailsServiceImpl.java | 20 +++ .../service/impl/SysZuulRouteServiceImpl.java | 20 +++ .../mapper/SysOauthClientDetailsMapper.xml | 25 +++ .../resources/mapper/SysZuulRouteMapper.xml | 25 +++ .../resources/templates/controller.java.vm | 17 +- 29 files changed, 895 insertions(+), 93 deletions(-) delete mode 100644 pig-auth/src/main/java/com/github/pig/auth/config/AuthServerConfig.java create mode 100644 pig-common/src/main/java/com/github/pig/common/entity/SysZuulRoute.java create mode 100644 pig-common/src/main/java/com/github/pig/common/vo/ZuulRouteVO.java create mode 100644 pig-gateway/src/main/java/com/github/pig/gateway/DynamicRouteConfiguration.java create mode 100644 pig-gateway/src/main/java/com/github/pig/gateway/component/config/DynamicRouteLocator.java delete mode 100644 pig-gateway/src/main/java/com/github/pig/gateway/feign/UserService.java create mode 100644 pig-gateway/src/main/java/com/github/pig/gateway/feign/ZuulRouteService.java delete mode 100644 pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/UserServiceFallbackImpl.java create mode 100644 pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/ZuulRouteServiceFallbackImpl.java create mode 100644 pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/OauthClientDetailsController.java create mode 100644 pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/ZuulRouteController.java create mode 100644 pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/mapper/SysOauthClientDetailsMapper.java create mode 100644 pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/mapper/SysZuulRouteMapper.java create mode 100644 pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/entity/SysOauthClientDetails.java create mode 100644 pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysOauthClientDetailsService.java create mode 100644 pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysZuulRouteService.java create mode 100644 pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysOauthClientDetailsServiceImpl.java create mode 100644 pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysZuulRouteServiceImpl.java create mode 100644 pig-modules/pig-upms-service/src/main/resources/mapper/SysOauthClientDetailsMapper.xml create mode 100644 pig-modules/pig-upms-service/src/main/resources/mapper/SysZuulRouteMapper.xml diff --git a/pig-auth/src/main/java/com/github/pig/auth/config/AuthServerConfig.java b/pig-auth/src/main/java/com/github/pig/auth/config/AuthServerConfig.java deleted file mode 100644 index b6a80626..00000000 --- a/pig-auth/src/main/java/com/github/pig/auth/config/AuthServerConfig.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.github.pig.auth.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author lengleng - * @date 2017/10/28 - */ -@Data -@Configuration -@ConfigurationProperties(prefix = "auth") -public class AuthServerConfig { - private List clients = new ArrayList<>(); - - @Data - class AuthServer { - private String clientId; - private String clientSecret; - private String scope; - } -} diff --git a/pig-common/src/main/java/com/github/pig/common/bean/config/FilterIgnorePropertiesConfig.java b/pig-common/src/main/java/com/github/pig/common/bean/config/FilterIgnorePropertiesConfig.java index 1f50740d..550fdc96 100644 --- a/pig-common/src/main/java/com/github/pig/common/bean/config/FilterIgnorePropertiesConfig.java +++ b/pig-common/src/main/java/com/github/pig/common/bean/config/FilterIgnorePropertiesConfig.java @@ -3,6 +3,7 @@ package com.github.pig.common.bean.config; import lombok.Data; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; @@ -14,6 +15,7 @@ import java.util.List; */ @Data @Configuration +@RefreshScope @ConditionalOnExpression("!'${ignore}'.isEmpty()") @ConfigurationProperties(prefix = "ignore") public class FilterIgnorePropertiesConfig { diff --git a/pig-common/src/main/java/com/github/pig/common/entity/SysZuulRoute.java b/pig-common/src/main/java/com/github/pig/common/entity/SysZuulRoute.java new file mode 100644 index 00000000..7b72c0d9 --- /dev/null +++ b/pig-common/src/main/java/com/github/pig/common/entity/SysZuulRoute.java @@ -0,0 +1,85 @@ +package com.github.pig.common.entity; + +import com.baomidou.mybatisplus.enums.IdType; +import java.util.Date; +import com.baomidou.mybatisplus.annotations.TableId; +import com.baomidou.mybatisplus.annotations.TableField; +import com.baomidou.mybatisplus.activerecord.Model; +import com.baomidou.mybatisplus.annotations.TableName; +import lombok.Data; + +import java.io.Serializable; + +/** + *

+ * 动态路由配置表 + *

+ * + * @author lengleng + * @since 2018-05-15 + */ +@Data +@TableName("sys_zuul_route") +public class SysZuulRoute extends Model { + + private static final long serialVersionUID = 1L; + + /** + * router Id + */ + @TableId(value = "id", type = IdType.AUTO) + private Integer id; + /** + * 路由路径 + */ + private String path; + /** + * 服务名称 + */ + @TableField("service_id") + private String serviceId; + /** + * url代理 + */ + private String url; + /** + * 转发去掉前缀 + */ + @TableField("strip_prefix") + private String stripPrefix; + /** + * 是否重试 + */ + private String retryable; + /** + * 是否启用 + */ + private String enabled; + /** + * 敏感请求头 + */ + @TableField("sensitiveHeaders_list") + private String sensitiveheadersList; + /** + * 创建时间 + */ + @TableField("create_time") + private Date createTime; + /** + * 更新时间 + */ + @TableField("update_time") + private Date updateTime; + /** + * 删除标识(0-正常,1-删除) + */ + @TableField("del_flag") + private String delFlag; + + @Override + protected Serializable pkVal() { + return this.id; + } + + +} diff --git a/pig-common/src/main/java/com/github/pig/common/vo/ZuulRouteVO.java b/pig-common/src/main/java/com/github/pig/common/vo/ZuulRouteVO.java new file mode 100644 index 00000000..92d7a240 --- /dev/null +++ b/pig-common/src/main/java/com/github/pig/common/vo/ZuulRouteVO.java @@ -0,0 +1,55 @@ +package com.github.pig.common.vo; + +import lombok.Data; + +/** + * @author lengleng + * @date 2018/5/15 + * 自定义路由实体 + */ +@Data +public class ZuulRouteVO { + /** + * router ID + */ + private String id; + + /** + * The path (pattern) for the route, e.g. /foo/**. + */ + private String path; + + /** + * The service ID (if any) to map to this route. You can specify a physical URL or + * a service, but not both. + */ + private String serviceId; + + /** + * A full physical URL to map to the route. An alternative is to use a service ID + * and service discovery to find the physical address. + */ + private String url; + + /** + * Flag to determine whether the prefix for this route (the path, minus pattern + * patcher) should be stripped before forwarding. + */ + private boolean stripPrefix = true; + + /** + * Flag to indicate that this route should be retryable (if supported). Generally + * retry requires a service ID and ribbon. + */ + private Boolean retryable; + + /** + * 是否开启 + */ + private Boolean enabled; + + /** + * 微服务敏感的header + */ + private String sensitiveHeadersList; +} diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/DynamicRouteConfiguration.java b/pig-gateway/src/main/java/com/github/pig/gateway/DynamicRouteConfiguration.java new file mode 100644 index 00000000..8346d76b --- /dev/null +++ b/pig-gateway/src/main/java/com/github/pig/gateway/DynamicRouteConfiguration.java @@ -0,0 +1,43 @@ +package com.github.pig.gateway; + +import com.github.pig.gateway.component.config.DynamicRouteLocator; +import com.github.pig.gateway.feign.ZuulRouteService; +import org.springframework.boot.autoconfigure.web.ServerProperties; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.client.serviceregistry.Registration; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; +import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +/** + * @author lengleng + * @date 2018/5/15 + * 动态路由配置类 + */ +@Configuration +public class DynamicRouteConfiguration { + private Registration registration; + private DiscoveryClient discovery; + private ZuulProperties zuulProperties; + private ServerProperties server; + private ZuulRouteService zuulRouteService; + + public DynamicRouteConfiguration(ZuulRouteService zuulRouteService, Registration registration, DiscoveryClient discovery, ZuulProperties zuulProperties, ServerProperties server) { + this.registration = registration; + this.discovery = discovery; + this.zuulProperties = zuulProperties; + this.server = server; + this.zuulRouteService = zuulRouteService; + } + + @Bean + public DynamicRouteLocator dynamicRouteLocator() { + return new DynamicRouteLocator(server.getServletPrefix() + , discovery + , zuulProperties + , registration + , zuulRouteService); + } +} diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/PigGatewayApplication.java b/pig-gateway/src/main/java/com/github/pig/gateway/PigGatewayApplication.java index 01db8605..6b005ffc 100644 --- a/pig-gateway/src/main/java/com/github/pig/gateway/PigGatewayApplication.java +++ b/pig-gateway/src/main/java/com/github/pig/gateway/PigGatewayApplication.java @@ -1,7 +1,9 @@ package com.github.pig.gateway; import org.springframework.boot.SpringApplication; +import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.cloud.client.SpringCloudApplication; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor; import org.springframework.cloud.netflix.feign.EnableFeignClients; @@ -9,6 +11,7 @@ import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.web.client.RestTemplate; /** * @author lengleng @@ -42,4 +45,9 @@ public class PigGatewayApplication { LoadBalancerInterceptor loadBalancerInterceptor(LoadBalancerClient loadBalance){ return new LoadBalancerInterceptor(loadBalance); } + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } } diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/component/config/DynamicRouteLocator.java b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/DynamicRouteLocator.java new file mode 100644 index 00000000..3501fa6a --- /dev/null +++ b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/DynamicRouteLocator.java @@ -0,0 +1,114 @@ +package com.github.pig.gateway.component.config; + +import com.github.pig.common.constant.ServiceNameConstant; +import com.github.pig.common.entity.SysZuulRoute; +import com.github.pig.gateway.feign.ZuulRouteService; +import com.xiaoleilu.hutool.collection.CollUtil; +import com.xiaoleilu.hutool.util.ArrayUtil; +import com.xiaoleilu.hutool.util.StrUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; +import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; +import org.springframework.web.client.RestTemplate; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author lengleng + * @date 2018/5/15 + * 动态路由实现 + */ +@Slf4j +public class DynamicRouteLocator extends DiscoveryClientRouteLocator { + private ZuulProperties properties; + private RestTemplate restTemplate; + private ZuulRouteService zuulRouteService; + + public DynamicRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties, ServiceInstance localServiceInstance, ZuulRouteService zuulRouteService) { + super(servletPath, discovery, properties, localServiceInstance); + this.properties = properties; + this.zuulRouteService = zuulRouteService; + } + + /** + * 重写路由配置 + *

+ * 1. properties 配置。 + * 2. eureka 默认配置。 + * 3. DB数据库配置。 + * + * @return 路由表 + */ + @Override + protected LinkedHashMap locateRoutes() { + LinkedHashMap routesMap = new LinkedHashMap<>(); + //读取properties配置、eureka默认配置 + routesMap.putAll(super.locateRoutes()); + log.info("初始默认的路由配置完成"); + routesMap.putAll(locateRoutesFromDb()); + LinkedHashMap values = new LinkedHashMap<>(); + for (Map.Entry entry : routesMap.entrySet()) { + String path = entry.getKey(); + if (!path.startsWith("/")) { + path = "/" + path; + } + if (StrUtil.isNotBlank(this.properties.getPrefix())) { + path = this.properties.getPrefix() + path; + if (!path.startsWith("/")) { + path = "/" + path; + } + } + values.put(path, entry.getValue()); + } + return routesMap; + } + + /** + * 拉去路由配置先采用RestTemplate 加载eureka中信息来是实现 + * + * @return + */ + private Map locateRoutesFromDb() { + Map routes = new LinkedHashMap<>(); + + String url = String.format("http://localhost:4000/route/findAllZuulRoute", ServiceNameConstant.UMPS_SERVICE); + SysZuulRoute[] response = restTemplate.getForObject(url, SysZuulRoute[].class); + if (ArrayUtil.isEmpty(response)) { + return routes; + } + + for (SysZuulRoute result : response) { + if (StrUtil.isBlank(result.getPath()) || StrUtil.isBlank(result.getUrl())) { + continue; + } + + ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute(); + try { + zuulRoute.setId(String.valueOf(result.getId())); + zuulRoute.setPath(result.getPath()); + zuulRoute.setServiceId(result.getServiceId()); + zuulRoute.setRetryable(StrUtil.equals(result.getRetryable(), "0") ? Boolean.FALSE : Boolean.TRUE); + zuulRoute.setStripPrefix(StrUtil.equals(result.getStripPrefix(), "0") ? Boolean.FALSE : Boolean.TRUE); + zuulRoute.setUrl(result.getUrl()); + List sensitiveHeadersList = StrUtil.splitTrim(result.getSensitiveheadersList(), ","); + if (CollUtil.isNotEmpty(sensitiveHeadersList)) { + Set sensitiveHeaderSet = CollUtil.newHashSet(); + sensitiveHeadersList.forEach(sensitiveHeader -> sensitiveHeaderSet.add(sensitiveHeader)); + zuulRoute.setSensitiveHeaders(sensitiveHeaderSet); + zuulRoute.setCustomSensitiveHeaders(true); + } + } catch (Exception e) { + log.error("从数据库加载路由配置异常", e); + } + log.info("添加数据库自定义的路由配置,path:{},serviceId:{}", zuulRoute.getPath(), zuulRoute.getServiceId()); + routes.put(zuulRoute.getPath(), zuulRoute); + } + return routes; + } +} diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java index 185e83c5..0a8bd226 100644 --- a/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java +++ b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java @@ -1,12 +1,18 @@ package com.github.pig.gateway.component.config; import com.github.pig.common.bean.config.FilterIgnorePropertiesConfig; -import com.github.pig.gateway.component.filter.ValidateCodeFilter; import com.github.pig.gateway.component.handler.PigAccessDeniedHandler; +import com.github.pig.gateway.feign.ZuulRouteService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.web.ServerProperties; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.client.serviceregistry.Registration; +import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; +import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @@ -15,6 +21,7 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.E import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler; + /** * @author lengleng * @date 2017/10/27 diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/feign/UserService.java b/pig-gateway/src/main/java/com/github/pig/gateway/feign/UserService.java deleted file mode 100644 index 3af86af7..00000000 --- a/pig-gateway/src/main/java/com/github/pig/gateway/feign/UserService.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.github.pig.gateway.feign; - -import com.github.pig.common.vo.UserVO; -import com.github.pig.gateway.feign.fallback.UserServiceFallbackImpl; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; - -/** - * @author lengleng - * @date 2017/10/31 - */ -@FeignClient(name = "pig-upms-service", fallback = UserServiceFallbackImpl.class) -public interface UserService { - /** - * 通过用户名查询用户、角色信息 - * - * @param username 用户名 - * @return UserVo - */ - @GetMapping("/user/findUserByUsername/{username}") - UserVO findUserByUsername(@PathVariable("username") String username); -} diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/feign/ZuulRouteService.java b/pig-gateway/src/main/java/com/github/pig/gateway/feign/ZuulRouteService.java new file mode 100644 index 00000000..e6b6397c --- /dev/null +++ b/pig-gateway/src/main/java/com/github/pig/gateway/feign/ZuulRouteService.java @@ -0,0 +1,26 @@ +package com.github.pig.gateway.feign; + +import com.github.pig.common.entity.SysZuulRoute; +import com.github.pig.gateway.feign.fallback.MenuServiceFallbackImpl; +import com.github.pig.gateway.feign.fallback.ZuulRouteServiceFallbackImpl; +import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.GetMapping; + +import java.util.List; + +/** + * @author lengleng + * @date 2018/5/15 + * 远程获取zuul配置 + */ +@FeignClient(name = "pig-upms-service", fallback = ZuulRouteServiceFallbackImpl.class) +public interface ZuulRouteService { + /** + * 调用upms查询全部的路由配置 + * + * @return 路由配置表 + */ + @GetMapping(value = "/route/findAllZuulRoute") + List findAllZuulRoute(); +} diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/MenuServiceFallbackImpl.java b/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/MenuServiceFallbackImpl.java index 7652dab5..2318e7f3 100644 --- a/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/MenuServiceFallbackImpl.java +++ b/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/MenuServiceFallbackImpl.java @@ -2,6 +2,8 @@ package com.github.pig.gateway.feign.fallback; import com.github.pig.common.vo.MenuVO; import com.github.pig.gateway.feign.MenuService; +import com.xiaoleilu.hutool.collection.CollUtil; +import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @@ -14,12 +16,12 @@ import java.util.Set; * why add @Service when i up version ? * https://github.com/spring-cloud/spring-cloud-netflix/issues/762 */ +@Slf4j @Service public class MenuServiceFallbackImpl implements MenuService { - private Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public Set findMenuByRole(String role) { - logger.error("调用{}异常{}","findMenuByRole",role); - return null; + log.error("调用{}异常{}","findMenuByRole",role); + return CollUtil.newHashSet(); } } diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/UserServiceFallbackImpl.java b/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/UserServiceFallbackImpl.java deleted file mode 100644 index b3976878..00000000 --- a/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/UserServiceFallbackImpl.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.github.pig.gateway.feign.fallback; - -import com.github.pig.common.vo.UserVO; -import com.github.pig.gateway.feign.UserService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -/** - * @author lengleng - * @date 2017/10/31 - * 用户服务的fallback - */ -@Service -public class UserServiceFallbackImpl implements UserService { - private Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Override - public UserVO findUserByUsername(String username) { - logger.error("调用{}异常:{}", "findUserByUsername", username); - return null; - } -} diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/ZuulRouteServiceFallbackImpl.java b/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/ZuulRouteServiceFallbackImpl.java new file mode 100644 index 00000000..e193865e --- /dev/null +++ b/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/ZuulRouteServiceFallbackImpl.java @@ -0,0 +1,35 @@ +package com.github.pig.gateway.feign.fallback; + +import com.github.pig.common.entity.SysZuulRoute; +import com.github.pig.common.vo.MenuVO; +import com.github.pig.gateway.feign.MenuService; +import com.github.pig.gateway.feign.ZuulRouteService; +import com.xiaoleilu.hutool.collection.CollUtil; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Set; + +/** + * @author lengleng + * @date 2018/5/15 + * 远程调用路由接口异常回调 + */ +@Slf4j +@Service +public class ZuulRouteServiceFallbackImpl implements ZuulRouteService { + + /** + * 调用upms查询全部的路由配置 + * + * @return 路由配置表 + */ + @Override + public List findAllZuulRoute() { + log.error("获取远程路由配置失败"); + return CollUtil.newArrayList(); + } +} diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/util/PigResourcesGenerator.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/util/PigResourcesGenerator.java index 12934c32..f686581a 100644 --- a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/util/PigResourcesGenerator.java +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/util/PigResourcesGenerator.java @@ -25,7 +25,7 @@ public class PigResourcesGenerator { public static void main(String[] args) { - String outputDir = "/Users/lengleng/work/source"; + String outputDir = "/Users/lengleng/work/temp"; final String viewOutputDir = outputDir + "/view/"; AutoGenerator mpg = new AutoGenerator(); // 全局配置 @@ -48,7 +48,7 @@ public class PigResourcesGenerator { dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("lengleng"); - dsc.setUrl("jdbc:mysql://106.14.69.75:3309/pig?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false"); + dsc.setUrl("jdbc:mysql://139.224.200.249:3309/pig?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false"); mpg.setDataSource(dsc); // 策略配置 diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/OauthClientDetailsController.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/OauthClientDetailsController.java new file mode 100644 index 00000000..2d30859c --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/OauthClientDetailsController.java @@ -0,0 +1,86 @@ +package com.github.pig.admin.controller; + +import java.util.Map; + +import com.github.pig.admin.model.entity.SysOauthClientDetails; +import com.github.pig.common.util.R; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import com.baomidou.mybatisplus.mapper.EntityWrapper; +import com.baomidou.mybatisplus.plugins.Page; +import com.github.pig.common.util.Query; +import com.github.pig.admin.service.SysOauthClientDetailsService; +import com.github.pig.common.web.BaseController; + +/** + *

+ * 前端控制器 + *

+ * + * @author lengleng + * @since 2018-05-15 + */ +@RestController +@RequestMapping("/client") +public class OauthClientDetailsController extends BaseController { + @Autowired + private SysOauthClientDetailsService sysOauthClientDetailsService; + + /** + * 通过ID查询 + * + * @param id ID + * @return SysOauthClientDetails + */ + @GetMapping("/{id}") + public SysOauthClientDetails get(@PathVariable Integer id) { + return sysOauthClientDetailsService.selectById(id); + } + + + /** + * 分页查询信息 + * + * @param params 分页对象 + * @return 分页对象 + */ + @RequestMapping("/page") + public Page page(@RequestParam Map params) { + return sysOauthClientDetailsService.selectPage(new Query<>(params), new EntityWrapper<>()); + } + + /** + * 添加 + * + * @param sysOauthClientDetails 实体 + * @return success/false + */ + @PostMapping + public R add(@RequestBody SysOauthClientDetails sysOauthClientDetails) { + return new R<>(sysOauthClientDetailsService.insert(sysOauthClientDetails)); + } + + /** + * 删除 + * + * @param id ID + * @return success/false + */ + @DeleteMapping("/{id}") + public R delete(@PathVariable String id) { + SysOauthClientDetails sysOauthClientDetails = new SysOauthClientDetails(); + sysOauthClientDetails.setClientId(id); + return new R<>(sysOauthClientDetailsService.deleteById(sysOauthClientDetails)); + } + + /** + * 编辑 + * + * @param sysOauthClientDetails 实体 + * @return success/false + */ + @PutMapping + public R edit(@RequestBody SysOauthClientDetails sysOauthClientDetails) { + return new R<>(sysOauthClientDetailsService.updateById(sysOauthClientDetails)); + } +} diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/ZuulRouteController.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/ZuulRouteController.java new file mode 100644 index 00000000..b48ecdd5 --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/ZuulRouteController.java @@ -0,0 +1,102 @@ +package com.github.pig.admin.controller; + +import java.util.List; +import java.util.Map; +import java.util.Date; + +import com.github.pig.common.entity.SysZuulRoute; +import com.github.pig.common.util.R; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import com.github.pig.common.constant.CommonConstant; +import com.baomidou.mybatisplus.mapper.EntityWrapper; +import com.baomidou.mybatisplus.plugins.Page; +import com.github.pig.common.util.Query; +import com.github.pig.admin.service.SysZuulRouteService; +import com.github.pig.common.web.BaseController; + +/** + *

+ * 动态路由配置表 前端控制器 + *

+ * + * @author lengleng + * @since 2018-05-15 + */ +@RestController +@RequestMapping("/route") +public class ZuulRouteController extends BaseController { + @Autowired + private SysZuulRouteService sysZuulRouteService; + + /** + * 通过ID查询 + * + * @param id ID + * @return SysZuulRoute + */ + @GetMapping("/{id}") + public SysZuulRoute get(@PathVariable Integer id) { + return sysZuulRouteService.selectById(id); + } + + /** + * 查询全部路由配置 + * + * @return 路由配置表 + */ + @GetMapping("/findAllZuulRoute") + public List findAllZuulRoute() { + return sysZuulRouteService.selectList(new EntityWrapper<>()); + } + + /** + * 分页查询信息 + * + * @param params 分页对象 + * @return 分页对象 + */ + @RequestMapping("/page") + public Page page(@RequestParam Map params) { + params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL); + return sysZuulRouteService.selectPage(new Query<>(params), new EntityWrapper<>()); + } + + /** + * 添加 + * + * @param sysZuulRoute 实体 + * @return success/false + */ + @PostMapping + public R add(@RequestBody SysZuulRoute sysZuulRoute) { + return new R<>(sysZuulRouteService.insert(sysZuulRoute)); + } + + /** + * 删除 + * + * @param id ID + * @return success/false + */ + @DeleteMapping("/{id}") + public R delete(@PathVariable Integer id) { + SysZuulRoute sysZuulRoute = new SysZuulRoute(); + sysZuulRoute.setId(id); + sysZuulRoute.setUpdateTime(new Date()); + sysZuulRoute.setDelFlag(CommonConstant.STATUS_DEL); + return new R<>(sysZuulRouteService.updateById(sysZuulRoute)); + } + + /** + * 编辑 + * + * @param sysZuulRoute 实体 + * @return success/false + */ + @PutMapping + public R edit(@RequestBody SysZuulRoute sysZuulRoute) { + sysZuulRoute.setUpdateTime(new Date()); + return new R<>(sysZuulRouteService.updateById(sysZuulRoute)); + } +} diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/mapper/SysOauthClientDetailsMapper.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/mapper/SysOauthClientDetailsMapper.java new file mode 100644 index 00000000..59fed0df --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/mapper/SysOauthClientDetailsMapper.java @@ -0,0 +1,17 @@ +package com.github.pig.admin.mapper; + + +import com.baomidou.mybatisplus.mapper.BaseMapper; +import com.github.pig.admin.model.entity.SysOauthClientDetails; + +/** + *

+ * Mapper 接口 + *

+ * + * @author lengleng + * @since 2018-05-15 + */ +public interface SysOauthClientDetailsMapper extends BaseMapper { + +} diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/mapper/SysZuulRouteMapper.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/mapper/SysZuulRouteMapper.java new file mode 100644 index 00000000..4f8b8fa3 --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/mapper/SysZuulRouteMapper.java @@ -0,0 +1,16 @@ +package com.github.pig.admin.mapper; + +import com.baomidou.mybatisplus.mapper.BaseMapper; +import com.github.pig.common.entity.SysZuulRoute; + +/** + *

+ * 动态路由配置表 Mapper 接口 + *

+ * + * @author lengleng + * @since 2018-05-15 + */ +public interface SysZuulRouteMapper extends BaseMapper { + +} diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/dto/MenuTree.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/dto/MenuTree.java index 184302ed..9aa592c8 100644 --- a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/dto/MenuTree.java +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/dto/MenuTree.java @@ -20,6 +20,7 @@ public class MenuTree extends TreeNode { private String code; private String type; private String label; + private Integer sort; public MenuTree() { } @@ -48,5 +49,6 @@ public class MenuTree extends TreeNode { this.component = menuVo.getComponent(); this.type = menuVo.getType(); this.label = menuVo.getName(); + this.sort = menuVo.getSort(); } } diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/entity/SysOauthClientDetails.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/entity/SysOauthClientDetails.java new file mode 100644 index 00000000..04e30a65 --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/model/entity/SysOauthClientDetails.java @@ -0,0 +1,154 @@ +package com.github.pig.admin.model.entity; + +import com.baomidou.mybatisplus.annotations.TableId; +import com.baomidou.mybatisplus.annotations.TableField; +import com.baomidou.mybatisplus.activerecord.Model; +import com.baomidou.mybatisplus.annotations.TableName; +import com.baomidou.mybatisplus.enums.IdType; + +import java.io.Serializable; + +/** + *

+ * + *

+ * + * @author lengleng + * @since 2018-05-15 + */ +@TableName("sys_oauth_client_details") +public class SysOauthClientDetails extends Model { + + private static final long serialVersionUID = 1L; + + @TableId(value = "client_id", type = IdType.INPUT) + private String clientId; + @TableField("resource_ids") + private String resourceIds; + @TableField("client_secret") + private String clientSecret; + private String scope; + @TableField("authorized_grant_types") + private String authorizedGrantTypes; + @TableField("web_server_redirect_uri") + private String webServerRedirectUri; + private String authorities; + @TableField("access_token_validity") + private Integer accessTokenValidity; + @TableField("refresh_token_validity") + private Integer refreshTokenValidity; + @TableField("additional_information") + private String additionalInformation; + private String autoapprove; + + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getResourceIds() { + return resourceIds; + } + + public void setResourceIds(String resourceIds) { + this.resourceIds = resourceIds; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + public String getAuthorizedGrantTypes() { + return authorizedGrantTypes; + } + + public void setAuthorizedGrantTypes(String authorizedGrantTypes) { + this.authorizedGrantTypes = authorizedGrantTypes; + } + + public String getWebServerRedirectUri() { + return webServerRedirectUri; + } + + public void setWebServerRedirectUri(String webServerRedirectUri) { + this.webServerRedirectUri = webServerRedirectUri; + } + + public String getAuthorities() { + return authorities; + } + + public void setAuthorities(String authorities) { + this.authorities = authorities; + } + + public Integer getAccessTokenValidity() { + return accessTokenValidity; + } + + public void setAccessTokenValidity(Integer accessTokenValidity) { + this.accessTokenValidity = accessTokenValidity; + } + + public Integer getRefreshTokenValidity() { + return refreshTokenValidity; + } + + public void setRefreshTokenValidity(Integer refreshTokenValidity) { + this.refreshTokenValidity = refreshTokenValidity; + } + + public String getAdditionalInformation() { + return additionalInformation; + } + + public void setAdditionalInformation(String additionalInformation) { + this.additionalInformation = additionalInformation; + } + + public String getAutoapprove() { + return autoapprove; + } + + public void setAutoapprove(String autoapprove) { + this.autoapprove = autoapprove; + } + + @Override + protected Serializable pkVal() { + return this.clientId; + } + + @Override + public String toString() { + return "SysOauthClientDetails{" + + ", clientId=" + clientId + + ", resourceIds=" + resourceIds + + ", clientSecret=" + clientSecret + + ", scope=" + scope + + ", authorizedGrantTypes=" + authorizedGrantTypes + + ", webServerRedirectUri=" + webServerRedirectUri + + ", authorities=" + authorities + + ", accessTokenValidity=" + accessTokenValidity + + ", refreshTokenValidity=" + refreshTokenValidity + + ", additionalInformation=" + additionalInformation + + ", autoapprove=" + autoapprove + + "}"; + } +} diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysMenuService.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysMenuService.java index 348a11c8..dba5f6e8 100644 --- a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysMenuService.java +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysMenuService.java @@ -37,7 +37,6 @@ public interface SysMenuService extends IService { * 级联删除菜单 * * @param id 菜单ID - * @param roleList 角色 * @return 成功、失败 */ Boolean deleteMenu(Integer id); @@ -46,7 +45,6 @@ public interface SysMenuService extends IService { * 更新菜单信息 * * @param sysMenu 菜单信息 - * @param roleList 角色 * @return 成功、失败 */ Boolean updateMenuById(SysMenu sysMenu); diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysOauthClientDetailsService.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysOauthClientDetailsService.java new file mode 100644 index 00000000..fdc94774 --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysOauthClientDetailsService.java @@ -0,0 +1,16 @@ +package com.github.pig.admin.service; + +import com.baomidou.mybatisplus.service.IService; +import com.github.pig.admin.model.entity.SysOauthClientDetails; + +/** + *

+ * 服务类 + *

+ * + * @author lengleng + * @since 2018-05-15 + */ +public interface SysOauthClientDetailsService extends IService { + +} diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysZuulRouteService.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysZuulRouteService.java new file mode 100644 index 00000000..c35620ef --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysZuulRouteService.java @@ -0,0 +1,16 @@ +package com.github.pig.admin.service; + +import com.baomidou.mybatisplus.service.IService; +import com.github.pig.common.entity.SysZuulRoute; + +/** + *

+ * 动态路由配置表 服务类 + *

+ * + * @author lengleng + * @since 2018-05-15 + */ +public interface SysZuulRouteService extends IService { + +} diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysMenuServiceImpl.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysMenuServiceImpl.java index 9fb732a3..00c55979 100644 --- a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysMenuServiceImpl.java +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysMenuServiceImpl.java @@ -10,16 +10,14 @@ import com.github.pig.admin.service.SysMenuService; import com.github.pig.common.constant.CommonConstant; import com.github.pig.common.util.Assert; import com.github.pig.common.vo.MenuVO; +import com.xiaoleilu.hutool.collection.CollUtil; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; /** *

@@ -94,12 +92,13 @@ public class SysMenuServiceImpl extends ServiceImpl impl // 获取符合条件得菜单 Set all = new HashSet<>(); roleNames.forEach(roleName -> all.addAll(findMenuByRoleName(roleName))); - final List menuTreeList = new ArrayList<>(); + List menuTreeList = new ArrayList<>(); all.forEach(menuVo -> { if (CommonConstant.MENU.equals(menuVo.getType())) { menuTreeList.add(new MenuTree(menuVo)); } }); + CollUtil.sort(menuTreeList, Comparator.comparingInt(MenuTree::getSort)); return TreeUtil.bulid(menuTreeList, -1); } diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysOauthClientDetailsServiceImpl.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysOauthClientDetailsServiceImpl.java new file mode 100644 index 00000000..7964d5f5 --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysOauthClientDetailsServiceImpl.java @@ -0,0 +1,20 @@ +package com.github.pig.admin.service.impl; + +import com.github.pig.admin.mapper.SysOauthClientDetailsMapper; +import com.baomidou.mybatisplus.service.impl.ServiceImpl; +import com.github.pig.admin.model.entity.SysOauthClientDetails; +import com.github.pig.admin.service.SysOauthClientDetailsService; +import org.springframework.stereotype.Service; + +/** + *

+ * 服务实现类 + *

+ * + * @author lengleng + * @since 2018-05-15 + */ +@Service +public class SysOauthClientDetailsServiceImpl extends ServiceImpl implements SysOauthClientDetailsService { + +} diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysZuulRouteServiceImpl.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysZuulRouteServiceImpl.java new file mode 100644 index 00000000..e7332c98 --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysZuulRouteServiceImpl.java @@ -0,0 +1,20 @@ +package com.github.pig.admin.service.impl; + +import com.github.pig.admin.mapper.SysZuulRouteMapper; +import com.baomidou.mybatisplus.service.impl.ServiceImpl; +import com.github.pig.common.entity.SysZuulRoute; +import com.github.pig.admin.service.SysZuulRouteService; +import org.springframework.stereotype.Service; + +/** + *

+ * 动态路由配置表 服务实现类 + *

+ * + * @author lengleng + * @since 2018-05-15 + */ +@Service +public class SysZuulRouteServiceImpl extends ServiceImpl implements SysZuulRouteService { + +} diff --git a/pig-modules/pig-upms-service/src/main/resources/mapper/SysOauthClientDetailsMapper.xml b/pig-modules/pig-upms-service/src/main/resources/mapper/SysOauthClientDetailsMapper.xml new file mode 100644 index 00000000..cd8b3999 --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/resources/mapper/SysOauthClientDetailsMapper.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + client_id AS clientId, resource_ids AS resourceIds, client_secret AS clientSecret, scope, authorized_grant_types AS authorizedGrantTypes, web_server_redirect_uri AS webServerRedirectUri, authorities, access_token_validity AS accessTokenValidity, refresh_token_validity AS refreshTokenValidity, additional_information AS additionalInformation, autoapprove + + + diff --git a/pig-modules/pig-upms-service/src/main/resources/mapper/SysZuulRouteMapper.xml b/pig-modules/pig-upms-service/src/main/resources/mapper/SysZuulRouteMapper.xml new file mode 100644 index 00000000..16d4a207 --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/resources/mapper/SysZuulRouteMapper.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + id, path, service_id AS serviceId, url, strip_prefix AS stripPrefix, retryable, enabled, sensitiveHeaders_list AS sensitiveheadersList, create_time AS createTime, update_time AS updateTime, del_flag AS delFlag + + + diff --git a/pig-modules/pig-upms-service/src/main/resources/templates/controller.java.vm b/pig-modules/pig-upms-service/src/main/resources/templates/controller.java.vm index dce6f0a1..3d7af8ec 100644 --- a/pig-modules/pig-upms-service/src/main/resources/templates/controller.java.vm +++ b/pig-modules/pig-upms-service/src/main/resources/templates/controller.java.vm @@ -7,6 +7,7 @@ import com.github.pig.common.constant.CommonConstant; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.github.pig.common.util.Query; +import com.github.pig.common.util.R; import ${package.Entity}.${entity}; import ${package.Service}.${entity}Service; #if(${superControllerClassPackage}) @@ -33,8 +34,8 @@ public class ${table.controllerName} extends ${superControllerClass} { * @return ${entity} */ @GetMapping("/{id}") - public ${entity} get(@PathVariable Integer id) { - return ${table.entityPath}Service.selectById(id); + public R<${entity}> get(@PathVariable Integer id) { + return new R<>(${table.entityPath}Service.selectById(id)); } @@ -56,8 +57,8 @@ public class ${table.controllerName} extends ${superControllerClass} { * @return success/false */ @PostMapping - public Boolean add(@RequestBody ${entity} ${table.entityPath}) { - return ${table.entityPath}Service.insert(${table.entityPath}); + public R add(@RequestBody ${entity} ${table.entityPath}) { + return new R<>(${table.entityPath}Service.insert(${table.entityPath})); } /** @@ -66,12 +67,12 @@ public class ${table.controllerName} extends ${superControllerClass} { * @return success/false */ @DeleteMapping("/{id}") - public Boolean delete(@PathVariable Integer id) { + public R delete(@PathVariable Integer id) { ${entity} ${table.entityPath} = new ${entity}(); ${table.entityPath}.setId(id); ${table.entityPath}.setUpdateTime(new Date()); ${table.entityPath}.setDelFlag(CommonConstant.STATUS_DEL); - return ${table.entityPath}Service.updateById(${table.entityPath}); + return new R<>(${table.entityPath}Service.updateById(${table.entityPath})); } /** @@ -80,8 +81,8 @@ public class ${table.controllerName} extends ${superControllerClass} { * @return success/false */ @PutMapping - public Boolean edit(@RequestBody ${entity} ${table.entityPath}) { + public R edit(@RequestBody ${entity} ${table.entityPath}) { ${table.entityPath}.setUpdateTime(new Date()); - return ${table.entityPath}Service.updateById(${table.entityPath}); + return new R<>(${table.entityPath}Service.updateById(${table.entityPath})); } } From bf139a1591a9616fb6782c16941c307483e55531 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=86=B7=E5=86=B7?= Date: Mon, 21 May 2018 10:56:49 +0800 Subject: [PATCH 08/18] v1.0.0 --- .../pig/common/constant/CommonConstant.java | 5 ++ .../pig/common/constant/MqQueueConstant.java | 5 ++ .../com/github/pig/common/vo/ZuulRouteVO.java | 2 +- .../config}/DynamicRouteConfiguration.java | 16 +++--- .../component/config/DynamicRouteLocator.java | 31 +++++------ .../config/ResourceServerConfiguration.java | 7 --- .../pig/gateway/feign/ZuulRouteService.java | 26 ---------- .../ZuulRouteServiceFallbackImpl.java | 35 ------------- .../pig/admin/common/config/RabbitConfig.java | 20 +++++++ .../listener/RouteConfigInitListener.java | 47 +++++++++++++++++ .../admin/controller/ZuulRouteController.java | 40 +++++++------- .../admin/service/SysZuulRouteService.java | 5 ++ .../service/impl/SysUserServiceImpl.java | 1 - .../service/impl/SysZuulRouteServiceImpl.java | 26 ++++++++++ .../resources/templates/controller.java.vm | 52 +++++++++---------- .../main/resources/templates/listvue.vue.vm | 30 +++++------ .../src/main/resources/templates/menu.sql.vm | 10 ++-- .../monitor/filter/StatusChangeNotifier.java | 7 ++- pom.xml | 2 +- 19 files changed, 201 insertions(+), 166 deletions(-) rename pig-gateway/src/main/java/com/github/pig/gateway/{ => component/config}/DynamicRouteConfiguration.java (63%) delete mode 100644 pig-gateway/src/main/java/com/github/pig/gateway/feign/ZuulRouteService.java delete mode 100644 pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/ZuulRouteServiceFallbackImpl.java create mode 100644 pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/listener/RouteConfigInitListener.java diff --git a/pig-common/src/main/java/com/github/pig/common/constant/CommonConstant.java b/pig-common/src/main/java/com/github/pig/common/constant/CommonConstant.java index b5180711..988ad492 100644 --- a/pig-common/src/main/java/com/github/pig/common/constant/CommonConstant.java +++ b/pig-common/src/main/java/com/github/pig/common/constant/CommonConstant.java @@ -62,4 +62,9 @@ public interface CommonConstant { * 阿里大鱼 */ String ALIYUN_SMS = "aliyun_sms"; + + /** + * 路由信息Redis保存的key + */ + String ROUTE_KEY = "_ROUTE_KEY"; } diff --git a/pig-common/src/main/java/com/github/pig/common/constant/MqQueueConstant.java b/pig-common/src/main/java/com/github/pig/common/constant/MqQueueConstant.java index 11467df9..0b851d33 100644 --- a/pig-common/src/main/java/com/github/pig/common/constant/MqQueueConstant.java +++ b/pig-common/src/main/java/com/github/pig/common/constant/MqQueueConstant.java @@ -30,4 +30,9 @@ public interface MqQueueConstant { * zipkin 队列 */ String ZIPKIN_NAME_QUEUE = "zipkin"; + + /** + * 路由配置状态队列 + */ + String ROUTE_CONFIG_CHANGE = "route_config_change"; } diff --git a/pig-common/src/main/java/com/github/pig/common/vo/ZuulRouteVO.java b/pig-common/src/main/java/com/github/pig/common/vo/ZuulRouteVO.java index 92d7a240..574a756c 100644 --- a/pig-common/src/main/java/com/github/pig/common/vo/ZuulRouteVO.java +++ b/pig-common/src/main/java/com/github/pig/common/vo/ZuulRouteVO.java @@ -35,7 +35,7 @@ public class ZuulRouteVO { * Flag to determine whether the prefix for this route (the path, minus pattern * patcher) should be stripped before forwarding. */ - private boolean stripPrefix = true; + private Boolean stripPrefix; /** * Flag to indicate that this route should be retryable (if supported). Generally diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/DynamicRouteConfiguration.java b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/DynamicRouteConfiguration.java similarity index 63% rename from pig-gateway/src/main/java/com/github/pig/gateway/DynamicRouteConfiguration.java rename to pig-gateway/src/main/java/com/github/pig/gateway/component/config/DynamicRouteConfiguration.java index 8346d76b..73a97308 100644 --- a/pig-gateway/src/main/java/com/github/pig/gateway/DynamicRouteConfiguration.java +++ b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/DynamicRouteConfiguration.java @@ -1,15 +1,12 @@ -package com.github.pig.gateway; +package com.github.pig.gateway.component.config; -import com.github.pig.gateway.component.config.DynamicRouteLocator; -import com.github.pig.gateway.feign.ZuulRouteService; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; +import org.springframework.data.redis.core.RedisTemplate; /** * @author lengleng @@ -22,14 +19,15 @@ public class DynamicRouteConfiguration { private DiscoveryClient discovery; private ZuulProperties zuulProperties; private ServerProperties server; - private ZuulRouteService zuulRouteService; + private RedisTemplate redisTemplate; - public DynamicRouteConfiguration(ZuulRouteService zuulRouteService, Registration registration, DiscoveryClient discovery, ZuulProperties zuulProperties, ServerProperties server) { + public DynamicRouteConfiguration(Registration registration, DiscoveryClient discovery, + ZuulProperties zuulProperties, ServerProperties server, RedisTemplate redisTemplate) { this.registration = registration; this.discovery = discovery; this.zuulProperties = zuulProperties; this.server = server; - this.zuulRouteService = zuulRouteService; + this.redisTemplate = redisTemplate; } @Bean @@ -38,6 +36,6 @@ public class DynamicRouteConfiguration { , discovery , zuulProperties , registration - , zuulRouteService); + , redisTemplate); } } diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/component/config/DynamicRouteLocator.java b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/DynamicRouteLocator.java index 3501fa6a..a5819f7b 100644 --- a/pig-gateway/src/main/java/com/github/pig/gateway/component/config/DynamicRouteLocator.java +++ b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/DynamicRouteLocator.java @@ -1,18 +1,15 @@ package com.github.pig.gateway.component.config; -import com.github.pig.common.constant.ServiceNameConstant; +import com.github.pig.common.constant.CommonConstant; import com.github.pig.common.entity.SysZuulRoute; -import com.github.pig.gateway.feign.ZuulRouteService; import com.xiaoleilu.hutool.collection.CollUtil; -import com.xiaoleilu.hutool.util.ArrayUtil; import com.xiaoleilu.hutool.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator; import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; -import org.springframework.web.client.RestTemplate; +import org.springframework.data.redis.core.RedisTemplate; import java.util.LinkedHashMap; import java.util.List; @@ -27,13 +24,13 @@ import java.util.Set; @Slf4j public class DynamicRouteLocator extends DiscoveryClientRouteLocator { private ZuulProperties properties; - private RestTemplate restTemplate; - private ZuulRouteService zuulRouteService; + private RedisTemplate redisTemplate; - public DynamicRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties, ServiceInstance localServiceInstance, ZuulRouteService zuulRouteService) { + public DynamicRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties, + ServiceInstance localServiceInstance, RedisTemplate redisTemplate) { super(servletPath, discovery, properties, localServiceInstance); this.properties = properties; - this.zuulRouteService = zuulRouteService; + this.redisTemplate = redisTemplate; } /** @@ -50,7 +47,7 @@ public class DynamicRouteLocator extends DiscoveryClientRouteLocator { LinkedHashMap routesMap = new LinkedHashMap<>(); //读取properties配置、eureka默认配置 routesMap.putAll(super.locateRoutes()); - log.info("初始默认的路由配置完成"); + log.debug("初始默认的路由配置完成"); routesMap.putAll(locateRoutesFromDb()); LinkedHashMap values = new LinkedHashMap<>(); for (Map.Entry entry : routesMap.entrySet()) { @@ -70,21 +67,21 @@ public class DynamicRouteLocator extends DiscoveryClientRouteLocator { } /** - * 拉去路由配置先采用RestTemplate 加载eureka中信息来是实现 + * Redis中保存的,没有从upms拉去,避免启动链路依赖问题(取舍),网关依赖业务模块的问题 * * @return */ private Map locateRoutesFromDb() { Map routes = new LinkedHashMap<>(); - String url = String.format("http://localhost:4000/route/findAllZuulRoute", ServiceNameConstant.UMPS_SERVICE); - SysZuulRoute[] response = restTemplate.getForObject(url, SysZuulRoute[].class); - if (ArrayUtil.isEmpty(response)) { + Object obj = redisTemplate.opsForValue().get(CommonConstant.ROUTE_KEY); + if (obj == null) { return routes; } - for (SysZuulRoute result : response) { - if (StrUtil.isBlank(result.getPath()) || StrUtil.isBlank(result.getUrl())) { + List results = (List) obj; + for (SysZuulRoute result : results) { + if (StrUtil.isBlank(result.getPath()) && StrUtil.isBlank(result.getUrl())) { continue; } @@ -106,7 +103,7 @@ public class DynamicRouteLocator extends DiscoveryClientRouteLocator { } catch (Exception e) { log.error("从数据库加载路由配置异常", e); } - log.info("添加数据库自定义的路由配置,path:{},serviceId:{}", zuulRoute.getPath(), zuulRoute.getServiceId()); + log.debug("添加数据库自定义的路由配置,path:{},serviceId:{}", zuulRoute.getPath(), zuulRoute.getServiceId()); routes.put(zuulRoute.getPath(), zuulRoute); } return routes; diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java index 0a8bd226..39f19fa1 100644 --- a/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java +++ b/pig-gateway/src/main/java/com/github/pig/gateway/component/config/ResourceServerConfiguration.java @@ -2,17 +2,10 @@ package com.github.pig.gateway.component.config; import com.github.pig.common.bean.config.FilterIgnorePropertiesConfig; import com.github.pig.gateway.component.handler.PigAccessDeniedHandler; -import com.github.pig.gateway.feign.ZuulRouteService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.web.ServerProperties; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/feign/ZuulRouteService.java b/pig-gateway/src/main/java/com/github/pig/gateway/feign/ZuulRouteService.java deleted file mode 100644 index e6b6397c..00000000 --- a/pig-gateway/src/main/java/com/github/pig/gateway/feign/ZuulRouteService.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.github.pig.gateway.feign; - -import com.github.pig.common.entity.SysZuulRoute; -import com.github.pig.gateway.feign.fallback.MenuServiceFallbackImpl; -import com.github.pig.gateway.feign.fallback.ZuulRouteServiceFallbackImpl; -import org.springframework.cloud.netflix.feign.FeignClient; -import org.springframework.stereotype.Component; -import org.springframework.web.bind.annotation.GetMapping; - -import java.util.List; - -/** - * @author lengleng - * @date 2018/5/15 - * 远程获取zuul配置 - */ -@FeignClient(name = "pig-upms-service", fallback = ZuulRouteServiceFallbackImpl.class) -public interface ZuulRouteService { - /** - * 调用upms查询全部的路由配置 - * - * @return 路由配置表 - */ - @GetMapping(value = "/route/findAllZuulRoute") - List findAllZuulRoute(); -} diff --git a/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/ZuulRouteServiceFallbackImpl.java b/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/ZuulRouteServiceFallbackImpl.java deleted file mode 100644 index e193865e..00000000 --- a/pig-gateway/src/main/java/com/github/pig/gateway/feign/fallback/ZuulRouteServiceFallbackImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.github.pig.gateway.feign.fallback; - -import com.github.pig.common.entity.SysZuulRoute; -import com.github.pig.common.vo.MenuVO; -import com.github.pig.gateway.feign.MenuService; -import com.github.pig.gateway.feign.ZuulRouteService; -import com.xiaoleilu.hutool.collection.CollUtil; -import lombok.extern.slf4j.Slf4j; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Set; - -/** - * @author lengleng - * @date 2018/5/15 - * 远程调用路由接口异常回调 - */ -@Slf4j -@Service -public class ZuulRouteServiceFallbackImpl implements ZuulRouteService { - - /** - * 调用upms查询全部的路由配置 - * - * @return 路由配置表 - */ - @Override - public List findAllZuulRoute() { - log.error("获取远程路由配置失败"); - return CollUtil.newArrayList(); - } -} diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/config/RabbitConfig.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/config/RabbitConfig.java index cbc78a80..1f8a1c65 100644 --- a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/config/RabbitConfig.java +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/config/RabbitConfig.java @@ -42,13 +42,33 @@ public class RabbitConfig { return new Queue(MqQueueConstant.MOBILE_SERVICE_STATUS_CHANGE); } + /** + * 初始化钉钉状态改变队列 + * + * @return + */ @Bean public Queue initDingTalkServiceStatusChangeQueue() { return new Queue(MqQueueConstant.DINGTALK_SERVICE_STATUS_CHANGE); } + /** + * 初始化zipkin队列 + * + * @return + */ @Bean public Queue initZipkinQueue() { return new Queue(MqQueueConstant.ZIPKIN_NAME_QUEUE); } + + /** + * 初始化路由配置状态队列 + * + * @return + */ + @Bean + public Queue initRouteConfigChangeQueue() { + return new Queue(MqQueueConstant.ROUTE_CONFIG_CHANGE); + } } diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/listener/RouteConfigInitListener.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/listener/RouteConfigInitListener.java new file mode 100644 index 00000000..ee3d94e7 --- /dev/null +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/common/listener/RouteConfigInitListener.java @@ -0,0 +1,47 @@ +package com.github.pig.admin.common.listener; + +import com.baomidou.mybatisplus.mapper.EntityWrapper; +import com.github.pig.admin.service.SysZuulRouteService; +import com.github.pig.common.constant.CommonConstant; +import com.github.pig.common.entity.SysZuulRoute; +import com.xiaoleilu.hutool.collection.CollUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * @author lengleng + * @date 2018/5/16 + */ +@Slf4j +@Component +public class RouteConfigInitListener implements ApplicationRunner { + @Autowired + private RedisTemplate redisTemplate; + @Autowired + private SysZuulRouteService sysZuulRouteService; + + /** + * Callback used to run the bean. + * 初始化路由配置的数据,避免gateway 依赖业务模块 + * + * @param args incoming application arguments + */ + @Override + public void run(ApplicationArguments args) { + log.info("开始初始化路由配置数据"); + EntityWrapper wrapper = new EntityWrapper(); + wrapper.eq(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL); + List routeList = sysZuulRouteService.selectList(wrapper); + if (CollUtil.isNotEmpty(routeList)) { + redisTemplate.opsForValue().set(CommonConstant.ROUTE_KEY, routeList); + log.info("更新Redis中路由配置数据:{}条", routeList.size()); + } + log.info("初始化路由配置数据完毕"); + } +} \ No newline at end of file diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/ZuulRouteController.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/ZuulRouteController.java index b48ecdd5..9713a380 100644 --- a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/ZuulRouteController.java +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/controller/ZuulRouteController.java @@ -1,19 +1,18 @@ package com.github.pig.admin.controller; -import java.util.List; -import java.util.Map; -import java.util.Date; - -import com.github.pig.common.entity.SysZuulRoute; -import com.github.pig.common.util.R; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import com.github.pig.common.constant.CommonConstant; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; -import com.github.pig.common.util.Query; import com.github.pig.admin.service.SysZuulRouteService; +import com.github.pig.common.constant.CommonConstant; +import com.github.pig.common.entity.SysZuulRoute; +import com.github.pig.common.util.Query; +import com.github.pig.common.util.R; import com.github.pig.common.web.BaseController; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Date; +import java.util.Map; /** *

@@ -28,7 +27,6 @@ import com.github.pig.common.web.BaseController; public class ZuulRouteController extends BaseController { @Autowired private SysZuulRouteService sysZuulRouteService; - /** * 通过ID查询 * @@ -40,16 +38,6 @@ public class ZuulRouteController extends BaseController { return sysZuulRouteService.selectById(id); } - /** - * 查询全部路由配置 - * - * @return 路由配置表 - */ - @GetMapping("/findAllZuulRoute") - public List findAllZuulRoute() { - return sysZuulRouteService.selectList(new EntityWrapper<>()); - } - /** * 分页查询信息 * @@ -99,4 +87,14 @@ public class ZuulRouteController extends BaseController { sysZuulRoute.setUpdateTime(new Date()); return new R<>(sysZuulRouteService.updateById(sysZuulRoute)); } + + /** + * 刷新配置 + * + * @return success/fasle + */ + @GetMapping("/apply") + public R apply() { + return new R<>(sysZuulRouteService.applyZuulRoute()); + } } diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysZuulRouteService.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysZuulRouteService.java index c35620ef..af990360 100644 --- a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysZuulRouteService.java +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/SysZuulRouteService.java @@ -13,4 +13,9 @@ import com.github.pig.common.entity.SysZuulRoute; */ public interface SysZuulRouteService extends IService { + /** + * 立即生效配置 + * @return + */ + Boolean applyZuulRoute(); } diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysUserServiceImpl.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysUserServiceImpl.java index a17e57f3..12b5e9e8 100644 --- a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysUserServiceImpl.java +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysUserServiceImpl.java @@ -128,7 +128,6 @@ public class SysUserServiceImpl extends ServiceImpl impl dataScope.setScopeName("deptId"); dataScope.setIsOnly(true); dataScope.setDeptIds(getChildDepts()); - dataScope.putAll(query.getCondition()); query.setRecords(sysUserMapper.selectUserVoPageDataScope(query, dataScope)); return query; } diff --git a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysZuulRouteServiceImpl.java b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysZuulRouteServiceImpl.java index e7332c98..38641519 100644 --- a/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysZuulRouteServiceImpl.java +++ b/pig-modules/pig-upms-service/src/main/java/com/github/pig/admin/service/impl/SysZuulRouteServiceImpl.java @@ -1,11 +1,19 @@ package com.github.pig.admin.service.impl; +import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.github.pig.admin.mapper.SysZuulRouteMapper; import com.baomidou.mybatisplus.service.impl.ServiceImpl; +import com.github.pig.common.constant.CommonConstant; +import com.github.pig.common.constant.MqQueueConstant; import com.github.pig.common.entity.SysZuulRoute; import com.github.pig.admin.service.SysZuulRouteService; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; +import java.util.List; + /** *

* 动态路由配置表 服务实现类 @@ -16,5 +24,23 @@ import org.springframework.stereotype.Service; */ @Service public class SysZuulRouteServiceImpl extends ServiceImpl implements SysZuulRouteService { + @Autowired + private RedisTemplate redisTemplate; + @Autowired + private RabbitTemplate rabbitTemplate; + /** + * 立即生效配置 + * + * @return + */ + @Override + public Boolean applyZuulRoute() { + EntityWrapper wrapper = new EntityWrapper(); + wrapper.eq(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL); + List routeList = selectList(wrapper); + redisTemplate.opsForValue().set(CommonConstant.ROUTE_KEY, routeList); + rabbitTemplate.convertAndSend(MqQueueConstant.ROUTE_CONFIG_CHANGE, 1); + return Boolean.TRUE; + } } diff --git a/pig-modules/pig-upms-service/src/main/resources/templates/controller.java.vm b/pig-modules/pig-upms-service/src/main/resources/templates/controller.java.vm index 3d7af8ec..1bc22aa4 100644 --- a/pig-modules/pig-upms-service/src/main/resources/templates/controller.java.vm +++ b/pig-modules/pig-upms-service/src/main/resources/templates/controller.java.vm @@ -1,4 +1,4 @@ -package ${package.Controller}; +package $!{package.Controller}; import java.util.Map; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; @@ -8,10 +8,10 @@ import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.github.pig.common.util.Query; import com.github.pig.common.util.R; -import ${package.Entity}.${entity}; -import ${package.Service}.${entity}Service; -#if(${superControllerClassPackage}) -import ${superControllerClassPackage}; +import $!{package.Entity}.$!{entity}; +import $!{package.Service}.$!{entity}Service; +#if($!{superControllerClassPackage}) +import $!{superControllerClassPackage}; #end /** @@ -19,23 +19,23 @@ import ${superControllerClassPackage}; * $!{table.comment} 前端控制器 *

* - * @author ${author} - * @since ${date} + * @author $!{author} + * @since $!{date} */ @RestController -@RequestMapping("/${table.entityPath}") -public class ${table.controllerName} extends ${superControllerClass} { - @Autowired private ${entity}Service ${table.entityPath}Service; +@RequestMapping("/$!{table.entityPath}") +public class $!{table.controllerName} extends $!{superControllerClass} { + @Autowired private $!{entity}Service $!{table.entityPath}Service; /** * 通过ID查询 * * @param id ID - * @return ${entity} + * @return $!{entity} */ @GetMapping("/{id}") - public R<${entity}> get(@PathVariable Integer id) { - return new R<>(${table.entityPath}Service.selectById(id)); + public R<$!{entity}> get(@PathVariable Integer id) { + return new R<>($!{table.entityPath}Service.selectById(id)); } @@ -48,17 +48,17 @@ public class ${table.controllerName} extends ${superControllerClass} { @RequestMapping("/page") public Page page(@RequestParam Map params) { params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL); - return ${table.entityPath}Service.selectPage(new Query<>(params), new EntityWrapper<>()); + return $!{table.entityPath}Service.selectPage(new Query<>(params), new EntityWrapper<>()); } /** * 添加 - * @param ${table.entityPath} 实体 + * @param $!{table.entityPath} 实体 * @return success/false */ @PostMapping - public R add(@RequestBody ${entity} ${table.entityPath}) { - return new R<>(${table.entityPath}Service.insert(${table.entityPath})); + public R add(@RequestBody $!{entity} $!{table.entityPath}) { + return new R<>($!{table.entityPath}Service.insert($!{table.entityPath})); } /** @@ -68,21 +68,21 @@ public class ${table.controllerName} extends ${superControllerClass} { */ @DeleteMapping("/{id}") public R delete(@PathVariable Integer id) { - ${entity} ${table.entityPath} = new ${entity}(); - ${table.entityPath}.setId(id); - ${table.entityPath}.setUpdateTime(new Date()); - ${table.entityPath}.setDelFlag(CommonConstant.STATUS_DEL); - return new R<>(${table.entityPath}Service.updateById(${table.entityPath})); + $!{entity} $!{table.entityPath} = new $!{entity}(); + $!{table.entityPath}.setId(id); + $!{table.entityPath}.setUpdateTime(new Date()); + $!{table.entityPath}.setDelFlag(CommonConstant.STATUS_DEL); + return new R<>($!{table.entityPath}Service.updateById($!{table.entityPath})); } /** * 编辑 - * @param ${table.entityPath} 实体 + * @param $!{table.entityPath} 实体 * @return success/false */ @PutMapping - public R edit(@RequestBody ${entity} ${table.entityPath}) { - ${table.entityPath}.setUpdateTime(new Date()); - return new R<>(${table.entityPath}Service.updateById(${table.entityPath})); + public R edit(@RequestBody $!{entity} $!{table.entityPath}) { + $!{table.entityPath}.setUpdateTime(new Date()); + return new R<>($!{table.entityPath}Service.updateById($!{table.entityPath})); } } diff --git a/pig-modules/pig-upms-service/src/main/resources/templates/listvue.vue.vm b/pig-modules/pig-upms-service/src/main/resources/templates/listvue.vue.vm index 8dc4f9c2..4dcd549b 100644 --- a/pig-modules/pig-upms-service/src/main/resources/templates/listvue.vue.vm +++ b/pig-modules/pig-upms-service/src/main/resources/templates/listvue.vue.vm @@ -1,25 +1,25 @@