sunyuchao 5 years ago
parent
commit
93630dff62
  1. 13
      doc/epmet-cloud.md
  2. 14
      doc/开发规范/命名规范.txt
  3. BIN
      doc/开发规范/阿里巴巴java开发规范1.4.pdf
  4. 11
      epmet-admin/epmet-admin-server/Dockerfile
  5. 17
      epmet-admin/epmet-admin-server/deploy/docker-compose-dev.yml
  6. 17
      epmet-admin/epmet-admin-server/deploy/docker-compose-prod.yml
  7. 17
      epmet-admin/epmet-admin-server/deploy/docker-compose-test.yml
  8. 61
      epmet-admin/epmet-admin-server/pom.xml
  9. 40
      epmet-admin/epmet-admin-server/src/main/java/com/epmet/aspect/RequestLogAspect.java
  10. 2
      epmet-admin/epmet-admin-server/src/main/java/com/epmet/entity/SysLogErrorEntity.java
  11. 2
      epmet-admin/epmet-admin-server/src/main/java/com/epmet/service/impl/NewsServiceImpl.java
  12. 16
      epmet-admin/epmet-admin-server/src/main/resources/bootstrap.yml
  13. 1
      epmet-admin/epmet-admin-server/src/main/resources/db/migration/V0.0.1__demo.sql
  14. 1
      epmet-admin/epmet-admin-server/src/main/resources/db/migration/V0.0.2__UPDATE_SMS_CONFIG_KEY.sql
  15. 13
      epmet-admin/epmet-admin-server/src/main/resources/logback-spring.xml
  16. 96
      epmet-admin/epmet-admin-server/src/test/java/io/renren/service/DynamicDataSourceTest.java
  17. 11
      epmet-auth/Dockerfile
  18. 17
      epmet-auth/deploy/docker-compose-dev.yml
  19. 17
      epmet-auth/deploy/docker-compose-prod.yml
  20. 17
      epmet-auth/deploy/docker-compose-test.yml
  21. 148
      epmet-auth/pom.xml
  22. 40
      epmet-auth/src/main/java/com/epmet/aspect/RequestLogAspect.java
  23. 24
      epmet-auth/src/main/java/com/epmet/constant/AuthHttpUrlConstant.java
  24. 22
      epmet-auth/src/main/java/com/epmet/constant/PublicUserLoginConstant.java
  25. 30
      epmet-auth/src/main/java/com/epmet/constant/ThirdApiConstant.java
  26. 29
      epmet-auth/src/main/java/com/epmet/controller/BackDoorController.java
  27. 125
      epmet-auth/src/main/java/com/epmet/controller/GovLoginController.java
  28. 117
      epmet-auth/src/main/java/com/epmet/controller/LoginController.java
  29. 95
      epmet-auth/src/main/java/com/epmet/controller/PublicUserLoginController.java
  30. 94
      epmet-auth/src/main/java/com/epmet/controller/ThirdLoginController.java
  31. 48
      epmet-auth/src/main/java/com/epmet/dto/form/GovWxmpEnteOrgFormDTO.java
  32. 27
      epmet-auth/src/main/java/com/epmet/dto/form/GovWxmpFormDTO.java
  33. 40
      epmet-auth/src/main/java/com/epmet/dto/form/LoginByPassWordFormDTO.java
  34. 43
      epmet-auth/src/main/java/com/epmet/dto/form/LoginByPhoneFormDTO.java
  35. 34
      epmet-auth/src/main/java/com/epmet/dto/form/LoginByWxCodeFormDTO.java
  36. 30
      epmet-auth/src/main/java/com/epmet/dto/form/LoginCommonFormDTO.java
  37. 28
      epmet-auth/src/main/java/com/epmet/dto/form/LoginFormDTO.java
  38. 27
      epmet-auth/src/main/java/com/epmet/dto/form/PaWxCodeFormDTO.java
  39. 39
      epmet-auth/src/main/java/com/epmet/dto/form/PublicSendSmsCodeFormDTO.java
  40. 37
      epmet-auth/src/main/java/com/epmet/dto/form/ResiWxPhoneFormDTO.java
  41. 26
      epmet-auth/src/main/java/com/epmet/dto/form/SendSmsCodeFormDTO.java
  42. 43
      epmet-auth/src/main/java/com/epmet/dto/form/StaffOrgsFormDTO.java
  43. 48
      epmet-auth/src/main/java/com/epmet/dto/form/ThirdStaffOrgsFormDTO.java
  44. 47
      epmet-auth/src/main/java/com/epmet/dto/form/ThirdWxmpEnteOrgFormDTO.java
  45. 19
      epmet-auth/src/main/java/com/epmet/dto/form/UpdateCachedRolesFormDTO.java
  46. 20
      epmet-auth/src/main/java/com/epmet/dto/result/UserTokenResultDTO.java
  47. 118
      epmet-auth/src/main/java/com/epmet/feign/EpmetUserFeignClient.java
  48. 58
      epmet-auth/src/main/java/com/epmet/feign/GovOrgFeignClient.java
  49. 71
      epmet-auth/src/main/java/com/epmet/feign/fallback/EpmetUserFeignClientFallback.java
  50. 44
      epmet-auth/src/main/java/com/epmet/feign/fallback/GovOrgFeignClientFallback.java
  51. 41
      epmet-auth/src/main/java/com/epmet/jwt/JwtTokenProperties.java
  52. 132
      epmet-auth/src/main/java/com/epmet/jwt/JwtTokenUtils.java
  53. 5
      epmet-auth/src/main/java/com/epmet/jwt/JwtUtils.java
  54. 65
      epmet-auth/src/main/java/com/epmet/redis/CaptchaRedis.java
  55. 124
      epmet-auth/src/main/java/com/epmet/redis/CustomerAppWxServiceUtil.java
  56. 79
      epmet-auth/src/main/java/com/epmet/service/GovLoginService.java
  57. 63
      epmet-auth/src/main/java/com/epmet/service/LoginService.java
  58. 50
      epmet-auth/src/main/java/com/epmet/service/PublicUserLoginService.java
  59. 56
      epmet-auth/src/main/java/com/epmet/service/ThirdLoginService.java
  60. 5
      epmet-auth/src/main/java/com/epmet/service/impl/CaptchaServiceImpl.java
  61. 493
      epmet-auth/src/main/java/com/epmet/service/impl/GovLoginServiceImpl.java
  62. 409
      epmet-auth/src/main/java/com/epmet/service/impl/LoginServiceImpl.java
  63. 307
      epmet-auth/src/main/java/com/epmet/service/impl/PublicUserLoginServiceImpl.java
  64. 546
      epmet-auth/src/main/java/com/epmet/service/impl/ThirdLoginServiceImpl.java
  65. 43
      epmet-auth/src/main/resources/bootstrap.yml
  66. 13
      epmet-auth/src/main/resources/logback-spring.xml
  67. 101
      epmet-auth/src/test/java/com/epmet/TokenGenTest.java
  68. 6
      epmet-cloud-generator/src/main/resources/application.yml
  69. 2
      epmet-cloud-generator/src/main/resources/generator.properties
  70. 125
      epmet-commons/epmet-common-clienttoken/pom.xml
  71. 31
      epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/annotation/Login.java
  72. 13
      epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/annotation/NeedClientToken.java
  73. 43
      epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/constant/LoginConstant.java
  74. 23
      epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/property/TokenPropertise.java
  75. 49
      epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/util/TokenUtil.java
  76. 55
      epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/util/UserUtil.java
  77. 13
      epmet-commons/epmet-commons-mybatis/pom.xml
  78. 25
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/annotation/DataFilter.java
  79. 147
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/aspect/DataFilterAspect.java
  80. 9
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/AccessSettingFormDTO.java
  81. 49
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/DepartmentListResultDTO.java
  82. 29
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/GetSQLFilterFormDTO.java
  83. 92
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/OperationScopeDTO.java
  84. 18
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/OperationScopeFormDTO.java
  85. 33
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/RoleOpeScopeResultDTO.java
  86. 59
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/StaffPermCacheFormDTO.java
  87. 37
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/StaffPermCacheResultDTO.java
  88. 26
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/StaffPermissionFormDTO.java
  89. 9
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/entity/DataScope.java
  90. 30
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/feign/MybatisGovAccessFeignClient.java
  91. 29
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/feign/MybatisGovOrgFeignClient.java
  92. 28
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/feign/fallback/MybatisGovAccessFeignClientFallback.java
  93. 26
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/feign/fallback/MybatisGovOrgFeignClientFallback.java
  94. 77
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/handler/FieldMetaObjectHandler.java
  95. 46
      epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/interceptor/DataFilterInterceptor.java
  96. 33
      epmet-commons/epmet-commons-service-call/pom.xml
  97. 94
      epmet-commons/epmet-commons-service-call/src/main/java/com/epmet/loadbalancer/EpmetRequestLoadBalancerRule.java
  98. 41
      epmet-commons/epmet-commons-tools-phone/pom.xml
  99. 79
      epmet-commons/epmet-commons-tools-phone/src/main/java/com/epmet/commons/tools/utils/PhoneDto.java
  100. 178
      epmet-commons/epmet-commons-tools-phone/src/main/java/com/epmet/commons/tools/utils/PhoneUtil.java

13
doc/epmet-cloud.md

@ -0,0 +1,13 @@
## 开发环境使用
##### 本机调用开发环境
```
开发环境已经搭建好了
在最新的代码中:
默认情况下,所有服务的pom.xml中应该启用dev环境,其他环境的active应该被注释掉(dev-local不再有用,可以删除)
根据dev环境中的配置,微服务会注册到nacos,并且调用其他微服务的时候会从nacos中取目标微服务的ip来发送请求
因此,本地电脑不再需要启动所有服务,只需要启动要开发的服务即可;默认情况下,本机的微服务在调用目标微服务的时候,都是调用的服务器,不再请求本地。
例如:有A、B2个服务,并且A调用B,如果我们只需要开发A服务,那本地只启动A服务即可,A调用B的时候,会调用服务器的B服务。
如果需要开发AB2个服务,那么将A中的FeignClient的url属性指向localhost。
PS:目前正在测试通过负载均衡器和本地环境变量实现动态修改目标服务IP,成功之后就不需要再修改FeignClient的url,配置一下环境变量即可,到时候具体说
```

14
doc/开发规范/命名规范.txt

@ -0,0 +1,14 @@
一、controller
1、方法名和接口名一致,改为驼峰式
二、service层:
2、同controller一致
三、dao层:
1、结果集是集合用selectListXXX
2、结果集为一个实例用selectOneXXX
3、更新:updateXXX
4、插入:insertXXX
5、删除:deleteXXX
6、获取统计值的方法用 selectCount

BIN
doc/开发规范/阿里巴巴java开发规范1.4.pdf

Binary file not shown.

11
epmet-admin/epmet-admin-server/Dockerfile

@ -0,0 +1,11 @@
FROM java:8
RUN export LANG="zh_CN.UTF-8"
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo 'Asia/Shanghai' > /etc/timezone
COPY ./target/*.jar ./app.jar
EXPOSE 8082
ENTRYPOINT ["sh", "-c", "$RUN_INSTRUCT"]

17
epmet-admin/epmet-admin-server/deploy/docker-compose-dev.yml

@ -0,0 +1,17 @@
version: "3.7"
services:
epmet-admin-server:
container_name: epmet-admin-server-dev
image: 192.168.1.130:10080/epmet-cloud-dev/epmet-admin-server:0.3.15
ports:
- "8082:8082"
network_mode: host # 使用现有网络
volumes:
- "/opt/epmet-cloud-logs/dev:/logs"
environment:
RUN_INSTRUCT: "java -Xms32m -Xmx200m -jar ./app.jar"
deploy:
resources:
limits:
cpus: '0.1'
memory: 250M

17
epmet-admin/epmet-admin-server/deploy/docker-compose-prod.yml

@ -0,0 +1,17 @@
version: "3.7"
services:
epmet-admin-server:
container_name: epmet-admin-server-prod
image: registry-vpc.cn-qingdao.aliyuncs.com/epmet-cloud-master/epmet-admin-server:0.3.15
ports:
- "8082:8082"
network_mode: host # 使用现有网络
volumes:
- "/opt/epmet-cloud-logs/prod:/logs"
environment:
RUN_INSTRUCT: "java -Xms256m -Xmx512m -jar ./app.jar"
deploy:
resources:
limits:
cpus: '0.1'
memory: 600M

17
epmet-admin/epmet-admin-server/deploy/docker-compose-test.yml

@ -0,0 +1,17 @@
version: "3.7"
services:
epmet-admin-server:
container_name: epmet-admin-server-test
image: registry-vpc.cn-qingdao.aliyuncs.com/epmet-cloud-release/epmet-admin-server:0.3.15
ports:
- "8082:8082"
network_mode: host # 使用现有网络
volumes:
- "/opt/epmet-cloud-logs/test:/logs"
environment:
RUN_INSTRUCT: "java -Xms32m -Xmx200m -jar ./app.jar"
deploy:
resources:
limits:
cpus: '0.1'
memory: 250M

61
epmet-admin/epmet-admin-server/pom.xml

@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<version>0.3.15</version>
<parent>
<groupId>com.epmet</groupId>
<artifactId>epmet-admin</artifactId>
@ -48,6 +48,12 @@
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- 替换Feign原生httpclient -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>10.3.0</version>
</dependency>
</dependencies>
<build>
@ -87,23 +93,25 @@
<!-- 数据库配置-->
<spring.datasource.druid.url>
<![CDATA[jdbc:mysql://47.104.224.45:3308/epmet_admin?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai]]>
<![CDATA[jdbc:mysql://192.168.1.130:3306/epmet_admin?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai]]>
</spring.datasource.druid.url>
<spring.datasource.druid.username>epmet</spring.datasource.druid.username>
<spring.datasource.druid.password>elink@833066</spring.datasource.druid.password>
<spring.datasource.druid.username>epmet_admin_user</spring.datasource.druid.username>
<spring.datasource.druid.password>EpmEt-db-UsEr</spring.datasource.druid.password>
<!-- redis配置 -->
<spring.redis.index>0</spring.redis.index>
<spring.redis.host>122.152.200.70</spring.redis.host>
<spring.redis.host>192.168.1.130</spring.redis.host>
<spring.redis.port>6379</spring.redis.port>
<spring.redis.password>123456</spring.redis.password>
<!-- nacos -->
<nacos.register-enabled>false</nacos.register-enabled>
<nacos.register-enabled>true</nacos.register-enabled>
<nacos.server-addr>122.152.200.70:8848</nacos.server-addr>
<nacos.discovery.namespace>fcd6fc8f-ca3a-4b01-8026-2b05cdc5976b</nacos.discovery.namespace>
<nacos.config.namespace></nacos.config.namespace>
<nacos.config.group></nacos.config.group>
<nacos.config-enabled>false</nacos.config-enabled>
<nacos.ip/>
<spring.flyway.enabled>false</spring.flyway.enabled>
</properties>
</profile>
<profile>
@ -117,23 +125,54 @@
<!-- 数据库配置-->
<spring.datasource.druid.url>
<![CDATA[jdbc:mysql://47.104.224.45:3308/epmet_admin?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai]]>
<![CDATA[jdbc:mysql://rm-m5ef9t617j6o5eup7.mysql.rds.aliyuncs.com:3306/epmet_admin?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai]]>
</spring.datasource.druid.url>
<spring.datasource.druid.username>epmet</spring.datasource.druid.username>
<spring.datasource.druid.password>elink@833066</spring.datasource.druid.password>
<!-- redis配置 -->
<spring.redis.index>0</spring.redis.index>
<spring.redis.host>122.152.200.70</spring.redis.host>
<spring.redis.host>r-m5eoz5b6tkx09y6bpz.redis.rds.aliyuncs.com</spring.redis.host>
<spring.redis.port>6379</spring.redis.port>
<spring.redis.password>123456</spring.redis.password>
<spring.redis.password>EpmEtrEdIs!q@w</spring.redis.password>
<!-- nacos -->
<nacos.register-enabled>true</nacos.register-enabled>
<nacos.server-addr>122.152.200.70:8848</nacos.server-addr>
<nacos.discovery.namespace>fcd6fc8f-ca3a-4b01-8026-2b05cdc5976b</nacos.discovery.namespace>
<nacos.server-addr>192.168.10.150:8848</nacos.server-addr>
<nacos.discovery.namespace>67e3c350-533e-4d7c-9f8f-faf1b4aa82ae</nacos.discovery.namespace>
<nacos.config.namespace></nacos.config.namespace>
<nacos.config.group></nacos.config.group>
<nacos.config-enabled>false</nacos.config-enabled>
<nacos.ip/>
<spring.flyway.enabled>true</spring.flyway.enabled>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<server.port>8082</server.port>
<spring.profiles.active>prod</spring.profiles.active>
<!-- 数据库配置-->
<spring.datasource.druid.url>
<![CDATA[jdbc:mysql://rm-m5e3vzs2637224wj9.mysql.rds.aliyuncs.com:3306/epmet_admin?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai]]>
</spring.datasource.druid.url>
<spring.datasource.druid.username>epmet_admin_user</spring.datasource.druid.username>
<spring.datasource.druid.password>EpmEt-db-UsEr</spring.datasource.druid.password>
<!-- redis配置 -->
<spring.redis.index>0</spring.redis.index>
<spring.redis.host>r-m5ez3n1j0qc3ykq2ut.redis.rds.aliyuncs.com</spring.redis.host>
<spring.redis.port>6379</spring.redis.port>
<spring.redis.password>EpmEtclOUdrEdIs!Q2w</spring.redis.password>
<!-- nacos -->
<nacos.register-enabled>true</nacos.register-enabled>
<nacos.server-addr>192.168.11.180:8848</nacos.server-addr>
<nacos.discovery.namespace>bd205d23-e696-47be-b995-916313f86e99</nacos.discovery.namespace>
<nacos.config.namespace></nacos.config.namespace>
<nacos.config.group></nacos.config.group>
<nacos.config-enabled>false</nacos.config-enabled>
<nacos.ip/>
<spring.flyway.enabled>true</spring.flyway.enabled>
</properties>
</profile>
</profiles>

40
epmet-admin/epmet-admin-server/src/main/java/com/epmet/aspect/RequestLogAspect.java

@ -0,0 +1,40 @@
package com.epmet.aspect;
import com.epmet.commons.tools.aspect.BaseRequestLogAspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 日志/异常处理切面实现调用父类方法完成日志记录和异常处理
*/
@Aspect
@Component
@Order(0)
public class RequestLogAspect extends BaseRequestLogAspect {
@Override
@Around(value = "execution(* com.epmet.controller.*Controller*.*(..)) ")
public Object proceed(ProceedingJoinPoint point) throws Throwable {
return super.proceed(point, getRequest());
}
/**
* 获取Request对象
*
* @return
*/
private HttpServletRequest getRequest() {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
return sra.getRequest();
}
}

2
epmet-admin/epmet-admin-server/src/main/java/com/epmet/entity/SysLogErrorEntity.java

@ -62,7 +62,7 @@ public class SysLogErrorEntity implements Serializable {
/**
* 创建者
*/
private Long creator;
private String creator;
/**
* 创建时间
*/

2
epmet-admin/epmet-admin-server/src/main/java/com/epmet/service/impl/NewsServiceImpl.java

@ -31,7 +31,7 @@ public class NewsServiceImpl extends BaseServiceImpl<NewsDao, NewsEntity> implem
* mybatis数据权限演示
*/
@Override
@DataFilter(prefix = "AND", isPendingCreator = false)
//@DataFilter(prefix = "AND", isPendingCreator = false)
public PageData<NewsDTO> page(Map<String, Object> params) {
paramsToLike(params, "title");

16
epmet-admin/epmet-admin-server/src/main/resources/bootstrap.yml

@ -66,6 +66,15 @@ spring:
namespace: @nacos.config.namespace@
group: @nacos.config.group@
file-extension: yaml
# 数据迁移工具flyway
flyway:
enabled: @spring.flyway.enabled@
locations: classpath:db/migration
url: @spring.datasource.druid.url@
user: @spring.datasource.druid.username@
password: @spring.datasource.druid.password@
baseline-on-migrate: true
baseline-version: 0
management:
endpoints:
web:
@ -84,6 +93,10 @@ mybatis-plus:
db-config:
#主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
id-type: ID_WORKER
#字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断"
field-strategy: NOT_NULL
#驼峰下划线转换
column-underline: true
banner: false
#原生配置
configuration:
@ -101,8 +114,7 @@ feign:
loggerLevel: BASIC
httpclient:
enabled: true
max-connections: 200
max-connections-per-route: 50
hystrix:
command:

1
epmet-admin/epmet-admin-server/src/main/resources/db/migration/V0.0.1__demo.sql

@ -0,0 +1 @@
select 0;

1
epmet-admin/epmet-admin-server/src/main/resources/db/migration/V0.0.2__UPDATE_SMS_CONFIG_KEY.sql

@ -0,0 +1 @@
UPDATE `epmet_admin`.`sys_params` SET `param_code` = 'SMS_CONFIG_KEY', `param_value` = '{\"aliyunAccessKeyId\":\"LTAI4G5KMmkxpix924ddeVNM\",\"aliyunAccessKeySecret\":\"92nB7g5L1JmBGSzZG5xsdGvfv9O8WX\",\"aliyunSignName\":\"党群e事通\",\"aliyunTemplateCode\":\"SMS_150731394\",\"platform\":1,\"qcloudAppId\":2,\"qcloudAppKey\":\"2\",\"qcloudSignName\":\"2\",\"qcloudTemplateId\":\"2\"}', `param_type` = 0, `remark` = '短信配置信息', `del_flag` = 0, `creator` = 1067246875800000001, `create_date` = '2020-03-08 16:31:36', `updater` = 1067246875800000001, `update_date` = '2020-03-08 16:31:36' WHERE `id` = 1067246875800000146;

13
epmet-admin/epmet-admin-server/src/main/resources/logback-spring.xml

@ -4,6 +4,11 @@
<property name="log.path" value="logs/admin"/>
<springProperty scope="context" name="appname" source="spring.application.name"/>
<!-- 日志上下文名称 -->
<contextName>${appname}</contextName>
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN"
value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
@ -28,7 +33,7 @@
<file>${log.path}/debug.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%contextName] [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
@ -55,7 +60,7 @@
<file>${log.path}/info.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%contextName] [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
@ -82,7 +87,7 @@
<file>${log.path}/warn.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%contextName] [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
@ -108,7 +113,7 @@
<file>${log.path}/error.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%contextName] [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->

96
epmet-admin/epmet-admin-server/src/test/java/io/renren/service/DynamicDataSourceTest.java

@ -1,48 +1,48 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 多数据源测试
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class DynamicDataSourceTest {
@Autowired
private DynamicDataSourceTestService dynamicDataSourceTestService;
@Test
public void test(){
Long id = 1067246875800000001L;
dynamicDataSourceTestService.selectById(id);
dynamicDataSourceTestService.updateUser(id);
dynamicDataSourceTestService.updateUserBySlave1(id);
dynamicDataSourceTestService.updateUserBySlave2(id);
}
}
///**
// * Copyright 2018 人人开源 https://www.renren.io
// * <p>
// * This program is free software: you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation, either version 3 of the License, or
// * (at your option) any later version.
// * <p>
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// * <p>
// * You should have received a copy of the GNU General Public License
// * along with this program. If not, see <http://www.gnu.org/licenses/>.
// */
//
//package com.epmet.service;
//
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.test.context.junit4.SpringRunner;
//
///**
// * 多数据源测试
// *
// * @author Mark sunlightcs@gmail.com
// * @since 1.0.0
// */
//@RunWith(SpringRunner.class)
//@SpringBootTest
//public class DynamicDataSourceTest {
// @Autowired
// private com.epmet.service.DynamicDataSourceTestService dynamicDataSourceTestService;
//
// @Test
// public void test(){
// Long id = 1067246875800000001L;
// dynamicDataSourceTestService.selectById(id);
// dynamicDataSourceTestService.updateUser(id);
// dynamicDataSourceTestService.updateUserBySlave1(id);
// dynamicDataSourceTestService.updateUserBySlave2(id);
// }
//
//
//}

11
epmet-auth/Dockerfile

@ -0,0 +1,11 @@
FROM java:8
RUN export LANG="zh_CN.UTF-8"
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo 'Asia/Shanghai' > /etc/timezone
COPY ./target/*.jar ./app.jar
EXPOSE 8081
ENTRYPOINT ["sh", "-c", "$RUN_INSTRUCT"]

17
epmet-auth/deploy/docker-compose-dev.yml

@ -0,0 +1,17 @@
version: "3.7"
services:
epmet-auth-server:
container_name: epmet-auth-server-dev
image: 192.168.1.130:10080/epmet-cloud-dev/epmet-auth:0.3.67
ports:
- "8081:8081"
network_mode: host # 使用现有网络
volumes:
- "/opt/epmet-cloud-logs/dev:/logs"
environment:
RUN_INSTRUCT: "java -Xms32m -Xmx200m -jar ./app.jar"
deploy:
resources:
limits:
cpus: '0.1'
memory: 250M

17
epmet-auth/deploy/docker-compose-prod.yml

@ -0,0 +1,17 @@
version: "3.7"
services:
epmet-auth-server:
container_name: epmet-auth-server-prod
image: registry-vpc.cn-qingdao.aliyuncs.com/epmet-cloud-master/epmet-auth:0.3.66
ports:
- "8081:8081"
network_mode: host # 使用现有网络
volumes:
- "/opt/epmet-cloud-logs/prod:/logs"
environment:
RUN_INSTRUCT: "java -Xms256m -Xmx512m -jar ./app.jar"
deploy:
resources:
limits:
cpus: '0.1'
memory: 600M

17
epmet-auth/deploy/docker-compose-test.yml

@ -0,0 +1,17 @@
version: "3.7"
services:
epmet-auth-server:
container_name: epmet-auth-server-test
image: registry-vpc.cn-qingdao.aliyuncs.com/epmet-cloud-release/epmet-auth:0.3.67
ports:
- "8081:8081"
network_mode: host # 使用现有网络
volumes:
- "/opt/epmet-cloud-logs/test:/logs"
environment:
RUN_INSTRUCT: "java -Xms32m -Xmx300m -jar ./app.jar"
deploy:
resources:
limits:
cpus: '0.1'
memory: 400M

148
epmet-auth/pom.xml

@ -2,7 +2,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<version>0.3.67</version>
<parent>
<groupId>com.epmet</groupId>
<artifactId>epmet-cloud</artifactId>
@ -57,6 +57,77 @@
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
<!-- 替换Feign原生httpclient -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>10.3.0</version>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>epmet-common-clienttoken</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>3.6.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>epmet-commons-tools-wx-ma</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>epmet-commons-tools-wx-mp</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>epmet-user-client</artifactId>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>epmet-message-client</artifactId>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>gov-org-client</artifactId>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>oper-access-client</artifactId>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.6.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>epmet-third-client</artifactId>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>oper-crm-client</artifactId>
<version>2.0.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
@ -94,17 +165,31 @@
<!-- redis配置 -->
<spring.redis.index>0</spring.redis.index>
<spring.redis.host>122.152.200.70</spring.redis.host>
<spring.redis.host>192.168.1.130</spring.redis.host>
<spring.redis.port>6379</spring.redis.port>
<spring.redis.password>123456</spring.redis.password>
<!-- nacos -->
<nacos.register-enabled>false</nacos.register-enabled>
<nacos.register-enabled>true</nacos.register-enabled>
<nacos.server-addr>122.152.200.70:8848</nacos.server-addr>
<nacos.discovery.namespace>fcd6fc8f-ca3a-4b01-8026-2b05cdc5976b</nacos.discovery.namespace>
<nacos.config.namespace></nacos.config.namespace>
<nacos.config.group></nacos.config.group>
<nacos.config-enabled>false</nacos.config-enabled>
<nacos.ip/>
<!--公众号配置-->
<wx.mp.configs.appId>wxcb6ce2ed0c5ae54c</wx.mp.configs.appId>
<wx.mp.configs.secret>c7f74941ee97fa9b2e1065772d34c397</wx.mp.configs.secret>
<wx.mp.configs.token>12345678Yzm</wx.mp.configs.token>
<wx.mp.configs.aesKey>jiKrJoPQsUIP9ayAwmuJQeAVPBjFOh5D1JxFDd7ZSU3</wx.mp.configs.aesKey>
<!--居民端小程序配置-->
<resi.wx.ma.appId>wx07674c23af51b521</resi.wx.ma.appId>
<resi.wx.ma.secret>a2fd0d29b007cbbcf8c8dda8c693d99b</resi.wx.ma.secret>
<!--政府端小程序配置-->
<gov.wx.ma.appId>wx3d1372029eb816a3</gov.wx.ma.appId>
<gov.wx.ma.secret>651f02d71ed3f123dfb584b8bf0f4d8b</gov.wx.ma.secret>
<!--<gov.wx.ma.appId>wx2679392c4cc2af22</gov.wx.ma.appId>
<gov.wx.ma.secret>e5e72147737cfeb2b0f3a43624cadb3f</gov.wx.ma.secret>-->
</properties>
</profile>
@ -119,17 +204,66 @@
<!-- redis配置 -->
<spring.redis.index>0</spring.redis.index>
<spring.redis.host>122.152.200.70</spring.redis.host>
<spring.redis.host>r-m5eoz5b6tkx09y6bpz.redis.rds.aliyuncs.com</spring.redis.host>
<spring.redis.port>6379</spring.redis.port>
<spring.redis.password>123456</spring.redis.password>
<spring.redis.password>EpmEtrEdIs!q@w</spring.redis.password>
<!-- nacos -->
<nacos.register-enabled>true</nacos.register-enabled>
<nacos.server-addr>122.152.200.70:8848</nacos.server-addr>
<nacos.discovery.namespace>fcd6fc8f-ca3a-4b01-8026-2b05cdc5976b</nacos.discovery.namespace>
<nacos.server-addr>192.168.10.150:8848</nacos.server-addr>
<nacos.discovery.namespace>67e3c350-533e-4d7c-9f8f-faf1b4aa82ae</nacos.discovery.namespace>
<nacos.config.namespace></nacos.config.namespace>
<nacos.config.group></nacos.config.group>
<nacos.config-enabled>false</nacos.config-enabled>
<nacos.ip/>
<!--公众号配置-->
<wx.mp.configs.appId>wxcb6ce2ed0c5ae54c</wx.mp.configs.appId>
<wx.mp.configs.secret>c7f74941ee97fa9b2e1065772d34c397</wx.mp.configs.secret>
<wx.mp.configs.token>12345678Yzm</wx.mp.configs.token>
<wx.mp.configs.aesKey>jiKrJoPQsUIP9ayAwmuJQeAVPBjFOh5D1JxFDd7ZSU3</wx.mp.configs.aesKey>
<!--居民端小程序配置-->
<resi.wx.ma.appId>wx07674c23af51b521</resi.wx.ma.appId>
<resi.wx.ma.secret>a2fd0d29b007cbbcf8c8dda8c693d99b</resi.wx.ma.secret>
<!--政府端小程序配置-->
<gov.wx.ma.appId>wx3d1372029eb816a3</gov.wx.ma.appId>
<gov.wx.ma.secret>651f02d71ed3f123dfb584b8bf0f4d8b</gov.wx.ma.secret>
</properties>
</profile>
<profile>
<id>prod</id>
<!--<activation>
<activeByDefault>true</activeByDefault>
</activation>-->
<properties>
<server.port>8081</server.port>
<spring.profiles.active>prod</spring.profiles.active>
<!-- redis配置 -->
<spring.redis.index>0</spring.redis.index>
<spring.redis.host>r-m5ez3n1j0qc3ykq2ut.redis.rds.aliyuncs.com</spring.redis.host>
<spring.redis.port>6379</spring.redis.port>
<spring.redis.password>EpmEtclOUdrEdIs!Q2w</spring.redis.password>
<!-- nacos -->
<nacos.register-enabled>true</nacos.register-enabled>
<nacos.server-addr>192.168.11.180:8848</nacos.server-addr>
<nacos.discovery.namespace>bd205d23-e696-47be-b995-916313f86e99</nacos.discovery.namespace>
<nacos.config.namespace></nacos.config.namespace>
<nacos.config.group></nacos.config.group>
<nacos.config-enabled>false</nacos.config-enabled>
<nacos.ip/>
<!--公众号配置-->
<wx.mp.configs.appId>wxcb6ce2ed0c5ae54c</wx.mp.configs.appId>
<wx.mp.configs.secret>c7f74941ee97fa9b2e1065772d34c397</wx.mp.configs.secret>
<wx.mp.configs.token>12345678Yzm</wx.mp.configs.token>
<wx.mp.configs.aesKey>jiKrJoPQsUIP9ayAwmuJQeAVPBjFOh5D1JxFDd7ZSU3</wx.mp.configs.aesKey>
<!--居民端小程序配置-->
<resi.wx.ma.appId>wx07674c23af51b521</resi.wx.ma.appId>
<resi.wx.ma.secret>a2fd0d29b007cbbcf8c8dda8c693d99b</resi.wx.ma.secret>
<!--政府端小程序配置-->
<gov.wx.ma.appId>wx3d1372029eb816a3</gov.wx.ma.appId>
<gov.wx.ma.secret>651f02d71ed3f123dfb584b8bf0f4d8b</gov.wx.ma.secret>
</properties>
</profile>
</profiles>

40
epmet-auth/src/main/java/com/epmet/aspect/RequestLogAspect.java

@ -0,0 +1,40 @@
package com.epmet.aspect;
import com.epmet.commons.tools.aspect.BaseRequestLogAspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 日志/异常处理切面实现调用父类方法完成日志记录和异常处理
*/
@Aspect
@Component
@Order(0)
public class RequestLogAspect extends BaseRequestLogAspect {
@Override
@Around(value = "execution(* com.epmet.controller.*Controller*.*(..)) ")
public Object proceed(ProceedingJoinPoint point) throws Throwable {
return super.proceed(point, getRequest());
}
/**
* 获取Request对象
*
* @return
*/
private HttpServletRequest getRequest() {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
return sra.getRequest();
}
}

24
epmet-auth/src/main/java/com/epmet/constant/AuthHttpUrlConstant.java

@ -0,0 +1,24 @@
package com.epmet.constant;
/**
* @Author zxc
* @CreateTime 2020/7/30 10:05
*/
public interface AuthHttpUrlConstant {
/**
* 注册url
*/
String REGISTER_URL = "https://epmet-cloud.elinkservice.cn/api/third/pacustomer/register";
/**
* 获取客户信息url
*/
String CUSTOMER_MSG_URL = "https://epmet-cloud.elinkservice.cn/api/third/customermp/getcustomermsg/";
/**
* 登录url
*/
String RESI_AND_WORK_LOGIN_URL = "https://epmet-cloud.elinkservice.cn/api/third/customermp/resiandworklogin";
}

22
epmet-auth/src/main/java/com/epmet/constant/PublicUserLoginConstant.java

@ -0,0 +1,22 @@
package com.epmet.constant;
/**
* @author sun
* @dscription
*/
public interface PublicUserLoginConstant {
/**
* 初始化用户信息失败
*/
String SAVE_USER_EXCEPTION = "初始化用户信息失败";
/**
* 是否登陆true false
*/
String PARAMETER_EXCEPTION = "是否登陆值错误";
/**
* 用户登陆 新增访问记录
*/
String SAVE_VISITED_EXCEPTION = "用户登陆,新增访问记录失败";
}

30
epmet-auth/src/main/java/com/epmet/constant/ThirdApiConstant.java

@ -0,0 +1,30 @@
package com.epmet.constant;
/**
* @author zhaoqifeng
* @dscription
* @date 2020/7/30 10:46
*/
public interface ThirdApiConstant {
/**
* 根据openId新增或更新用户信息
*/
String THIRD_PAUSER_SAVEUSER = "https://epmet-cloud.elinkservice.cn/api/third/pauser/saveuser";
/**
* 根据手机号查询公众号用户基本信息校验用户是否存在
*/
String THIRD_PAUSER_CHECKPAUSER = "https://epmet-cloud.elinkservice.cn/api/third/pauser/checkpauser";
/**
* 用户登陆新增访问记录数据
*/
String THIRD_PAUSERVISITED_SAVEUSERVISITED = "https://epmet-cloud.elinkservice.cn/api/third/pauservisited/saveuservisited";
/**
* 根据客户Id查询各项注册信息
*/
String THIRD_PACUSTOMER_GETCUSTOMERAGENCYUSER = "https://epmet-cloud.elinkservice.cn/api/third/pacustomer/getcustomeragencyuser/";
/**
* 修改客户数据状态为已完成初始化
*/
String THIRD_PACUSTOMER_UPDATECUSTOMER = "https://epmet-cloud.elinkservice.cn/api/third/pacustomer/updatecustomer/";
}

29
epmet-auth/src/main/java/com/epmet/controller/BackDoorController.java

@ -0,0 +1,29 @@
package com.epmet.controller;
import com.epmet.redis.CustomerAppWxServiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Set;
/**
* @author jianjun liu
* @date 2020-06-04 20:39
**/
@RestController
@RequestMapping("opback")
public class BackDoorController {
@Autowired
private CustomerAppWxServiceUtil customerAppWxServiceUtil;
/**
* 数据库添加新客户app后
*
* @return
*/
@RequestMapping("reloadcustomerapp")
public Set<String> initWxMaService() {
return customerAppWxServiceUtil.initWxMaService();
}
}

125
epmet-auth/src/main/java/com/epmet/controller/GovLoginController.java

@ -0,0 +1,125 @@
package com.epmet.controller;
import com.epmet.commons.tools.annotation.LoginUser;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.utils.Result;
import com.epmet.commons.tools.validator.ValidatorUtils;
import com.epmet.dto.form.*;
import com.epmet.dto.result.StaffOrgsResultDTO;
import com.epmet.dto.result.UserTokenResultDTO;
import com.epmet.service.GovLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Description 政府端登录
* @Author yinzuomei
* @Date 2020/4/20 10:54
*/
@RestController
@RequestMapping("gov")
public class GovLoginController {
@Autowired
private GovLoginService govLoginService;
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.result.UserTokenResultDTO>
* @Author yinzuomei
* @Description 1政府端小程序根据wxCode获取上一次登录信息返回token
* @Date 2020/4/20 11:22
**/
@PostMapping(value = "/loginwxmp/loginbywxcode")
public Result<UserTokenResultDTO> loginByWxCode(@RequestBody GovWxmpFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO,LoginCommonFormDTO.AddUserInternalGroup.class);
UserTokenResultDTO userTokenResultDTO=govLoginService.loginByWxCode(formDTO);
return new Result<UserTokenResultDTO>().ok(userTokenResultDTO);
}
/**
* @param formDTO 手机号
* @return com.epmet.commons.tools.utils.Result
* @Author yinzuomei
* @Description 2政府端微信小程序登录-发送验证码
* @Date 2020/4/18 10:58
**/
@PostMapping(value = "/loginwxmp/sendsmscode")
public Result sendSmsCode(@RequestBody SendSmsCodeFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO,SendSmsCodeFormDTO.AddUserShowGroup.class);
govLoginService.sendSmsCode(formDTO);
return new Result();
}
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.common.token.dto.result.UserTokenResultDTO>
* @Author yinzuomei
* @Description 3手机验证码获取组织
* @Date 2020/4/18 21:14
**/
@PostMapping(value = "/loginwxmp/getmyorg")
public Result<List<StaffOrgsResultDTO>> getmyorg(@RequestBody StaffOrgsFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO,StaffOrgsFormDTO.AddUserShowGroup.class, StaffOrgsFormDTO.GetMyOrgByLoginWxmp.class);
List<StaffOrgsResultDTO> staffOrgs=govLoginService.getMyOrg(formDTO);
return new Result<List<StaffOrgsResultDTO>>().ok(staffOrgs);
}
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.result.UserTokenResultDTO>
* @Author yinzuomei
* @Description 4选择组织进入首页
* @Date 2020/4/20 13:07
**/
@PostMapping(value = "/loginwxmp/enterorg")
public Result<UserTokenResultDTO> enterOrg(@RequestBody GovWxmpEnteOrgFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO,GovWxmpEnteOrgFormDTO.AddUserShowGroup.class,GovWxmpEnteOrgFormDTO.AddUserInternalGroup.class);
UserTokenResultDTO userTokenResultDTO=govLoginService.enterOrg(formDTO);
return new Result<UserTokenResultDTO>().ok(userTokenResultDTO);
}
/**
* @param tokenDto
* @return com.epmet.commons.tools.utils.Result
* @Author yinzuomei
* @Description 政府端小程序退出
* @Date 2020/4/21 22:22
**/
@PostMapping("/loginwxmp/loginout")
public Result loginOut(@LoginUser TokenDto tokenDto) {
govLoginService.loginOut(tokenDto);
return new Result();
}
/**
* 更新缓存的角色列表
* @param form
* @return
*/
@PostMapping("/updatecachedroles")
public Result updateCachedRoles(@RequestBody UpdateCachedRolesFormDTO form) {
ValidatorUtils.validateEntity(form);
govLoginService.updateCachedRoles(form.getStaffId(), form.getOrgId(), form.getRoleIds());
return new Result();
}
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<java.util.List < com.epmet.dto.result.StaffOrgsResultDTO>>
* @author yinzuomei
* @description 6手机号密码获取组织
* @Date 2020/6/30 22:43
**/
@PostMapping(value = "/getmyorgbypassword")
public Result<List<StaffOrgsResultDTO>> getMyOrgByPassword(@RequestBody StaffOrgsFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO, StaffOrgsFormDTO.AddUserShowGroup.class, StaffOrgsFormDTO.GetMyOrgByPassWordGroup.class);
List<StaffOrgsResultDTO> staffOrgs = govLoginService.getMyOrgByPassword(formDTO);
return new Result<List<StaffOrgsResultDTO>>().ok(staffOrgs);
}
}

117
epmet-auth/src/main/java/com/epmet/controller/LoginController.java

@ -0,0 +1,117 @@
package com.epmet.controller;
import com.epmet.commons.tools.annotation.LoginUser;
import com.epmet.commons.tools.exception.ErrorCode;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.utils.Result;
import com.epmet.commons.tools.validator.AssertUtils;
import com.epmet.commons.tools.validator.ValidatorUtils;
import com.epmet.dto.form.LoginByPassWordFormDTO;
import com.epmet.dto.form.LoginByWxCodeFormDTO;
import com.epmet.dto.form.ResiWxPhoneFormDTO;
import com.epmet.dto.result.UserTokenResultDTO;
import com.epmet.service.CaptchaService;
import com.epmet.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
/**
* @Description 通用登录接口
* @Author yinzuomei
* @Date 2020/3/14 13:58
*/
@RestController
@RequestMapping("login")
public class LoginController {
@Autowired
private CaptchaService captchaService;
@Autowired
private LoginService loginService;
/**
* @return void
* @param response
* @param uuid
* @Author yinzuomei
* @Description 运营端管理后台-生成验证码
* @Date 2020/3/17 16:08
**/
@GetMapping("captcha")
public void captcha(HttpServletResponse response, String uuid) throws IOException {
//uuid不能为空
AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL);
//生成图片验证码
BufferedImage image = captchaService.create(uuid);
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
out.close();
}
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<java.lang.String>
* @Author yinzuomei
* @Description 居民端微信小程序登录
* @Date 2020/3/14 14:35
**/
@PostMapping("/resiwxmp/loginbywxcode")
public Result<UserTokenResultDTO> loginByWxCode(@RequestBody LoginByWxCodeFormDTO formDTO) {
//效验数据
ValidatorUtils.validateEntity(formDTO);
return loginService.loginByWxCode(formDTO);
}
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.UserTokenResultDTO>
* @Author yinzuomei
* @Description 手机号+密码登录接口
* @Date 2020/3/14 19:46
**/
@PostMapping("/operweb/loginbypassword")
public Result<UserTokenResultDTO> loginByPassword(@RequestBody LoginByPassWordFormDTO formDTO) {
//效验数据
ValidatorUtils.validateEntity(formDTO);
Result<UserTokenResultDTO> result = loginService.loginByPassword(formDTO);
return result;
}
/**
* @param request
* @return com.epmet.commons.tools.utils.Result
* @Author yinzuomei
* @Description 退出登录
* @Date 2020/3/18 22:43
**/
@PostMapping(value = "logout")
public Result logout(@LoginUser TokenDto tokenDto, HttpServletRequest request) {
return loginService.logoutByToken(tokenDto);
}
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result
* @author yinzuomei
* @description 获取用户微信绑定的手机号
* @Date 2020/7/2 14:33
**/
@PostMapping("getresiwxphone")
public Result getResiWxPhone(@RequestBody ResiWxPhoneFormDTO formDTO) {
String phone = loginService.getResiWxPhone(formDTO);
if (StringUtils.isNotBlank(phone) && !"null".equals(phone)) {
return new Result().ok(phone);
}
return new Result().ok("");
}
}

95
epmet-auth/src/main/java/com/epmet/controller/PublicUserLoginController.java

@ -0,0 +1,95 @@
package com.epmet.controller;
import com.epmet.commons.tools.annotation.LoginUser;
import com.epmet.commons.tools.constant.Constant;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.utils.Result;
import com.epmet.commons.tools.validator.ValidatorUtils;
import com.epmet.constant.PublicUserLoginConstant;
import com.epmet.dto.form.LoginByPhoneFormDTO;
import com.epmet.dto.form.PaWxCodeFormDTO;
import com.epmet.dto.form.PublicSendSmsCodeFormDTO;
import com.epmet.dto.form.RegisterFormDTO;
import com.epmet.dto.result.UserTokenResultDTO;
import com.epmet.service.PublicUserLoginService;
import com.netflix.ribbon.proxy.annotation.Http;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.*;
/**
* 描述一下
*
* @author yinzuomei@elink-cn.com
* @date 2020/7/8 18:29
*/
@RestController
@RequestMapping("publicuser")
public class PublicUserLoginController {
@Autowired
private PublicUserLoginService publicUserLoginService;
/**
* @return com.epmet.commons.tools.utils.Result
* @param formDTO
* @author sun
* @description 解析wxcode获取用户信息并生成token
**/
@PostMapping(value = "/wxcodetotoken")
public Result<UserTokenResultDTO> wxCodeToToken(@RequestHeader("source") String source, @RequestBody PaWxCodeFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO, PaWxCodeFormDTO.AddUserInternalGroup.class);
formDTO.setSource(source);
return new Result<UserTokenResultDTO>().ok(publicUserLoginService.wxCodeToToken(formDTO));
}
/**
* @param formDTO 手机号
* @return com.epmet.commons.tools.utils.Result
* @Author sun
* @Description 公众号登录-发送验证码
**/
@PostMapping(value = "/sendsmscode")
public Result sendSmsCode(@RequestHeader("source") String source, @RequestBody PublicSendSmsCodeFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO,PublicSendSmsCodeFormDTO.AddUserShowGroup.class);
if (formDTO.getIsLogon() != true && formDTO.getIsLogon() != false) {
throw new RenException(PublicUserLoginConstant.PARAMETER_EXCEPTION);
}
formDTO.setSource(source);
publicUserLoginService.sendSmsCode(formDTO);
return new Result();
}
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result
* @Author sun
* @Description 公众号-手机验证码登陆
**/
@PostMapping(value = "/loginbyphone")
public Result<UserTokenResultDTO> loginByPhone(@RequestHeader("source") String source, @LoginUser TokenDto tokenDTO, @RequestBody LoginByPhoneFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO, LoginByPhoneFormDTO.AddUserShowGroup.class, LoginByPhoneFormDTO.LoginByPhone.class);
formDTO.setSource(source);
return new Result<UserTokenResultDTO>().ok(publicUserLoginService.loginByPhone(tokenDTO, formDTO));
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 公众号-手机号注册
**/
@PostMapping(value = "/register")
public Result<UserTokenResultDTO> register(@RequestHeader("source") String source, @LoginUser TokenDto tokenDTO, @RequestBody RegisterFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO, RegisterFormDTO.AddUserInternalGroup.class, RegisterFormDTO.AddUserShowGroup.class);
formDTO.setUserId(tokenDTO.getUserId());
formDTO.setSource(source);
return new Result<UserTokenResultDTO>().ok(publicUserLoginService.register(formDTO));
}
}

94
epmet-auth/src/main/java/com/epmet/controller/ThirdLoginController.java

@ -0,0 +1,94 @@
package com.epmet.controller;
import com.epmet.commons.tools.utils.Result;
import com.epmet.commons.tools.validator.ValidatorUtils;
import com.epmet.dto.form.LoginFormDTO;
import com.epmet.dto.form.StaffOrgsFormDTO;
import com.epmet.dto.form.ThirdStaffOrgsFormDTO;
import com.epmet.dto.form.ThirdWxmpEnteOrgFormDTO;
import com.epmet.dto.result.StaffOrgsResultDTO;
import com.epmet.dto.result.UserTokenResultDTO;
import com.epmet.service.ThirdLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Description 第三方-居民端政府端登陆服务
* @author sun
*/
@RestController
@RequestMapping("thirdlogin")
public class ThirdLoginController {
@Autowired
private ThirdLoginService thirdLoginService;
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-居民端微信小程序登录
**/
@PostMapping("resilogin")
public Result<UserTokenResultDTO> resiLogin(@RequestBody LoginFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO);
return new Result<UserTokenResultDTO>().ok(thirdLoginService.resiLogin(formDTO));
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-政府端微信小程序登录
**/
@PostMapping("worklogin")
public Result<UserTokenResultDTO> workLogin(@RequestBody LoginFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO);
return new Result<UserTokenResultDTO>().ok(thirdLoginService.workLogin(formDTO));
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-选择组织进入首页
**/
@PostMapping(value = "enterorg")
public Result<UserTokenResultDTO> enterOrg(@RequestBody ThirdWxmpEnteOrgFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO,ThirdWxmpEnteOrgFormDTO.AddUserShowGroup.class,ThirdWxmpEnteOrgFormDTO.AddUserInternalGroup.class);
UserTokenResultDTO userTokenResultDTO=thirdLoginService.enterOrg(formDTO);
return new Result<UserTokenResultDTO>().ok(userTokenResultDTO);
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-手机验证码获取组织
**/
@PostMapping(value = "/getmyorg")
public Result<List<StaffOrgsResultDTO>> getmyorg(@RequestBody ThirdStaffOrgsFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO, StaffOrgsFormDTO.AddUserShowGroup.class, StaffOrgsFormDTO.GetMyOrgByLoginWxmp.class);
List<StaffOrgsResultDTO> staffOrgs = thirdLoginService.getMyOrg(formDTO);
return new Result<List<StaffOrgsResultDTO>>().ok(staffOrgs);
}
/**
* @param formDTO
* @return
* @author sun
* @description 单客户-手机号密码获取组织
**/
@PostMapping(value = "/getmyorgbypassword")
public Result<List<StaffOrgsResultDTO>> getMyOrgByPassword(@RequestBody ThirdStaffOrgsFormDTO formDTO) {
ValidatorUtils.validateEntity(formDTO, StaffOrgsFormDTO.AddUserShowGroup.class, StaffOrgsFormDTO.GetMyOrgByPassWordGroup.class);
List<StaffOrgsResultDTO> staffOrgs = thirdLoginService.getMyOrgByPassword(formDTO);
return new Result<List<StaffOrgsResultDTO>>().ok(staffOrgs);
}
}

48
epmet-auth/src/main/java/com/epmet/dto/form/GovWxmpEnteOrgFormDTO.java

@ -0,0 +1,48 @@
package com.epmet.dto.form;
import com.epmet.commons.tools.validator.group.CustomerClientShowGroup;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 选择组织进入首页入参Dto
* @Author yinzuomei
* @Date 2020/4/20 13:03
*/
@Data
public class GovWxmpEnteOrgFormDTO implements Serializable {
public interface AddUserInternalGroup {}
public interface AddUserShowGroup extends CustomerClientShowGroup {}
/**
* wxCode
*/
@NotBlank(message = "wxCode不能为空",groups = {AddUserInternalGroup.class})
private String wxCode;
/**
* 手机号
*/
@NotBlank(message = "手机号不能为空",groups = {AddUserShowGroup.class})
private String mobile;
/**
* 选择的组织所属的id
*/
@NotBlank(message = "客户id不能为空",groups = {AddUserInternalGroup.class})
private String customerId;
/**
* 选择的要进入的组织(根组织id)
*/
@NotBlank(message = "组织id不能为空",groups = {AddUserInternalGroup.class})
private String rootAgencyId;
/**
* desc:小程序appId
*/
private String appId;
}

27
epmet-auth/src/main/java/com/epmet/dto/form/GovWxmpFormDTO.java

@ -0,0 +1,27 @@
package com.epmet.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 政府端小程序根据wxCode获取上一次登录信息返回token
* @Author yinzuomei
* @Date 2020/4/20 11:20
*/
@Data
public class GovWxmpFormDTO extends LoginCommonFormDTO implements Serializable {
private static final long serialVersionUID = -207861963128774742L;
/**
* wxCode
*/
@NotBlank(message = "wxCode不能为空",groups = {AddUserInternalGroup.class})
private String wxCode;
/**
* appId
*/
private String appId;
}

40
epmet-auth/src/main/java/com/epmet/dto/form/LoginByPassWordFormDTO.java

@ -0,0 +1,40 @@
package com.epmet.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 手机号+密码登录接口入参
* @Author yinzuomei
* @Date 2020/3/14 19:46
*/
@Data
public class LoginByPassWordFormDTO extends LoginCommonFormDTO implements Serializable {
private static final long serialVersionUID = -7507437651048051183L;
/**
* 手机号
*/
@NotBlank(message = "手机号不能为空",groups = {AddUserShowGroup.class})
private String phone;
/**
* 密码
*/
@NotBlank(message = "密码不能为空",groups = {AddUserShowGroup.class})
private String password;
/**
* 验证码
*/
@NotBlank(message="验证码不能为空",groups = {AddUserShowGroup.class})
private String captcha;
/**
* 唯一标识
*/
@NotBlank(message="唯一标识不能为空",groups = {AddUserInternalGroup.class})
private String uuid;
}

43
epmet-auth/src/main/java/com/epmet/dto/form/LoginByPhoneFormDTO.java

@ -0,0 +1,43 @@
package com.epmet.dto.form;
import com.epmet.commons.tools.validator.group.CustomerClientShowGroup;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 手机验证码登陆接口入参
* @Author sun
*/
@Data
public class LoginByPhoneFormDTO implements Serializable {
private static final long serialVersionUID = 4193133227120225342L;
/**
* 添加用户操作的用户可见异常分组
* 该分组用于校验需要返回给前端错误信息提示的列需要继承CustomerClientShowGroup
* 返回错误码为8999提示信息为DTO中具体的列的校验注解message的内容
*/
public interface AddUserShowGroup extends CustomerClientShowGroup {
}
public interface LoginByPhone extends CustomerClientShowGroup{}
/**
* 手机号
*/
@NotBlank(message = "手机号不能为空", groups = {AddUserShowGroup.class})
private String phone;
/**
* 验证码
*/
@NotBlank(message="验证码不能为空", groups = {LoginByPhone.class})
private String smsCode;
/**
* 数据来源(dev:开发 test:体验 prod:生产)
*/
private String source;
}

34
epmet-auth/src/main/java/com/epmet/dto/form/LoginByWxCodeFormDTO.java

@ -0,0 +1,34 @@
package com.epmet.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 微信小程序登录接口入参
* @Author yinzuomei
* @Date 2020/3/14 14:39
*/
@Data
public class LoginByWxCodeFormDTO extends LoginCommonFormDTO implements Serializable {
private static final long serialVersionUID = 7950477424010655108L;
/**
* 微信code
*/
@NotBlank(message = "wxCode不能为空",groups = {AddUserInternalGroup.class})
private String wxCode;
/**
* 用户信息
*/
private String encryptedData;
/**
* 加密算法的初始向量
*/
private String iv;
private String appId;
}

30
epmet-auth/src/main/java/com/epmet/dto/form/LoginCommonFormDTO.java

@ -0,0 +1,30 @@
package com.epmet.dto.form;
import com.epmet.commons.tools.validator.group.CustomerClientShowGroup;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 登录接口通用入参
* @Author yinzuomei
* @Date 2020/3/14 19:47
*/
@Data
public class LoginCommonFormDTO implements Serializable {
private static final long serialVersionUID = -5582224784914714820L;
public interface AddUserInternalGroup {}
public interface AddUserShowGroup extends CustomerClientShowGroup {}
/**
* 政府端:gov居民端:resi运营端:oper
*/
@NotBlank(message = "app不能为空(政府端:gov、居民端:resi、运营端:oper)",groups ={AddUserInternalGroup.class} )
private String app;
/**
* PC端:web微信小程序:wxmp
*/
@NotBlank(message = "client不能为空(PC端:web、微信小程序:wxmp)",groups ={AddUserInternalGroup.class})
private String client;
}

28
epmet-auth/src/main/java/com/epmet/dto/form/LoginFormDTO.java

@ -0,0 +1,28 @@
package com.epmet.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 单客户-居民端微信小程序登录
* @Author sun
*/
@Data
public class LoginFormDTO extends LoginCommonFormDTO implements Serializable {
private static final long serialVersionUID = 7950477424010655108L;
/**
* 小程序appId
*/
@NotBlank(message = "appId不能为空",groups = {AddUserInternalGroup.class})
private String appId;
/**
* 用户微信code
*/
@NotBlank(message = "wxCode不能为空",groups = {AddUserInternalGroup.class})
private String wxCode;
}

27
epmet-auth/src/main/java/com/epmet/dto/form/PaWxCodeFormDTO.java

@ -0,0 +1,27 @@
package com.epmet.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* 描述一下
*
* @author yinzuomei@elink-cn.com
* @date 2020/7/8 18:32
*/
@Data
public class PaWxCodeFormDTO implements Serializable {
private static final long serialVersionUID = -207861963128774742L;
public interface AddUserInternalGroup {}
/**
* wxCode
*/
@NotBlank(message = "wxCode不能为空",groups = {AddUserInternalGroup.class})
private String wxCode;
/**
* 数据来源(dev:开发 test:体验 prod:生产)
*/
private String source;
}

39
epmet-auth/src/main/java/com/epmet/dto/form/PublicSendSmsCodeFormDTO.java

@ -0,0 +1,39 @@
package com.epmet.dto.form;
import com.epmet.commons.tools.validator.group.CustomerClientShowGroup;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 公众号手机号+验证码登录接口入参
* @Author sun
*/
@Data
public class PublicSendSmsCodeFormDTO implements Serializable {
private static final long serialVersionUID = -1852541457359282018L;
/**
* 添加用户操作的用户可见异常分组
* 该分组用于校验需要返回给前端错误信息提示的列需要继承CustomerClientShowGroup
* 返回错误码为8999提示信息为DTO中具体的列的校验注解message的内容
*/
public interface AddUserShowGroup extends CustomerClientShowGroup {
}
/**
* 手机号
*/
@NotBlank(message = "手机号不能为空", groups = {AddUserShowGroup.class})
private String phone;
/**
* 是否登陆登陆true 注册false
*/
private Boolean isLogon;
/**
* 数据来源(dev:开发 test:体验 prod:生产)
*/
private String source;
}

37
epmet-auth/src/main/java/com/epmet/dto/form/ResiWxPhoneFormDTO.java

@ -0,0 +1,37 @@
package com.epmet.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* 描述一下
*
* @author yinzuomei@elink-cn.com
* @date 2020/7/2 14:28
*/
@Data
public class ResiWxPhoneFormDTO implements Serializable {
private static final long serialVersionUID = 4381236451736209332L;
public interface AddUserInternalGroup {}
/**
* 微信code
*/
@NotBlank(message = "wxCode不能为空",groups = {AddUserInternalGroup.class})
private String wxCode;
/**
* 用户信息
*/
@NotBlank(message = "encryptedData不能为空",groups = {AddUserInternalGroup.class})
private String encryptedData;
/**
* 加密算法的初始向量
*/
@NotBlank(message = "iv不能为空",groups = {AddUserInternalGroup.class})
private String iv;
private String appId;
}

26
epmet-auth/src/main/java/com/epmet/dto/form/SendSmsCodeFormDTO.java

@ -0,0 +1,26 @@
package com.epmet.dto.form;
import com.epmet.commons.tools.validator.group.CustomerClientShowGroup;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 政府端手机号+验证码登录接口入参
* @Author yinzuomei
* @Date 2020/04/18 10:26
*/
@Data
public class SendSmsCodeFormDTO implements Serializable {
private static final long serialVersionUID = -1852541457359282018L;
/**
* 添加用户操作的用户可见异常分组
* 该分组用于校验需要返回给前端错误信息提示的列需要继承CustomerClientShowGroup
* 返回错误码为8999提示信息为DTO中具体的列的校验注解message的内容
*/
public interface AddUserShowGroup extends CustomerClientShowGroup {
}
@NotBlank(message = "手机号不能为空", groups = {AddUserShowGroup.class})
private String mobile;
}

43
epmet-auth/src/main/java/com/epmet/dto/form/StaffOrgsFormDTO.java

@ -0,0 +1,43 @@
package com.epmet.dto.form;
import com.epmet.commons.tools.validator.group.CustomerClientShowGroup;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 手机验证码获取组织接口入参
* @Author yinzuomei
* @Date 2020/4/18 10:38
*/
@Data
public class StaffOrgsFormDTO implements Serializable {
private static final long serialVersionUID = 4193133227120225342L;
/**
* 添加用户操作的用户可见异常分组
* 该分组用于校验需要返回给前端错误信息提示的列需要继承CustomerClientShowGroup
* 返回错误码为8999提示信息为DTO中具体的列的校验注解message的内容
*/
public interface AddUserShowGroup extends CustomerClientShowGroup {
}
public interface GetMyOrgByPassWordGroup extends CustomerClientShowGroup {
}
public interface GetMyOrgByLoginWxmp extends CustomerClientShowGroup{}
/**
* 手机号
*/
@NotBlank(message = "手机号不能为空", groups = {AddUserShowGroup.class})
private String mobile;
/**
* 验证码
*/
@NotBlank(message="验证码不能为空", groups = {GetMyOrgByLoginWxmp.class})
private String smsCode;
@NotBlank(message = "密码不能为空",groups ={GetMyOrgByPassWordGroup.class})
private String password;
}

48
epmet-auth/src/main/java/com/epmet/dto/form/ThirdStaffOrgsFormDTO.java

@ -0,0 +1,48 @@
package com.epmet.dto.form;
import com.epmet.commons.tools.validator.group.CustomerClientShowGroup;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description appId手机号验证码获取组织-接口入参
* @Author sun
*/
@Data
public class ThirdStaffOrgsFormDTO implements Serializable {
private static final long serialVersionUID = 4193133227120225342L;
/**
* 添加用户操作的用户可见异常分组
* 该分组用于校验需要返回给前端错误信息提示的列需要继承CustomerClientShowGroup
* 返回错误码为8999提示信息为DTO中具体的列的校验注解message的内容
*/
public interface AddUserShowGroup extends CustomerClientShowGroup {
}
public interface GetMyOrgByPassWordGroup extends CustomerClientShowGroup {
}
public interface GetMyOrgByLoginWxmp extends CustomerClientShowGroup{}
/**
* 小程序appId
*/
@NotBlank(message = "appId不能为空", groups = {AddUserShowGroup.class})
private String appId;
/**
* 手机号
*/
@NotBlank(message = "手机号不能为空", groups = {AddUserShowGroup.class})
private String mobile;
/**
* 验证码
*/
@NotBlank(message="验证码不能为空", groups = {GetMyOrgByLoginWxmp.class})
private String smsCode;
@NotBlank(message = "密码不能为空",groups ={GetMyOrgByPassWordGroup.class})
private String password;
}

47
epmet-auth/src/main/java/com/epmet/dto/form/ThirdWxmpEnteOrgFormDTO.java

@ -0,0 +1,47 @@
package com.epmet.dto.form;
import com.epmet.commons.tools.validator.group.CustomerClientShowGroup;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
* @Description 单客户-选择组织进入首页入参Dto
* @Author sun
*/
@Data
public class ThirdWxmpEnteOrgFormDTO implements Serializable {
public interface AddUserInternalGroup {}
public interface AddUserShowGroup extends CustomerClientShowGroup {}
/**
* wxCode
*/
@NotBlank(message = "wxCode不能为空",groups = {AddUserInternalGroup.class})
private String wxCode;
/**
* 手机号
*/
@NotBlank(message = "手机号不能为空",groups = {AddUserShowGroup.class})
private String mobile;
/**
* 选择的组织所属的id
*/
@NotBlank(message = "客户id不能为空",groups = {AddUserInternalGroup.class})
private String customerId;
/**
* 选择的要进入的组织(根组织id)
*/
@NotBlank(message = "组织id不能为空",groups = {AddUserInternalGroup.class})
private String rootAgencyId;
/**
* 客户appIdexJson文件中获取
*/
@NotBlank(message = "appId不能为空",groups = {AddUserInternalGroup.class})
private String appId;
}

19
epmet-auth/src/main/java/com/epmet/dto/form/UpdateCachedRolesFormDTO.java

@ -0,0 +1,19 @@
package com.epmet.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.util.List;
@Data
public class UpdateCachedRolesFormDTO {
@NotBlank(message = "客户ID不能为空")
private String staffId;
@NotBlank(message = "机关ID不能为空")
private String orgId;
private List<String> roleIds;
}

20
epmet-auth/src/main/java/com/epmet/dto/result/UserTokenResultDTO.java

@ -0,0 +1,20 @@
package com.epmet.dto.result;
import lombok.Data;
import java.io.Serializable;
/**
* @Description 登录接口返参DTO
* @Author yinzuomei
* @Date 2020/3/14 15:10
*/
@Data
public class UserTokenResultDTO implements Serializable {
private static final long serialVersionUID = 5214475907074876716L;
/**
* 令牌
*/
private String token;
}

118
epmet-auth/src/main/java/com/epmet/feign/EpmetUserFeignClient.java

@ -0,0 +1,118 @@
package com.epmet.feign;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.CustomerStaffDTO;
import com.epmet.dto.GovStaffRoleDTO;
import com.epmet.dto.UserDTO;
import com.epmet.dto.UserWechatDTO;
import com.epmet.dto.form.*;
import com.epmet.dto.result.PasswordLoginUserInfoResultDTO;
import com.epmet.dto.result.StaffLatestAgencyResultDTO;
import com.epmet.feign.fallback.EpmetUserFeignClientFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
/**
* @Description
* @Author yinzuomei
* @Date 2020/3/16 14:48
*/
@FeignClient(name = ServiceConstant.EPMET_USER_SERVER, fallback = EpmetUserFeignClientFallback.class)
public interface EpmetUserFeignClient {
/**
* 获取用户信息
*
* @param loginUserInfoFormDTO
* @return java.lang.String
* @author yinzuomei
* @date 2020/3/16 14:48
*/
@PostMapping(value = "epmetuser/user/selecWxLoginUserInfo", consumes = MediaType.APPLICATION_JSON_VALUE)
Result<UserDTO> selecWxLoginUserInfo(@RequestBody WxLoginUserInfoFormDTO loginUserInfoFormDTO);
/**
* 获取居民微信信息保存到user_wechat表,返回主键
*
* @param userWechatDTO
* @return java.lang.String
* @author yinzuomei
* @date 2020/3/16 14:48
*/
@PostMapping(value = "epmetuser/user/saveOrUpdateUserWechatDTO", consumes = MediaType.APPLICATION_JSON_VALUE)
Result<UserDTO> saveOrUpdateUserWechatDTO(@RequestBody UserWechatDTO userWechatDTO);
/**
* @param passwordLoginUserInfoFormDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.result.PasswordLoginUserInfoResultDTO>
* @Author yinzuomei
* @Description 根据手机号查询用户信息
* @Date 2020/3/16 16:14
**/
@PostMapping(value = "epmetuser/user/selectLoginUserInfoByPassword", consumes = MediaType.APPLICATION_JSON_VALUE)
Result<PasswordLoginUserInfoResultDTO> selectLoginUserInfoByPassword(@RequestBody PasswordLoginUserInfoFormDTO passwordLoginUserInfoFormDTO);
/**
* @param mobile
* @return com.epmet.commons.tools.utils.Result
* @Author yinzuomei
* @Description 根据手机号查询政府端工作人员基本信息校验用户是否存在
* @Date 2020/4/18 14:03
**/
@GetMapping(value = "epmetuser/customerstaff/getcustsomerstaffbyphone/{mobile}")
Result<List<CustomerStaffDTO>> checkCustomerStaff(@PathVariable("mobile") String mobile);
/**
* @param staffWechatFormDTO
* @return com.epmet.commons.tools.utils.Result
* @Author yinzuomei
* @Description 机验证码登录时记录微信openId与当前用户的关系
* @Date 2020/4/18 22:44
**/
@PostMapping(value = "epmetuser/staffwechat/savestaffwechat", consumes = MediaType.APPLICATION_JSON_VALUE)
Result saveStaffWechat(@RequestBody StaffWechatFormDTO staffWechatFormDTO);
/**
* @param openId
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.result.LatestStaffWechatLoginDTO>
* @Author yinzuomei
* @Description 获取当前微信上次登录的账号信息
* @Date 2020/4/20 12:53
**/
@GetMapping(value = "epmetuser/staffagencyvisited/getlatest/{openId}")
Result<StaffLatestAgencyResultDTO> getLatestStaffWechatLoginRecord(@PathVariable("openId") String openId);
/**
* @param customerStaffFormDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.CustomerStaffDTO>
* @Author yinzuomei
* @Description 根据手机号+客户id获取工作人员基本信息
* @Date 2020/4/20 14:16
**/
@PostMapping(value = "epmetuser/customerstaff/getcustomerstaffinfo", consumes = MediaType.APPLICATION_JSON_VALUE)
Result<CustomerStaffDTO> getCustomerStaffInfo(@RequestBody CustomerStaffFormDTO customerStaffFormDTO);
/**
* @param staffLoginHistoryFormDTO
* @return com.epmet.commons.tools.utils.Result
* @Author yinzuomei
* @Description 保存登录日志
* @Date 2020/4/20 14:38
**/
@PostMapping(value = "epmetuser/staffagencyvisited/saveStaffLoginRecord", consumes = MediaType.APPLICATION_JSON_VALUE)
Result saveStaffLoginRecord(StaffLoginAgencyRecordFormDTO staffLoginHistoryFormDTO);
/**
* 查询工作人员的角色
* @return
*/
@PostMapping("/epmetuser/staffrole/staffroles")
Result<List<GovStaffRoleDTO>> getRolesOfStaff(StaffRoleFormDTO staffRoleFormDTO);
}

58
epmet-auth/src/main/java/com/epmet/feign/GovOrgFeignClient.java

@ -0,0 +1,58 @@
package com.epmet.feign;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.CustomerAgencyDTO;
import com.epmet.dto.form.StaffOrgFormDTO;
import com.epmet.dto.result.DepartmentListResultDTO;
import com.epmet.dto.result.GridByStaffResultDTO;
import com.epmet.dto.result.StaffOrgsResultDTO;
import com.epmet.feign.fallback.GovOrgFeignClientFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;
/**
* @Description 政府端组织机构模块
* @Author yinzuomei
* @Date 2020/4/20 15:18
*/
@FeignClient(name = ServiceConstant.GOV_ORG_SERVER, fallback = GovOrgFeignClientFallback.class)
public interface GovOrgFeignClient {
/**
* @return com.epmet.commons.tools.utils.Result<java.util.List<com.epmet.dto.result.StaffOrgsResultDTO>>
* @param staffOrgFormDTO
* @Author yinzuomei
* @Description 获取客户对应的根级组织名称
* @Date 2020/4/20 21:37
**/
@PostMapping(value = "/gov/org/customeragency/getStaffOrgList",consumes = MediaType.APPLICATION_JSON_VALUE)
Result<List<StaffOrgsResultDTO>> getStaffOrgList(StaffOrgFormDTO staffOrgFormDTO);
/**
* 查询人员部门列表
* @param staffId
* @return
*/
@PostMapping("/gov/org/department/staff/{staffId}/departmentlist")
Result<List<DepartmentListResultDTO>> getDepartmentListByStaffId(@PathVariable("staffId") String staffId);
/**
* 查询工作人员所有的网格
* @param staffId
* @return
*/
@PostMapping("/gov/org/grid/gridsbystaffid/{staffId}")
Result<List<GridByStaffResultDTO>> listGridsbystaffid(@PathVariable("staffId") String staffId);
/**
* 根据staffId查询所属的组织机构
* @param staffId
* @return
*/
@PostMapping("/gov/org/agency/agencybystaff/{staffId}")
Result<CustomerAgencyDTO> getAgencyByStaff(@PathVariable("staffId") String staffId);
}

71
epmet-auth/src/main/java/com/epmet/feign/fallback/EpmetUserFeignClientFallback.java

@ -0,0 +1,71 @@
package com.epmet.feign.fallback;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.utils.ModuleUtils;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.CustomerStaffDTO;
import com.epmet.dto.GovStaffRoleDTO;
import com.epmet.dto.UserDTO;
import com.epmet.dto.UserWechatDTO;
import com.epmet.dto.form.*;
import com.epmet.dto.result.PasswordLoginUserInfoResultDTO;
import com.epmet.dto.result.StaffLatestAgencyResultDTO;
import com.epmet.feign.EpmetUserFeignClient;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @Description
* @Author yinzuomei
* @Date 2020/3/16 14:53
*/
@Component
public class EpmetUserFeignClientFallback implements EpmetUserFeignClient {
@Override
public Result<UserDTO> selecWxLoginUserInfo(WxLoginUserInfoFormDTO loginUserInfoFormDTO) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_USER_SERVER, "selecWxLoginUserInfo", loginUserInfoFormDTO);
}
@Override
public Result<UserDTO> saveOrUpdateUserWechatDTO(UserWechatDTO userWechatDTO) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_USER_SERVER, "saveOrUpdateUserWechatDTO", userWechatDTO);
}
@Override
public Result<PasswordLoginUserInfoResultDTO> selectLoginUserInfoByPassword(PasswordLoginUserInfoFormDTO passwordLoginUserInfoFormDTO) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_USER_SERVER, "selectLoginUserInfoByPassword", passwordLoginUserInfoFormDTO);
}
@Override
public Result<List<CustomerStaffDTO>> checkCustomerStaff(String phone) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_USER_SERVER, "getCustsomerStaffByPhone", phone);
}
@Override
public Result saveStaffWechat(StaffWechatFormDTO staffWechatFormDTO) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_USER_SERVER, "saveStaffWechat", staffWechatFormDTO);
}
@Override
public Result<StaffLatestAgencyResultDTO> getLatestStaffWechatLoginRecord(String openId) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_USER_SERVER, "getLatestStaffWechatLoginRecord", openId);
}
@Override
public Result<CustomerStaffDTO> getCustomerStaffInfo(CustomerStaffFormDTO customerStaffFormDTO) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_USER_SERVER, "getCustomerStaffInfo", customerStaffFormDTO);
}
@Override
public Result saveStaffLoginRecord(StaffLoginAgencyRecordFormDTO staffLoginHistoryFormDTO) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_USER_SERVER, "saveStaffLoginRecord", staffLoginHistoryFormDTO);
}
@Override
public Result<List<GovStaffRoleDTO>> getRolesOfStaff(StaffRoleFormDTO staffRoleFormDTO) {
return ModuleUtils.feignConError(ServiceConstant.EPMET_USER_SERVER, "getRolesOfStaff", staffRoleFormDTO);
}
}

44
epmet-auth/src/main/java/com/epmet/feign/fallback/GovOrgFeignClientFallback.java

@ -0,0 +1,44 @@
package com.epmet.feign.fallback;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.utils.ModuleUtils;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.CustomerAgencyDTO;
import com.epmet.dto.form.StaffOrgFormDTO;
import com.epmet.dto.result.DepartmentListResultDTO;
import com.epmet.dto.result.GridByStaffResultDTO;
import com.epmet.dto.result.StaffOrgsResultDTO;
import com.epmet.feign.GovOrgFeignClient;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @Description 政府端组织机构模块
* @Author yinzuomei
* @Date 2020/4/20 15:19
*/
@Component
public class GovOrgFeignClientFallback implements GovOrgFeignClient {
@Override
public Result<List<StaffOrgsResultDTO>> getStaffOrgList(StaffOrgFormDTO staffOrgFormDTO) {
return ModuleUtils.feignConError(ServiceConstant.GOV_ORG_SERVER, "getStaffOrgList", staffOrgFormDTO);
}
@Override
public Result<List<DepartmentListResultDTO>> getDepartmentListByStaffId(String staffId) {
return ModuleUtils.feignConError(ServiceConstant.GOV_ORG_SERVER, "getDepartmentListByStaffId", staffId);
}
@Override
public Result<List<GridByStaffResultDTO>> listGridsbystaffid(String staffId) {
return ModuleUtils.feignConError(ServiceConstant.GOV_ORG_SERVER, "listGridsbystaffid", staffId);
}
@Override
public Result<CustomerAgencyDTO> getAgencyByStaff(String staffId) {
return ModuleUtils.feignConError(ServiceConstant.GOV_ORG_SERVER, "getAgencyByStaff", staffId);
}
}

41
epmet-auth/src/main/java/com/epmet/jwt/JwtTokenProperties.java

@ -0,0 +1,41 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有侵权必究
*/
package com.epmet.jwt;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* Jwt
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Configuration
@ConfigurationProperties(prefix = "jwt.token")
public class JwtTokenProperties {
private String secret;
private int expire;
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public int getExpire() {
return expire;
}
public void setExpire(int expire) {
this.expire = expire;
}
}

132
epmet-auth/src/main/java/com/epmet/jwt/JwtTokenUtils.java

@ -0,0 +1,132 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有侵权必究
*/
package com.epmet.jwt;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Jwt工具类
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Component
public class JwtTokenUtils {
private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);
@Autowired
private JwtTokenProperties jwtProperties;
/**
* 生成jwt token 弃用
*/
@Deprecated
public String generateToken(String userId) {
return Jwts.builder()
.setHeaderParam("typ", "JWT")
.setSubject(userId)
.setIssuedAt(new Date())
.setExpiration(DateTime.now().plusSeconds(jwtProperties.getExpire()).toDate())
.signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret())
.compact();
}
public Claims getClaimByToken(String token) {
try {
return Jwts.parser()
.setSigningKey(jwtProperties.getSecret())
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
logger.debug("validate is token error, token = " + token, e);
return null;
}
}
/**
* @return java.util.Date
* @param token
* @Author yinzuomei
* @Description 获取token的有效期截止时间
* @Date 2020/3/18 22:17
**/
public Date getExpiration(String token){
try {
return Jwts.parser()
.setSigningKey(jwtProperties.getSecret())
.parseClaimsJws(token)
.getBody().getExpiration();
} catch (Exception e) {
logger.debug("validate is token error, token = " + token, e);
return null;
}
}
/**
* @param map
* @return java.lang.String
* @Author yinzuomei
* @Description 根据app+client+userId生成token
* @Date 2020/3/18 22:29
**/
public String createToken(Map<String, Object> map) {
return Jwts.builder()
.setHeaderParam("typ", "JWT")
.setClaims(map)
.setIssuedAt(new Date())
.setExpiration(DateTime.now().plusSeconds(jwtProperties.getExpire()).toDate())
.signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret())
.compact();
}
/**
* token是否过期
*
* @return true过期
*/
public boolean isTokenExpired(Date expiration) {
return expiration.before(new Date());
}
public static void main(String[] args) {
Map<String, Object> map=new HashMap<>();
map.put("app","gov");
map.put("client","wxmp");
map.put("userId","100526ABC");
String tokenStr=Jwts.builder()
.setHeaderParam("typ", "JWT")
.setClaims(map)
.setIssuedAt(new Date())
.setExpiration(DateTime.now().plusSeconds(604800).toDate())
.signWith(SignatureAlgorithm.HS512, "7016867071f0ebf1c46f123eaaf4b9d6[elink.epmet]")
.compact();
System.out.println(tokenStr);
Claims claims= Jwts.parser()
.setSigningKey("7016867071f0ebf1c46f123eaaf4b9d6[elink.epmet]")
.parseClaimsJws(tokenStr)
.getBody();
System.out.println("app="+ claims.get("app"));
System.out.println("client="+ claims.get("client"));
System.out.println("userId="+ claims.get("userId"));
}
}

5
epmet-auth/src/main/java/com/epmet/jwt/JwtUtils.java

@ -29,9 +29,10 @@ import java.util.Date;
public class JwtUtils {
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
/* @Autowired
private JwtProperties jwtProperties;*/
@Autowired
private JwtProperties jwtProperties;
private JwtTokenProperties jwtProperties;
/**
* 生成jwt token
*/

65
epmet-auth/src/main/java/com/epmet/redis/CaptchaRedis.java

@ -8,8 +8,13 @@
package com.epmet.redis;
import com.epmet.common.token.constant.LoginConstant;
import com.epmet.commons.tools.redis.RedisKeys;
import com.epmet.commons.tools.redis.RedisUtils;
import com.epmet.dto.form.PublicSendSmsCodeFormDTO;
import com.epmet.dto.form.SendSmsCodeFormDTO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@ -21,22 +26,29 @@ import org.springframework.stereotype.Component;
*/
@Component
public class CaptchaRedis {
private Logger logger = LogManager.getLogger(CaptchaRedis.class);
/**
* 验证码5分钟过期
*/
private final static long EXPIRE = 60 * 5L;
/**
* 过期时长为30分钟单位
*/
private final static long MINUTE_THIRTY_EXPIRE = 60 * 30 * 1L;
@Autowired
private RedisUtils redisUtils;
public void set(String uuid, String captcha){
String key = RedisKeys.getLoginCaptchaKey(uuid);
logger.info("保存验证码key=["+key+"]");
redisUtils.set(key, captcha, EXPIRE);
}
public String get(String uuid){
String key = RedisKeys.getLoginCaptchaKey(uuid);
String captcha = (String)redisUtils.get(key);
//logger.info("获取验证码key=["+key+"]captcha=["+captcha+"]");
//删除验证码
if(captcha != null){
redisUtils.delete(key);
@ -44,4 +56,55 @@ public class CaptchaRedis {
return captcha;
}
/**
* @param sendSmsCodeFormDTO appclientphone
* @param smsCode 验证码
* @return void
* @Author yinzuomei
* @Description
* @Date 2020/4/18 13:53
**/
public void saveSmsCode(SendSmsCodeFormDTO sendSmsCodeFormDTO, String smsCode) {
String smsCodeKey = RedisKeys.getLoginSmsCodeKey(LoginConstant.APP_GOV, LoginConstant.CLIENT_WXMP, sendSmsCodeFormDTO.getMobile());
logger.info(String.format("短信验证码key=%s", smsCodeKey));
redisUtils.set(smsCodeKey, smsCode, MINUTE_THIRTY_EXPIRE);
}
/**
* @param mobile
* @return java.lang.String
* @Author yinzuomei
* @Description 获取登录时发送的验证码
* @Date 2020/4/18 21:33
**/
public String getSmsCode(String mobile) {
String smsCodeKey = RedisKeys.getLoginSmsCodeKey(LoginConstant.APP_GOV, LoginConstant.CLIENT_WXMP, mobile);
String smsCode = (String) redisUtils.get(smsCodeKey);
return smsCode;
}
/**
* @param sendSmsCodeFormDTO appclientphone
* @param smsCode 验证码
* @return void
* @Author sun
* @Description 公众号-短信验证码存入redis
**/
public void savePublicSmsCode(PublicSendSmsCodeFormDTO sendSmsCodeFormDTO, String smsCode) {
String smsCodeKey = RedisKeys.getLoginSmsCodeKey(LoginConstant.APP_PUBLIC, LoginConstant.CLIENT_MP, sendSmsCodeFormDTO.getPhone());
logger.info(String.format("短信验证码key=%s", smsCodeKey));
redisUtils.set(smsCodeKey, smsCode, MINUTE_THIRTY_EXPIRE);
}
/**
* @param phone
* @return java.lang.String
* @Author sun
* @Description 公众号-获取登录时发送的验证码
**/
public String getPublicSmsCode(String phone) {
String smsCodeKey = RedisKeys.getLoginSmsCodeKey(LoginConstant.APP_PUBLIC, LoginConstant.CLIENT_MP, phone);
String smsCode = (String) redisUtils.get(smsCodeKey);
return smsCode;
}
}

124
epmet-auth/src/main/java/com/epmet/redis/CustomerAppWxServiceUtil.java

@ -0,0 +1,124 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有侵权必究
*/
package com.epmet.redis;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.alibaba.fastjson.JSON;
import com.epmet.commons.tools.redis.RedisKeys;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.CustomerAppDTO;
import com.epmet.dto.CustomerAppRedisDTO;
import com.epmet.feign.OperCrmOpenFeignClient;
import com.google.common.collect.Maps;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 客户app Redis
*
* @author Mark sunlightcs@gmail.com
* @since 1.0.0
*/
@Component
public class CustomerAppWxServiceUtil implements ApplicationRunner {
private static Logger logger = LogManager.getLogger(CustomerAppWxServiceUtil.class);
/**
* 过期时长为30分钟单位
*/
private final static long MINUTE_THIRTY_EXPIRE = 60 * 60 * 24 * 7L;
private final static String JSON_STR = "JSON";
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private OperCrmOpenFeignClient operCrmOpenFeignClient;
private static Map<String, WxMaService> maServices = Maps.newConcurrentMap();
public static WxMaService getWxMaService(String appId) {
WxMaService wxMaService = maServices.get(appId);
if (wxMaService == null) {
logger.error("getMaService appId:{} is not config from customer_app", appId);
}
return wxMaService;
}
@Override
public void run(ApplicationArguments args) {
initWxMaService();
}
public Set<String> initWxMaService() {
Map<String, WxMaService> maServicesNew = Maps.newConcurrentMap();
SetOperations appSet = null;
List<CustomerAppDTO> result = null;
String appKey = RedisKeys.getCustomerAppKey();
try {
appSet = redisTemplate.opsForSet();
Set<CustomerAppRedisDTO> members = appSet.members(appKey);
if (!CollectionUtils.isEmpty(members)) {
members.forEach(app -> {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(app.getAppId());
config.setSecret(app.getSecret());
config.setMsgDataFormat(JSON_STR);
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(config);
maServicesNew.put(app.getAppId(), service);
});
}
} catch (Exception ex) {
logger.error("init wxMaService from redis error", ex);
}
try {
Result<List<CustomerAppDTO>> configAllAppResult = operCrmOpenFeignClient.getConfigAllApp();
logger.info("wxMaService operCrmOpenFeignClient.getConfigAllApp result:{}", JSON.toJSONString(configAllAppResult));
if (configAllAppResult == null || !configAllAppResult.success()) {
logger.info("wxMaService operCrmOpenFeignClient.getConfigAllApp fail");
return maServicesNew.keySet();
}
result = configAllAppResult.getData();
result.forEach(app -> {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(app.getAppId());
config.setSecret(app.getSecret());
config.setMsgDataFormat(JSON_STR);
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(config);
maServicesNew.put(app.getAppId(), service);
});
} catch (Exception e) {
logger.error("init wxMaService from db exception", e);
}
if (maServicesNew.size() > 0) {
maServices = maServicesNew;
if (appSet != null && result != null) {
for (CustomerAppDTO app : result) {
appSet.add(appKey, app);
}
}
}
return maServicesNew.keySet();
}
}

79
epmet-auth/src/main/java/com/epmet/service/GovLoginService.java

@ -0,0 +1,79 @@
package com.epmet.service;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.dto.form.GovWxmpEnteOrgFormDTO;
import com.epmet.dto.form.GovWxmpFormDTO;
import com.epmet.dto.form.SendSmsCodeFormDTO;
import com.epmet.dto.form.StaffOrgsFormDTO;
import com.epmet.dto.result.StaffOrgsResultDTO;
import com.epmet.dto.result.UserTokenResultDTO;
import java.util.List;
/**
* @Description 政府端登录服务
* @Author yinzuomei
* @Date 2020/4/20 10:56
*/
public interface GovLoginService {
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result
* @Author yinzuomei
* @Description 政府端微信小程序登录-发送验证码
* @Date 2020/4/18 10:59
**/
void sendSmsCode(SendSmsCodeFormDTO formDTO);
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.common.token.dto.result.UserTokenResultDTO>
* @Author yinzuomei
* @Description 3手机验证码获取组织
* @Date 2020/4/18 21:11
**/
List<StaffOrgsResultDTO> getMyOrg(StaffOrgsFormDTO formDTO);
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.result.UserTokenResultDTO>
* @Author yinzuomei
* @Description 政府端小程序根据wxCode获取上一次登录信息返回token
* @Date 2020/4/20 11:23
**/
UserTokenResultDTO loginByWxCode(GovWxmpFormDTO formDTO);
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.result.UserTokenResultDTO>
* @Author yinzuomei
* @Description 4选择组织进入首页
* @Date 2020/4/20 13:08
**/
UserTokenResultDTO enterOrg(GovWxmpEnteOrgFormDTO formDTO);
/**
* @return com.epmet.commons.tools.utils.Result
* @param tokenDto
* @Author yinzuomei
* @Description 政府端工作人员退出登录
* @Date 2020/4/21 22:08
**/
void loginOut(TokenDto tokenDto);
/**
* 更新缓存中的角色列表
* @param staffId
* @param roleIds
*/
void updateCachedRoles(String staffId, String orgId, List<String> roleIds);
/**
* @return java.util.List<com.epmet.dto.result.StaffOrgsResultDTO>
* @param formDTO
* @author yinzuomei
* @description 6手机号密码获取组织
* @Date 2020/6/30 22:43
**/
List<StaffOrgsResultDTO> getMyOrgByPassword(StaffOrgsFormDTO formDTO);
}

63
epmet-auth/src/main/java/com/epmet/service/LoginService.java

@ -0,0 +1,63 @@
package com.epmet.service;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.utils.Result;
import com.epmet.dto.form.LoginByPassWordFormDTO;
import com.epmet.dto.form.LoginByWxCodeFormDTO;
import com.epmet.dto.form.ResiWxPhoneFormDTO;
import com.epmet.dto.result.UserTokenResultDTO;
/**
* @Description
* @Author yinzuomei
* @Date 2020/3/14 20:21
*/
public interface LoginService {
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.UserTokenResultDTO>
* @Author yinzuomei
* @Description 居民端微信小程序登录
* @Date 2020/3/14 19:34
**/
Result<UserTokenResultDTO> loginByWxCode(LoginByWxCodeFormDTO formDTO);
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.UserTokenResultDTO>
* @Author yinzuomei
* @Description 手机号+密码登录接口
* @Date 2020/3/14 19:54
**/
Result<UserTokenResultDTO> loginByPassword(LoginByPassWordFormDTO formDTO);
/**
* @param tokenDto
* @return com.epmet.commons.tools.utils.Result
* @Author yinzuomei
* @Description 退出登录
* @Date 2020/3/18 22:44
**/
Result logoutByToken(TokenDto tokenDto);
/**
* @return cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult
* @param app
* @param wxCode
* @param appId 非必填
* @Author yinzuomei
* @Description 解析wxCode
* @Date 2020/4/19 0:24
**/
WxMaJscode2SessionResult getWxMaUser(String app, String wxCode, String appId);
/**
* @return java.lang.String
* @param formDTO
* @author yinzuomei
* @description 获取用户微信绑定的手机号
* @Date 2020/7/2 14:33
**/
String getResiWxPhone(ResiWxPhoneFormDTO formDTO);
}

50
epmet-auth/src/main/java/com/epmet/service/PublicUserLoginService.java

@ -0,0 +1,50 @@
package com.epmet.service;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.dto.form.LoginByPhoneFormDTO;
import com.epmet.dto.form.PaWxCodeFormDTO;
import com.epmet.dto.form.PublicSendSmsCodeFormDTO;
import com.epmet.dto.form.RegisterFormDTO;
import com.epmet.dto.result.UserTokenResultDTO;
/**
* 描述一下
*
* @author yinzuomei@elink-cn.com
* @date 2020/7/8 18:31
*/
public interface PublicUserLoginService {
/**
* @return
* @param formDTO
* @author sun
* @description 解析wxcode获取用户信息并生成token
**/
UserTokenResultDTO wxCodeToToken(PaWxCodeFormDTO formDTO);
/**
* @param formDTO 手机号
* @return com.epmet.commons.tools.utils.Result
* @Author sun
* @Description 公众号登录-发送验证码
**/
void sendSmsCode(PublicSendSmsCodeFormDTO formDTO);
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result
* @Author sun
* @Description 公众号-手机验证码登陆
**/
UserTokenResultDTO loginByPhone(TokenDto tokenDTO, LoginByPhoneFormDTO formDTO);
/**
* @param formDTO
* @return
* @Author sun
* @Description 公众号-手机号注册
**/
UserTokenResultDTO register(RegisterFormDTO formDTO);
}

56
epmet-auth/src/main/java/com/epmet/service/ThirdLoginService.java

@ -0,0 +1,56 @@
package com.epmet.service;
import com.epmet.dto.form.LoginFormDTO;
import com.epmet.dto.form.ThirdStaffOrgsFormDTO;
import com.epmet.dto.form.ThirdWxmpEnteOrgFormDTO;
import com.epmet.dto.result.StaffOrgsResultDTO;
import com.epmet.dto.result.UserTokenResultDTO;
import java.util.List;
/**
* @Description 第三方-居民端政府端登陆服务
* @author sun
*/
public interface ThirdLoginService {
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-居民端微信小程序登录
**/
UserTokenResultDTO resiLogin(LoginFormDTO formDTO);
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-政府端微信小程序登录
**/
UserTokenResultDTO workLogin(LoginFormDTO formDTO);
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-选择组织进入首页
**/
UserTokenResultDTO enterOrg(ThirdWxmpEnteOrgFormDTO formDTO);
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-手机验证码获取组织
**/
List<StaffOrgsResultDTO> getMyOrg(ThirdStaffOrgsFormDTO formDTO);
/**
* @param formDTO
* @return
* @author sun
* @description 单客户-手机号密码获取组织
**/
List<StaffOrgsResultDTO> getMyOrgByPassword(ThirdStaffOrgsFormDTO formDTO);
}

5
epmet-auth/src/main/java/com/epmet/service/impl/CaptchaServiceImpl.java

@ -11,6 +11,8 @@ package com.epmet.service.impl;
import com.google.code.kaptcha.Producer;
import com.epmet.redis.CaptchaRedis;
import com.epmet.service.CaptchaService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -24,6 +26,7 @@ import java.awt.image.BufferedImage;
*/
@Service
public class CaptchaServiceImpl implements CaptchaService {
private Logger logger = LogManager.getLogger(CaptchaServiceImpl.class);
@Autowired
private Producer producer;
@Autowired
@ -33,7 +36,7 @@ public class CaptchaServiceImpl implements CaptchaService {
public BufferedImage create(String uuid) {
//生成验证码
String captcha = producer.createText();
//logger.info("uuid:"+uuid+",生成的验证码:"+captcha);
//保存验证码
captchaRedis.set(uuid, captcha);

493
epmet-auth/src/main/java/com/epmet/service/impl/GovLoginServiceImpl.java

@ -0,0 +1,493 @@
package com.epmet.service.impl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.epmet.common.token.constant.LoginConstant;
import com.epmet.commons.tools.constant.AppClientConstant;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.exception.EpmetErrorCode;
import com.epmet.commons.tools.exception.ExceptionUtils;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.security.dto.GovTokenDto;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.security.password.PasswordUtils;
import com.epmet.commons.tools.utils.ConvertUtils;
import com.epmet.commons.tools.utils.CpUserDetailRedis;
import com.epmet.commons.tools.utils.DateUtils;
import com.epmet.commons.tools.utils.Result;
import com.epmet.commons.tools.validator.PhoneValidatorUtils;
import com.epmet.constant.SmsTemplateConstant;
import com.epmet.dto.CustomerAgencyDTO;
import com.epmet.dto.CustomerStaffDTO;
import com.epmet.dto.GovStaffRoleDTO;
import com.epmet.dto.form.*;
import com.epmet.dto.result.*;
import com.epmet.feign.EpmetMessageOpenFeignClient;
import com.epmet.feign.EpmetUserFeignClient;
import com.epmet.feign.EpmetUserOpenFeignClient;
import com.epmet.feign.GovOrgFeignClient;
import com.epmet.jwt.JwtTokenProperties;
import com.epmet.jwt.JwtTokenUtils;
import com.epmet.redis.CaptchaRedis;
import com.epmet.service.GovLoginService;
import com.epmet.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.stream.Collectors;
/**
* @Description 政府端登录服务
* @Author yinzuomei
* @Date 2020/4/20 10:56
*/
@Service
public class GovLoginServiceImpl implements GovLoginService {
private static final Logger logger = LoggerFactory.getLogger(GovLoginServiceImpl.class);
private static final String SEND_SMS_CODE_ERROR = "发送短信验证码异常,手机号[%s],code[%s],msg[%s]";
@Autowired
private LoginService loginService;
@Autowired
private EpmetUserFeignClient epmetUserFeignClient;
@Autowired
private CaptchaRedis captchaRedis;
@Autowired
private JwtTokenUtils jwtTokenUtils;
@Autowired
private JwtTokenProperties jwtTokenProperties;
@Autowired
private CpUserDetailRedis cpUserDetailRedis;
@Autowired
private GovOrgFeignClient govOrgFeignClient;
@Autowired
private EpmetMessageOpenFeignClient epmetMessageOpenFeignClient;
@Autowired
private EpmetUserOpenFeignClient userOpenFeignClient;
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result
* @Author yinzuomei
* @Description 政府端微信小程序登录-发送验证码
* @Date 2020/4/18 10:59
**/
@Override
public void sendSmsCode(SendSmsCodeFormDTO formDTO) {
//1、校验手机号是否符合规范
if (!PhoneValidatorUtils.isMobile(formDTO.getMobile())) {
logger.error(String.format(SEND_SMS_CODE_ERROR, formDTO.getMobile(), EpmetErrorCode.ERROR_PHONE.getCode(), EpmetErrorCode.ERROR_PHONE.getMsg()));
throw new RenException(EpmetErrorCode.ERROR_PHONE.getCode());
}
//2、根据手机号校验用户是否存在
Result<List<CustomerStaffDTO>> customerStaffResult = epmetUserFeignClient.checkCustomerStaff(formDTO.getMobile());
if (!customerStaffResult.success()) {
logger.error(String.format(SEND_SMS_CODE_ERROR, formDTO.getMobile(), customerStaffResult.getCode(), customerStaffResult.getMsg()));
throw new RenException(customerStaffResult.getCode());
}
//3、发送短信验证码
SendVerificationCodeFormDTO sendVerificationCodeFormDTO=new SendVerificationCodeFormDTO();
sendVerificationCodeFormDTO.setMobile(formDTO.getMobile());
sendVerificationCodeFormDTO.setAliyunTemplateCode(SmsTemplateConstant.LGOIN_CONFIRM);
Result<SendVerificationCodeResultDTO> smsCodeResult=epmetMessageOpenFeignClient.sendVerificationCode(sendVerificationCodeFormDTO);
if (!smsCodeResult.success()) {
logger.error(String.format(SEND_SMS_CODE_ERROR, formDTO.getMobile(), smsCodeResult.getCode(), smsCodeResult.getMsg()));
throw new RenException(smsCodeResult.getCode());
}
//4、保存短信验证码(删除现有短信验证码、将新的短信验证码存入Redis)
captchaRedis.saveSmsCode(formDTO, smsCodeResult.getData().getCode());
logger.info(String.format("发送短信验证码成功,手机号[%s]", formDTO.getMobile()));
}
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.common.token.dto.result.UserTokenResultDTO>
* @Author yinzuomei
* @Description 3手机验证码获取组织
* @Date 2020/4/18 21:11
**/
@Override
public List<StaffOrgsResultDTO> getMyOrg(StaffOrgsFormDTO formDTO) {
//1、根据手机号查询到用户信息
Result<List<CustomerStaffDTO>> customerStaffResult = epmetUserFeignClient.checkCustomerStaff(formDTO.getMobile());
if (!customerStaffResult.success()) {
logger.error(String.format("手机验证码登录异常,手机号[%s],code[%s],msg[%s]", formDTO.getMobile(), customerStaffResult.getCode(), customerStaffResult.getMsg()));
throw new RenException(customerStaffResult.getCode());
}
//2、验证码是否正确
String rightSmsCode = captchaRedis.getSmsCode(formDTO.getMobile());
if (!formDTO.getSmsCode().equals(rightSmsCode)) {
logger.error(String.format("验证码错误code[%s],msg[%s]",EpmetErrorCode.MOBILE_CODE_ERROR.getCode(),EpmetErrorCode.MOBILE_CODE_ERROR.getMsg()));
throw new RenException(EpmetErrorCode.MOBILE_CODE_ERROR.getCode());
}
//3、查询用户所有的组织信息
List<String> customerIdList = new ArrayList<>();
for (CustomerStaffDTO customerStaffDTO : customerStaffResult.getData()) {
customerIdList.add(customerStaffDTO.getCustomerId());
}
StaffOrgFormDTO staffOrgFormDTO = new StaffOrgFormDTO();
staffOrgFormDTO.setCustomerIdList(customerIdList);
Result<List<StaffOrgsResultDTO>> result = govOrgFeignClient.getStaffOrgList(staffOrgFormDTO);
if(result.success()&&null!=result.getData()){
return result.getData();
}
logger.error(String .format("手机验证码获取组织,调用%s服务失败,入参手机号%s,验证码%s,返回错误码%s,错误提示信息%s", ServiceConstant.GOV_ORG_SERVER,formDTO.getMobile(),formDTO.getSmsCode(),result.getCode(),result.getMsg()));
return new ArrayList<>();
}
@Override
public UserTokenResultDTO loginByWxCode(GovWxmpFormDTO formDTO) {
//1、解析微信用户
WxMaJscode2SessionResult wxMaJscode2SessionResult = loginService.getWxMaUser(formDTO.getApp(), formDTO.getWxCode(), formDTO.getAppId());
if(null!=wxMaJscode2SessionResult){
logger.info(String.format("app=%s,wxCode=%s,openId=%s",formDTO.getApp(),formDTO.getWxCode(),wxMaJscode2SessionResult.getOpenid()));
}
Result<StaffLatestAgencyResultDTO> latestStaffWechat = epmetUserFeignClient.getLatestStaffWechatLoginRecord(wxMaJscode2SessionResult.getOpenid());
if (!latestStaffWechat.success() || null == latestStaffWechat.getData()) {
logger.error(String.format("没有获取到用户最近一次登录账户信息,code[%s],msg[%s]", EpmetErrorCode.PLEASE_LOGIN.getCode(), EpmetErrorCode.PLEASE_LOGIN.getMsg()));
throw new RenException(EpmetErrorCode.PLEASE_LOGIN.getCode());
}
StaffLatestAgencyResultDTO staffLatestAgencyResultDTO = latestStaffWechat.getData();
//2、记录staff_wechat
this.savestaffwechat(staffLatestAgencyResultDTO.getStaffId(), wxMaJscode2SessionResult.getOpenid());
//3、记录登录日志
this.saveStaffLoginRecord(staffLatestAgencyResultDTO);
//4、获取用户token
String token = this.generateGovWxmpToken(staffLatestAgencyResultDTO.getStaffId());
//5、保存到redis
this.saveLatestGovTokenDto(staffLatestAgencyResultDTO, wxMaJscode2SessionResult, token);
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
}
//保存tokenDto到redis
private void saveLatestGovTokenDto(StaffLatestAgencyResultDTO staffLatestAgency,
WxMaJscode2SessionResult wxMaJscode2SessionResult,
String token) {
int expire = jwtTokenProperties.getExpire();
GovTokenDto govTokenDto = new GovTokenDto();
govTokenDto.setApp(LoginConstant.APP_GOV);
govTokenDto.setClient(LoginConstant.CLIENT_WXMP);
govTokenDto.setUserId(staffLatestAgency.getStaffId());
govTokenDto.setOpenId(wxMaJscode2SessionResult.getOpenid());
govTokenDto.setSessionKey(wxMaJscode2SessionResult.getSessionKey());
govTokenDto.setUnionId(wxMaJscode2SessionResult.getUnionid());
govTokenDto.setToken(token);
govTokenDto.setUpdateTime(System.currentTimeMillis());
govTokenDto.setExpireTime(jwtTokenUtils.getExpiration(token).getTime());
govTokenDto.setRootAgencyId(staffLatestAgency.getAgencyId());
govTokenDto.setCustomerId(staffLatestAgency.getCustomerId());
//设置部门,网格,角色列表
govTokenDto.setDeptIdList(getDeptartmentIdList(staffLatestAgency.getStaffId()));
govTokenDto.setGridIdList(getGridIdList(staffLatestAgency.getStaffId()));
CustomerAgencyDTO agency = getAgencyByStaffId(staffLatestAgency.getStaffId());
if (agency != null) {
govTokenDto.setAgencyId(agency.getId());
govTokenDto.setRoleList(queryGovStaffRoles(staffLatestAgency.getStaffId(), agency.getId()));
}
govTokenDto.setOrgIdPath(getOrgIdPath(staffLatestAgency.getStaffId()));
cpUserDetailRedis.set(govTokenDto, expire);
logger.info("截止时间:" + DateUtils.format(jwtTokenUtils.getExpiration(token), "yyyy-MM-dd HH:mm:ss"));
}
/**
* 查询人员在某机关单位下的角色列表
* @param staffId
* @param orgId
* @return
*/
public List<GovTokenDto.Role> queryGovStaffRoles(String staffId, String orgId) {
StaffRoleFormDTO formDTO = new StaffRoleFormDTO();
formDTO.setStaffId(staffId);
formDTO.setOrgId(orgId);
Result<List<GovStaffRoleDTO>> gridResult = epmetUserFeignClient.getRolesOfStaff(formDTO);
if (!CollectionUtils.isEmpty(gridResult.getData())) {
//return gridResult.getData().stream().map(role -> role.getId()).collect(Collectors.toSet());
return ConvertUtils.sourceToTarget(gridResult.getData(), GovTokenDto.Role.class);
}
return null;
}
/**
* 根据工作人员ID查询网格ID列表
* @param staffId
* @return
*/
public Set<String> getGridIdList(String staffId) {
Result<List<GridByStaffResultDTO>> result = govOrgFeignClient.listGridsbystaffid(staffId);
if (!result.success()) {
logger.error("登录:查询网格列表,远程调用返回错误:{}", result.getMsg());
return null;
} else {
List<GridByStaffResultDTO> grids = result.getData();
return grids.stream().map(grid -> grid.getGridId()).collect(Collectors.toSet());
}
}
public Set<String> getDeptartmentIdList(String staffId) {
try {
Result<List<DepartmentListResultDTO>> deptListResult = govOrgFeignClient.getDepartmentListByStaffId(staffId);
if (deptListResult.success()) {
if (!CollectionUtils.isEmpty(deptListResult.getData())) {
Set<String> deptIdLists = deptListResult.getData().stream().map(dept -> dept.getDepartmentId()).collect(Collectors.toSet());
return deptIdLists;
}
} else {
logger.error("登录:查询部门列表,远程调用返回错误:{}", deptListResult.getMsg());
}
} catch (Exception e) {
String errorStackTrace = ExceptionUtils.getErrorStackTrace(e);
logger.error("登录:查询部门列表异常:{}", errorStackTrace);
}
return null;
}
//保存登录日志
private Result saveStaffLoginRecord(StaffLatestAgencyResultDTO latestStaffWechatLoginDTO) {
StaffLoginAgencyRecordFormDTO staffLoginAgencyRecordFormDTO = new StaffLoginAgencyRecordFormDTO();
staffLoginAgencyRecordFormDTO.setCustomerId(latestStaffWechatLoginDTO.getCustomerId());
staffLoginAgencyRecordFormDTO.setStaffId(latestStaffWechatLoginDTO.getStaffId());
staffLoginAgencyRecordFormDTO.setWxOpenId(latestStaffWechatLoginDTO.getWxOpenId());
staffLoginAgencyRecordFormDTO.setMobile(latestStaffWechatLoginDTO.getMobile());
staffLoginAgencyRecordFormDTO.setAgencyId(latestStaffWechatLoginDTO.getAgencyId());
Result staffLoginRecordResult = epmetUserFeignClient.saveStaffLoginRecord(staffLoginAgencyRecordFormDTO);
return staffLoginRecordResult;
}
@Override
public UserTokenResultDTO enterOrg(GovWxmpEnteOrgFormDTO formDTO) {
//1、需要校验要登录的客户,是否被禁用
CustomerStaffFormDTO customerStaffFormDTO = new CustomerStaffFormDTO();
customerStaffFormDTO.setCustomerId(formDTO.getCustomerId());
customerStaffFormDTO.setMobile(formDTO.getMobile());
Result<CustomerStaffDTO> customerStaffDTOResult = epmetUserFeignClient.getCustomerStaffInfo(customerStaffFormDTO);
if (!customerStaffDTOResult.success() || null == customerStaffDTOResult.getData()) {
logger.error(String.format("获取工作人员信息失败,手机号[%s],客户id:[%s],code[%s],msg[%s]", formDTO.getMobile(), formDTO.getCustomerId(), customerStaffDTOResult.getCode(), customerStaffDTOResult.getMsg()));
throw new RenException(customerStaffDTOResult.getCode());
}
CustomerStaffDTO customerStaff = customerStaffDTOResult.getData();
//2、解析微信用户
WxMaJscode2SessionResult wxMaJscode2SessionResult = loginService.getWxMaUser(LoginConstant.APP_GOV, formDTO.getWxCode(), formDTO.getAppId());
//3、记录staff_wechat,并记录用户激活状态,激活时间
this.savestaffwechat(customerStaff.getUserId(), wxMaJscode2SessionResult.getOpenid());
//4、记录登录日志
this.saveStaffLoginRecord(formDTO, customerStaff.getUserId(), wxMaJscode2SessionResult.getOpenid());
//5.1、获取用户token
String token = this.generateGovWxmpToken(customerStaff.getUserId());
//5.2、保存到redis
this.saveGovTokenDto(formDTO.getRootAgencyId(), formDTO.getCustomerId(), customerStaff.getUserId(), wxMaJscode2SessionResult, token);
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
}
@Override
public void loginOut(TokenDto tokenDto) {
if(null == tokenDto){
logger.error("token解析失败,直接跳转重新登录即可");
throw new RenException("当前用户信息获取失败");
}
cpUserDetailRedis.logout(tokenDto.getApp() , tokenDto.getClient() , tokenDto.getUserId());
}
@Override
public void updateCachedRoles(String staffId, String orgId, List<String> roleIds) {
GovTokenDto userDetails = cpUserDetailRedis.get(AppClientConstant.APP_GOV, AppClientConstant.CLIENT_WXMP, staffId, GovTokenDto.class);
if (userDetails == null) {
return;
}
GovStaffRoleFormDTO form = new GovStaffRoleFormDTO();
form.setRoleIdList(roleIds);
Result<List<GovStaffRoleResultDTO>> result = userOpenFeignClient.getByIds(form);
if (!result.success()) {
throw new RenException("更新缓存中的角色列表失败:" + result.getInternalMsg());
}
List<GovTokenDto.Role> roles = result.getData().stream().map(roleDto -> {
GovTokenDto.Role role = new GovTokenDto.Role();
role.setRoleName(roleDto.getRoleName());
role.setRoleKey(roleDto.getRoleKey());
role.setId(roleDto.getRoleId());
return role;
}).collect(Collectors.toList());
userDetails.setRoleList(roles);
cpUserDetailRedis.set(userDetails, jwtTokenProperties.getExpire());
}
@Override
public List<StaffOrgsResultDTO> getMyOrgByPassword(StaffOrgsFormDTO formDTO) {
//1、根据手机号查询到用户信息
Result<List<CustomerStaffDTO>> customerStaffResult = epmetUserFeignClient.checkCustomerStaff(formDTO.getMobile());
if (!customerStaffResult.success()) {
logger.error(String.format("手机密码登录异常,手机号[%s],code[%s],msg[%s]", formDTO.getMobile(), customerStaffResult.getCode(), customerStaffResult.getMsg()));
throw new RenException(customerStaffResult.getCode());
}
//2、密码是否正确
List<CustomerStaffDTO> customerStaffList=customerStaffResult.getData();
//3、查询用户所有的组织信息
List<String> customerIdList = new ArrayList<>();
//是否设置过密码
boolean havePasswordFlag=false;
//密码是否正确
boolean passwordRightFlag=false;
for (CustomerStaffDTO customerStaffDTO : customerStaffList) {
if(StringUtils.isNotBlank(customerStaffDTO.getPassword())){
havePasswordFlag=true;
}else{
logger.warn(String.format("当前用户:手机号%s,客户Id%s下未设置密码.",formDTO.getMobile(),customerStaffDTO.getCustomerId()));
continue;
}
if (!PasswordUtils.matches(formDTO.getPassword(), customerStaffDTO.getPassword())) {
logger.warn(String.format("当前用户:手机号%s,客户Id%s密码匹配错误.",formDTO.getMobile(),customerStaffDTO.getCustomerId()));
}else{
logger.warn(String.format("当前用户:手机号%s,客户Id%s密码匹配正确.",formDTO.getMobile(),customerStaffDTO.getCustomerId()));
passwordRightFlag=true;
customerIdList.add(customerStaffDTO.getCustomerId());
}
}
//根据手机号查出来所有用户,密码都为空,表明用户未激活账户,未设置密码
if(!havePasswordFlag){
logger.error(String.format("当前手机号(%s)下所有账户都未设置密码,请先使用验证码登录激活账户",formDTO.getMobile()));
throw new RenException(EpmetErrorCode.PASSWORD_ERROR.getCode());
}
//密码错误
if(!passwordRightFlag){
logger.error(String.format("根据当前手机号(%s)密码未找到所属组织,密码错误",formDTO.getMobile()));
throw new RenException(EpmetErrorCode.PASSWORD_ERROR.getCode());
}
StaffOrgFormDTO staffOrgFormDTO = new StaffOrgFormDTO();
staffOrgFormDTO.setCustomerIdList(customerIdList);
Result<List<StaffOrgsResultDTO>> result = govOrgFeignClient.getStaffOrgList(staffOrgFormDTO);
if(result.success()&&null!=result.getData()){
return result.getData();
}
logger.error(String .format("手机验证码获取组织,调用%s服务失败,入参手机号%s,密码%s,返回错误码%s,错误提示信息%s",
ServiceConstant.GOV_ORG_SERVER,
formDTO.getMobile(),
formDTO.getPassword(),
result.getCode(),
result.getMsg()));
return new ArrayList<>();
}
//保存登录日志
private Result saveStaffLoginRecord(GovWxmpEnteOrgFormDTO formDTO, String staffId, String openId) {
StaffLoginAgencyRecordFormDTO staffLoginAgencyRecordFormDTO = new StaffLoginAgencyRecordFormDTO();
staffLoginAgencyRecordFormDTO.setCustomerId(formDTO.getCustomerId());
staffLoginAgencyRecordFormDTO.setStaffId(staffId);
staffLoginAgencyRecordFormDTO.setWxOpenId(openId);
staffLoginAgencyRecordFormDTO.setMobile(formDTO.getMobile());
staffLoginAgencyRecordFormDTO.setAgencyId(formDTO.getRootAgencyId());
Result staffLoginRecordResult = epmetUserFeignClient.saveStaffLoginRecord(staffLoginAgencyRecordFormDTO);
return staffLoginRecordResult;
}
/**
* @param userId
* @param openid
* @return com.epmet.commons.tools.utils.Result
* @Author yinzuomei
* @Description 保存微信和当前登录用户关系
* @Date 2020/4/18 22:54
**/
private Result savestaffwechat(String userId, String openid) {
StaffWechatFormDTO staffWechatFormDTO = new StaffWechatFormDTO();
staffWechatFormDTO.setUserId(userId);
staffWechatFormDTO.setWxOpenId(openid);
return epmetUserFeignClient.saveStaffWechat(staffWechatFormDTO);
}
/**
* @Description 生成token
* @Date 2020/4/18 23:04
**/
private String generateGovWxmpToken(String staffId) {
Map<String, Object> map = new HashMap<>();
map.put("app", LoginConstant.APP_GOV);
map.put("client", LoginConstant.CLIENT_WXMP);
map.put("userId", staffId);
String token = jwtTokenUtils.createToken(map);
logger.info("app:" + LoginConstant.APP_GOV + ";client:" + LoginConstant.CLIENT_WXMP + ";userId:" + staffId + ";生成token[" + token + "]");
return token;
}
/**
* @Description 生成token
* @Date 2020/4/18 23:04
**/
private void saveGovTokenDto(String orgId,
String customerId,
String staffId,
WxMaJscode2SessionResult wxMaJscode2SessionResult,
String token) {
int expire = jwtTokenProperties.getExpire();
GovTokenDto govTokenDto = new GovTokenDto();
govTokenDto.setApp(LoginConstant.APP_GOV);
govTokenDto.setClient(LoginConstant.CLIENT_WXMP);
govTokenDto.setUserId(staffId);
govTokenDto.setOpenId(wxMaJscode2SessionResult.getOpenid());
govTokenDto.setSessionKey(wxMaJscode2SessionResult.getSessionKey());
govTokenDto.setUnionId(null == wxMaJscode2SessionResult.getUnionid() ? "" : wxMaJscode2SessionResult.getUnionid());
govTokenDto.setToken(token);
govTokenDto.setUpdateTime(System.currentTimeMillis());
govTokenDto.setExpireTime(jwtTokenUtils.getExpiration(token).getTime());
govTokenDto.setRootAgencyId(orgId);
govTokenDto.setCustomerId(customerId);
//设置部门,网格,角色列表
govTokenDto.setDeptIdList(getDeptartmentIdList(staffId));
govTokenDto.setGridIdList(getGridIdList(staffId));
CustomerAgencyDTO agency = getAgencyByStaffId(staffId);
if (agency != null) {
govTokenDto.setAgencyId(agency.getId());
govTokenDto.setRoleList(queryGovStaffRoles(staffId, agency.getId()));
}
govTokenDto.setOrgIdPath(getOrgIdPath(staffId));
cpUserDetailRedis.set(govTokenDto, expire);
logger.info("截止时间:" + DateUtils.format(jwtTokenUtils.getExpiration(token), "yyyy-MM-dd HH:mm:ss"));
}
/**
* 查询工作人员的OrgIdPath
* @param staffId
* @return
*/
public String getOrgIdPath(String staffId) {
Result<CustomerAgencyDTO> result = govOrgFeignClient.getAgencyByStaff(staffId);
if (!result.success()) {
logger.error("登录:查询登录人所属的机关OrgIdPath失败:{}", result.getMsg());
return null;
}
CustomerAgencyDTO agency = result.getData();
if (agency != null) {
if ("0".equals(agency.getPid())) {
// 顶级
return agency.getId();
} else {
return agency.getPids().concat(":").concat(agency.getId());
}
}
return null;
}
public CustomerAgencyDTO getAgencyByStaffId(String staffId) {
Result<CustomerAgencyDTO> result = govOrgFeignClient.getAgencyByStaff(staffId);
if (!result.success()) {
logger.error("登录:查询登录人所属的机关OrgIdPath失败:{}", result.getMsg());
return null;
}
return result.getData();
}
}

409
epmet-auth/src/main/java/com/epmet/service/impl/LoginServiceImpl.java

@ -0,0 +1,409 @@
package com.epmet.service.impl;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.alibaba.fastjson.JSON;
import com.epmet.common.token.constant.LoginConstant;
import com.epmet.commons.tools.exception.EpmetErrorCode;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.security.password.PasswordUtils;
import com.epmet.commons.tools.utils.CpUserDetailRedis;
import com.epmet.commons.tools.utils.DateUtils;
import com.epmet.commons.tools.utils.Result;
import com.epmet.commons.tools.validator.ValidatorUtils;
import com.epmet.dto.UserDTO;
import com.epmet.dto.UserWechatDTO;
import com.epmet.dto.form.*;
import com.epmet.dto.result.PasswordLoginUserInfoResultDTO;
import com.epmet.dto.result.UserTokenResultDTO;
import com.epmet.feign.EpmetUserFeignClient;
import com.epmet.feign.OperAccessOpenFeignClient;
import com.epmet.jwt.JwtTokenProperties;
import com.epmet.jwt.JwtTokenUtils;
import com.epmet.redis.CustomerAppWxServiceUtil;
import com.epmet.service.CaptchaService;
import com.epmet.service.LoginService;
import com.epmet.utils.WxMaServiceUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* @Description
* @Author yinzuomei
* @Date 2020/3/14 20:31
*/
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
private static final Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);
@Autowired
private EpmetUserFeignClient epmetUserFeignClient;
@Autowired
private WxMaServiceUtils wxMaServiceUtils;
@Autowired
private JwtTokenUtils jwtTokenUtils;
@Autowired
private JwtTokenProperties jwtTokenProperties;
@Autowired
private CpUserDetailRedis cpUserDetailRedis;
@Autowired
private CaptchaService captchaService;
@Autowired
private OperAccessOpenFeignClient operAccessOpenFeignClient;
/**
* 居民端微信小程序登录
*
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.UserTokenResultDTO>
* @author yinzuomei
* @since 2020/3/14 19:34
*/
@Override
public Result<UserTokenResultDTO> loginByWxCode(LoginByWxCodeFormDTO formDTO) {
if(!(LoginConstant.APP_RESI.equals(formDTO.getApp())&&LoginConstant.CLIENT_WXMP.equals(formDTO.getClient()))){
logger.error("当前接口只适用于居民端微信小程序登录");
throw new RenException("参数错误");
}
//1、根据wxCode获取微信信息
WxMaJscode2SessionResult wxMaJscode2SessionResult = this.getWxMaUser(formDTO.getApp(),formDTO.getWxCode(),formDTO.getAppId());
logger.info("openId=[" + wxMaJscode2SessionResult.getOpenid() + "]unionId=[" + wxMaJscode2SessionResult.getUnionid() + "]");
//2、根据openId查询数据库,没有则直接插入一条记录
String userId = this.getUserId(formDTO, wxMaJscode2SessionResult);
if (StringUtils.isNotBlank(userId)) {
//3、封装token且存到redis
String token=this.generateToken(formDTO,userId);
this.saveTokenDto(formDTO,userId,wxMaJscode2SessionResult,token);
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return new Result<UserTokenResultDTO>().ok(userTokenResultDTO);
}else{
logger.error("登录失败userId为空");
throw new RenException("登录失败");
}
}
/**
* 解析微信code获取小程序用户信息
*
* @param app
* @param wxCode
* @return cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult
* @author yinzuomei
* @date 2020/3/14 20:16
*/
@Override
public WxMaJscode2SessionResult getWxMaUser(String app,String wxCode,String appId) {
WxMaJscode2SessionResult wxMaJscode2SessionResult = null;
try {
if (StringUtils.isNotBlank(appId)){
WxMaService wxMaService = CustomerAppWxServiceUtil.getWxMaService(appId);
if (wxMaService == null){
throw new RenException("解析微信用户信息失败");
}
wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(wxCode);
}else{
if (LoginConstant.APP_GOV.equals(app)) {
wxMaJscode2SessionResult = wxMaServiceUtils.govWxMaService().jsCode2SessionInfo(wxCode);
} else if (LoginConstant.APP_OPER.equals(app)) {
wxMaJscode2SessionResult = wxMaServiceUtils.operWxMaService().jsCode2SessionInfo(wxCode);
} else if (LoginConstant.APP_RESI.equals(app)) {
wxMaJscode2SessionResult = wxMaServiceUtils.resiWxMaService().jsCode2SessionInfo(wxCode);
}
}
} catch (WxErrorException e) {
log.error("->[getMaOpenId]::error[{}]", "解析微信code失败",e);
}
if (null == wxMaJscode2SessionResult) {
log.error(String.format("解析微信用户信息失败,app[%s],wxCode[%s],result:[%S]",app,wxCode, JSON.toJSONString(wxMaJscode2SessionResult)));
throw new RenException("解析微信用户信息失败");
} else if (StringUtils.isBlank(wxMaJscode2SessionResult.getOpenid())) {
log.error(String.format("获取微信openid失败,app[%s],wxCode[%s]",app,wxCode));
throw new RenException("获取微信openid失败");
}
return wxMaJscode2SessionResult;
}
@Override
public String getResiWxPhone(ResiWxPhoneFormDTO formDTO) {
String phone="";
try {
ValidatorUtils.validateEntity(formDTO, ResiWxPhoneFormDTO.AddUserInternalGroup.class);
WxMaService wxMaService = null;
if (StringUtils.isNotBlank(formDTO.getAppId())){
wxMaService = CustomerAppWxServiceUtil.getWxMaService(formDTO.getAppId());
}else{
wxMaService = wxMaServiceUtils.resiWxMaService();
}
WxMaJscode2SessionResult wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(formDTO.getWxCode());
WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(wxMaJscode2SessionResult.getSessionKey(),
formDTO.getEncryptedData(),
formDTO.getIv());
if (null != phoneNoInfo) {
phone= phoneNoInfo.getPurePhoneNumber();
}
} catch (WxErrorException e) {
e.printStackTrace();
log.error(String.format("获取用户微信绑定的手机号接口异常%s",e.getMessage()));
} catch(Exception e){
e.printStackTrace();
log.error(String.format("获取用户微信绑定的手机号接口异常%s",e.getMessage()));
}
return phone;
}
/**
* 根据openId查询用户id
*
* @param formDTO
* @param wxMaJscode2SessionResult
* @return java.lang.String
* @author yinzuomei
* @since 2020/3/14 19:34
*/
private String getUserId(LoginByWxCodeFormDTO formDTO, WxMaJscode2SessionResult wxMaJscode2SessionResult) {
WxLoginUserInfoFormDTO wxLoginUserInfoFormDTO = new WxLoginUserInfoFormDTO();
wxLoginUserInfoFormDTO.setApp(formDTO.getApp());
wxLoginUserInfoFormDTO.setOpenId(wxMaJscode2SessionResult.getOpenid());
//1、先根据app、client、openId查询
Result<UserDTO> userResult = epmetUserFeignClient.selecWxLoginUserInfo(wxLoginUserInfoFormDTO);
String userId = "";
if (!userResult.success()) {
logger.error("根据openId、app获取用户信息失败" + userResult.getMsg());
throw new RenException("获取用户信息失败" + userResult.getMsg());
}
if(null!=userResult.getData()&&StringUtils.isNotBlank(userResult.getData().getId())){
userId = userResult.getData().getId();
}
//2、如果已经存在userId,则更新微信信息
if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(formDTO.getEncryptedData()) && StringUtils.isNotBlank(formDTO.getIv())) {
this.updateWxInfO(userId,formDTO,wxMaJscode2SessionResult);
}
//3、数据库不存在此用户则创建此用户
if (StringUtils.isBlank(userId)) {
userId = createUser(formDTO, wxMaJscode2SessionResult);
}
return userId;
}
/**
* @return com.epmet.commons.tools.utils.Result
* @param userId
* @param wxMaJscode2SessionResult
* @Author yinzuomei
* @Description 获取用户微信基本信息更新到本地
* @Date 2020/3/20 19:51
**/
private Result updateWxInfO(String userId,
LoginByWxCodeFormDTO formDTO,
WxMaJscode2SessionResult wxMaJscode2SessionResult) {
WxMaUserInfo wxMaUserInfo = wxMaServiceUtils.resiWxMaService().getUserService()
.getUserInfo(wxMaJscode2SessionResult.getSessionKey(),
formDTO.getEncryptedData(),
formDTO.getIv());
UserWechatDTO userWechatDTO = this.packageCustomerUserDTO(wxMaUserInfo);
userWechatDTO.setUserId(userId);
Result<UserDTO> updateUserDtoResult=epmetUserFeignClient.saveOrUpdateUserWechatDTO(userWechatDTO);
return new Result();
}
/**
* @param formDTO
* @param wxMaJscode2SessionResult
* @return java.lang.String
* @Author yinzuomei
* @Description 陌生人首次授权创建用户信息
* @Date 2020/3/20 19:42
**/
private String createUser(LoginByWxCodeFormDTO formDTO, WxMaJscode2SessionResult wxMaJscode2SessionResult) {
String userId = "";
//查询customer_user
UserWechatDTO userWechatDTO = new UserWechatDTO();
if (StringUtils.isNotBlank(formDTO.getIv()) && StringUtils.isNotBlank(formDTO.getEncryptedData())) {
WxMaUserInfo wxMaUserInfo = wxMaServiceUtils.resiWxMaService().getUserService()
.getUserInfo(wxMaJscode2SessionResult.getSessionKey(),
formDTO.getEncryptedData(),
formDTO.getIv());
userWechatDTO = this.packageCustomerUserDTO(wxMaUserInfo);
} else {
userWechatDTO.setWxOpenId(wxMaJscode2SessionResult.getOpenid());
userWechatDTO.setUnionId(wxMaJscode2SessionResult.getUnionid());
}
Result<UserDTO> saveUserWechatResult = epmetUserFeignClient.saveOrUpdateUserWechatDTO(userWechatDTO);
if (!saveUserWechatResult.success()||null==saveUserWechatResult.getData()) {
throw new RenException("创建用户失败" + saveUserWechatResult.getMsg());
}
userId = saveUserWechatResult.getData().getId();
return userId;
}
/**
* @param wxMaUserInfo
* @return com.epmet.dto.UserWechatDTO
* @Author yinzuomei
* @Description 微信信息封装为customer_user记录
* @Date 2020/3/17 18:22
**/
private UserWechatDTO packageCustomerUserDTO(WxMaUserInfo wxMaUserInfo) {
UserWechatDTO userWechatDTO = new UserWechatDTO();
userWechatDTO.setCity(wxMaUserInfo.getCity());
userWechatDTO.setWxOpenId(wxMaUserInfo.getOpenId());
userWechatDTO.setUnionId(wxMaUserInfo.getUnionId());
userWechatDTO.setNickname(wxMaUserInfo.getNickName());
userWechatDTO.setCountry(wxMaUserInfo.getCountry());
userWechatDTO.setHeadImgUrl(wxMaUserInfo.getAvatarUrl());
userWechatDTO.setProvince(wxMaUserInfo.getProvince());
userWechatDTO.setSex(Integer.valueOf(wxMaUserInfo.getGender()));
return userWechatDTO;
}
/**
* 手机号+密码登录接口
*
* @param formDTO
* @return com.epmet.commons.tools.utils.Result<com.epmet.dto.UserTokenResultDTO>
* @author yinzuomei
* @since 2020/3/14 19:34
*/
@Override
public Result<UserTokenResultDTO> loginByPassword(LoginByPassWordFormDTO formDTO) {
if(!(LoginConstant.APP_OPER.equals(formDTO.getApp())&&LoginConstant.CLIENT_WEB.equals(formDTO.getClient()))){
logger.error("当前接口只适用于运营端管理后台");
throw new RenException("当前接口只适用于运营端管理后台");
}
//1、验证码是否正确
boolean flag = captchaService.validate(formDTO.getUuid(), formDTO.getCaptcha());
if (!flag) {
logger.error(String.format("用户%s登录,验证码输入错误,暂时放行",formDTO.getPhone()));
//2020-05-21去除验证码校验 TODO
//return new Result<UserTokenResultDTO>().error(EpmetErrorCode.ERR10019.getCode());
}
//2、账号是否存在
//获取用户信息
PasswordLoginUserInfoFormDTO passwordLoginUserInfoFormDTO = new PasswordLoginUserInfoFormDTO();
passwordLoginUserInfoFormDTO.setApp(formDTO.getApp());
passwordLoginUserInfoFormDTO.setPhone(formDTO.getPhone());
Result<PasswordLoginUserInfoResultDTO> userInfoResult = epmetUserFeignClient.selectLoginUserInfoByPassword(passwordLoginUserInfoFormDTO);
if (!userInfoResult.success() || null == userInfoResult.getData()) {
logger.error("根据手机号查询运营人员信息失败,返回10003账号不存在");
throw new RenException(EpmetErrorCode.ERR10003.getCode());
}
//3、密码是否正确
//密码错误
if (!PasswordUtils.matches(formDTO.getPassword(), userInfoResult.getData().getPassWord())) {
throw new RenException(EpmetErrorCode.ERR10004.getCode());
}
//4、生成token返回,且将TokenDto存到redis
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(this.packagingUserToken(formDTO, userInfoResult.getData().getUserId()));
return new Result<UserTokenResultDTO>().ok(userTokenResultDTO);
}
/**
* 封装用户token值
*
* @param formDTO
* @param userId
* @return java.lang.String
* @author yinzuomei
* @since 2020/3/14 19:34
*/
private String packagingUserToken(LoginByPassWordFormDTO formDTO,
String userId) {
// 生成token
Map<String, Object> map = new HashMap<>();
map.put("app", formDTO.getApp());
map.put("client", formDTO.getClient());
map.put("userId", userId);
String token = jwtTokenUtils.createToken(map);
logger.info("app:"+formDTO.getApp()+";client:"+formDTO.getClient()+";userId:"+userId+";生成token["+token+"]");
int expire = jwtTokenProperties.getExpire();
TokenDto tokenDto = new TokenDto();
tokenDto.setApp(formDTO.getApp());
tokenDto.setClient(formDTO.getClient());
tokenDto.setUserId(userId);
tokenDto.setToken(token);
tokenDto.setUpdateTime(System.currentTimeMillis());
tokenDto.setExpireTime(jwtTokenUtils.getExpiration(token).getTime());
cpUserDetailRedis.set(tokenDto, expire);
logger.info("截止时间:"+ DateUtils.format(jwtTokenUtils.getExpiration(token),"yyyy-MM-dd HH:mm:ss"));
return token;
}
@Override
public Result logoutByToken(TokenDto tokenDto) {
//记录登出日志
//删除redis
if (null == tokenDto) {
logger.error("运营端用户退出系统错误:账号不存在,接口继续执行返回成功");
return new Result();
}
cpUserDetailRedis.logout(tokenDto.getApp(), tokenDto.getClient(), tokenDto.getUserId());
//web端清空菜单栏和权限
Result operAccessResult = operAccessOpenFeignClient.clearOperUserAccess();
if (operAccessResult.success()) {
logger.info(String.format("运营人员%s退出成功,清空菜单和权限redis成功", tokenDto.getUserId()));
} else {
logger.error(String.format("运营人员%s退出成功,清空菜单和权限redis异常", tokenDto.getUserId()));
}
return new Result();
}
/**
* @Description 生成token
* @Date 2020/4/18 23:04
**/
private String generateToken(LoginCommonFormDTO formDTO,String userId){
Map<String, Object> map = new HashMap<>();
map.put("app", formDTO.getApp());
map.put("client", formDTO.getClient());
map.put("userId", userId);
String token = jwtTokenUtils.createToken(map);
logger.info("app:"+formDTO.getApp()+";client:"+formDTO.getClient()+";userId:"+userId+";生成token["+token+"]");
return token;
}
/**
* @Description 生成token
* @Date 2020/4/18 23:04
**/
private String saveTokenDto(LoginCommonFormDTO formDTO,
String userId,
WxMaJscode2SessionResult wxMaJscode2SessionResult,
String token) {
int expire = jwtTokenProperties.getExpire();
TokenDto tokenDto = new TokenDto();
tokenDto.setApp(formDTO.getApp());
tokenDto.setClient(formDTO.getClient());
tokenDto.setUserId(userId);
tokenDto.setOpenId(wxMaJscode2SessionResult.getOpenid());
tokenDto.setSessionKey(wxMaJscode2SessionResult.getSessionKey());
tokenDto.setUnionId(wxMaJscode2SessionResult.getUnionid());
tokenDto.setToken(token);
tokenDto.setUpdateTime(System.currentTimeMillis());
tokenDto.setExpireTime(jwtTokenUtils.getExpiration(token).getTime());
cpUserDetailRedis.set(tokenDto, expire);
logger.info("截止时间:"+ DateUtils.format(jwtTokenUtils.getExpiration(token),"yyyy-MM-dd HH:mm:ss"));
return token;
}
}

307
epmet-auth/src/main/java/com/epmet/service/impl/PublicUserLoginServiceImpl.java

@ -0,0 +1,307 @@
package com.epmet.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.epmet.common.token.constant.LoginConstant;
import com.epmet.commons.tools.exception.EpmetErrorCode;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.utils.*;
import com.epmet.commons.tools.validator.PhoneValidatorUtils;
import com.epmet.constant.AuthHttpUrlConstant;
import com.epmet.constant.PublicUserLoginConstant;
import com.epmet.constant.SmsTemplateConstant;
import com.epmet.constant.ThirdApiConstant;
import com.epmet.dto.PaCustomerDTO;
import com.epmet.dto.PaUserDTO;
import com.epmet.dto.PaUserWechatDTO;
import com.epmet.dto.form.*;
import com.epmet.dto.result.*;
import com.epmet.feign.EpmetMessageOpenFeignClient;
import com.epmet.jwt.JwtTokenProperties;
import com.epmet.jwt.JwtTokenUtils;
import com.epmet.redis.CaptchaRedis;
import com.epmet.service.PublicUserLoginService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* 描述一下
*
* @author yinzuomei@elink-cn.com
* @date 2020/7/8 18:31
*/
@Service
public class PublicUserLoginServiceImpl implements PublicUserLoginService {
private static final Logger logger = LoggerFactory.getLogger(PublicUserLoginServiceImpl.class);
private static final String SEND_SMS_CODE_ERROR = "发送短信验证码异常,手机号[%s],code[%s],msg[%s]";
@Autowired
private WxMpService wxMpService;
@Autowired
private JwtTokenUtils jwtTokenUtils;
@Autowired
private JwtTokenProperties jwtTokenProperties;
@Autowired
private CpUserDetailRedis cpUserDetailRedis;
@Autowired
private EpmetMessageOpenFeignClient epmetMessageOpenFeignClient;
@Autowired
private CaptchaRedis captchaRedis;
@Override
public UserTokenResultDTO wxCodeToToken(PaWxCodeFormDTO formDTO) {
//1.通过微信code获取用户基本信息
WxMpUser wxMpUser = this.getWxMpUser(formDTO.getWxCode());
WxCodeToTokenFormDTO dto = new WxCodeToTokenFormDTO();
dto.setWxMpUser(wxMpUser);
dto.setSource(formDTO.getSource());
//2.将获取的用户基本信息初始化到数据库
String data = HttpClientManager.getInstance().sendPostByJSON(ThirdApiConstant.THIRD_PAUSER_SAVEUSER, JSON.toJSONString(dto)).getData();
JSONObject toResult = JSON.parseObject(data);
Result result = ConvertUtils.mapToEntity(toResult, Result.class);
if (!result.success()) {
throw new RenException(PublicUserLoginConstant.SAVE_USER_EXCEPTION);
}
Object RegisterResult = result.getData();
JSONObject jsonObject = JSON.parseObject(RegisterResult.toString());
SaveUserResultDTO resultDTO = ConvertUtils.mapToEntity(jsonObject, SaveUserResultDTO.class);
//3.获取用户token
String token = this.generateGovWxmpToken(resultDTO.getUserId());
//4.保存到redis
String openid = wxMpUser.getOpenId();
String unionId = (null == wxMpUser.getUnionId() ? "" : wxMpUser.getUnionId());
this.saveLatestGovTokenDto("", resultDTO.getUserId(), openid, unionId, token);
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
}
private WxMpUser getWxMpUser(String wxCode) {
WxMpUser wxMpUser = null;
try {
WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(wxCode);
wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
} catch (WxErrorException e) {
logger.error("->[getWxMpUser]::error[{}]", "解析微信用户信息失败", e.getMessage());
e.printStackTrace();
throw new RenException("解析微信用户信息失败" + e.getMessage());
}
if (null == wxMpUser ) {
logger.error("wxMpUser is null");
throw new RenException("解析微信用户信息失败 wxMpUser is null");
}
if(StringUtils.isBlank(wxMpUser.getOpenId())){
logger.error("wxMpUser.getOpenId() is null");
throw new RenException("解析微信用户信息失败");
}
/*if(StringUtils.isBlank(wxMpUser.getUnionId())){
logger.error("wxMpUser.getUnionId() is null");
// throw new RenException("解析微信用户信息失败");
}*/
return wxMpUser;
}
/**
* @Description 生成token
**/
private String generateGovWxmpToken(String userId) {
Map<String, Object> map = new HashMap<>();
map.put("app", LoginConstant.APP_PUBLIC);
map.put("client", LoginConstant.CLIENT_MP);
map.put("userId", userId);
String token = jwtTokenUtils.createToken(map);
logger.info("app:" + LoginConstant.APP_PUBLIC + ";client:" + LoginConstant.CLIENT_MP + ";userId:" + userId + ";生成token[" + token + "]");
return token;
}
//保存tokenDto到redis
private void saveLatestGovTokenDto(String customerId, String userId, String openId, String unionId, String token) {
TokenDto tokenDTO = new TokenDto();
int expire = jwtTokenProperties.getExpire();
tokenDTO.setApp(LoginConstant.APP_PUBLIC);
tokenDTO.setClient(LoginConstant.CLIENT_MP);
tokenDTO.setOpenId(openId);
tokenDTO.setUnionId(unionId);
tokenDTO.setToken(token);
//首次初始化时还没有客户
tokenDTO.setCustomerId(customerId);
tokenDTO.setUserId(userId);
tokenDTO.setExpireTime(jwtTokenUtils.getExpiration(token).getTime());
tokenDTO.setUpdateTime(System.currentTimeMillis());
cpUserDetailRedis.set(tokenDTO, expire);
logger.info("截止时间:" + DateUtils.format(jwtTokenUtils.getExpiration(token), "yyyy-MM-dd HH:mm:ss"));
}
/**
* @param formDTO 手机号
* @return com.epmet.commons.tools.utils.Result
* @Author sun
* @Description 公众号登录-发送验证码
**/
@Override
public void sendSmsCode(PublicSendSmsCodeFormDTO formDTO) {
//1、校验手机号是否符合规范
if (!PhoneValidatorUtils.isMobile(formDTO.getPhone())) {
logger.error(String.format(SEND_SMS_CODE_ERROR, formDTO.getPhone(), EpmetErrorCode.ERROR_PHONE.getCode(), EpmetErrorCode.ERROR_PHONE.getMsg()));
throw new RenException(EpmetErrorCode.ERROR_PHONE.getCode());
}
//2、根据数据来源和手机号校验用户是否存在
CheckPaUserFormDTO dto = new CheckPaUserFormDTO();
dto.setPhone(formDTO.getPhone());
dto.setSource(formDTO.getSource());
String data = HttpClientManager.getInstance().sendPostByJSON(ThirdApiConstant.THIRD_PAUSER_CHECKPAUSER, JSON.toJSONString(dto)).getData();
JSONObject toResult = JSON.parseObject(data);
Result result = ConvertUtils.mapToEntity(toResult, Result.class);
if (!result.success()) {
logger.error(String.format(SEND_SMS_CODE_ERROR, formDTO.getPhone(), result.getCode(), result.getMsg()));
throw new RenException(result.getCode());
}
Object RegisterResult = result.getData();
JSONObject jsonObject = JSON.parseObject(RegisterResult.toString());
Map<String,Object> map = (Map)jsonObject.get("paUserResult");
PaUserDTO userDTO = ConvertUtils.mapToEntity(map, PaUserDTO.class);
//登陆
if (formDTO.getIsLogon() && null == userDTO) {
throw new RenException(EpmetErrorCode.PUBLIC_NOT_EXISTS.getCode());
}
//注册
if (!formDTO.getIsLogon() && null != userDTO) {
throw new RenException(EpmetErrorCode.MOBILE_USED.getCode());
}
//3、发送短信验证码
SendVerificationCodeFormDTO sendVerificationCodeFormDTO = new SendVerificationCodeFormDTO();
sendVerificationCodeFormDTO.setMobile(formDTO.getPhone());
//登陆或注册对应的短息模板
sendVerificationCodeFormDTO.setAliyunTemplateCode(formDTO.getIsLogon() ? SmsTemplateConstant.LGOIN_CONFIRM : SmsTemplateConstant.USER_REGISTER);
Result<SendVerificationCodeResultDTO> smsCodeResult = epmetMessageOpenFeignClient.sendVerificationCode(sendVerificationCodeFormDTO);
if (!smsCodeResult.success()) {
logger.error(String.format(SEND_SMS_CODE_ERROR, formDTO.getPhone(), smsCodeResult.getCode(), smsCodeResult.getMsg()));
throw new RenException(smsCodeResult.getCode());
}
//4、保存短信验证码(删除现有短信验证码、将新的短信验证码存入Redis)
captchaRedis.savePublicSmsCode(formDTO, smsCodeResult.getData().getCode());
logger.info(String.format("发送短信验证码成功,手机号[%s]", formDTO.getPhone()));
}
/**
* @param formDTO
* @return com.epmet.commons.tools.utils.Result
* @Author sun
* @Description 公众号-手机验证码登陆
**/
@Override
public UserTokenResultDTO loginByPhone(TokenDto tokenDTO, LoginByPhoneFormDTO formDTO) {
//1.根据数据来源和手机号查询用户、客户信息
CheckPaUserFormDTO dto = new CheckPaUserFormDTO();
dto.setPhone(formDTO.getPhone());
dto.setSource(formDTO.getSource());
String data = HttpClientManager.getInstance().sendPostByJSON(ThirdApiConstant.THIRD_PAUSER_CHECKPAUSER, JSON.toJSONString(dto)).getData();
JSONObject toResult = JSON.parseObject(data);
Result result = ConvertUtils.mapToEntity(toResult, Result.class);
if (!result.success()) {
logger.error(String.format("手机验证码登录异常,手机号[%s],code[%s],msg[%s]", formDTO.getPhone(), result.getCode(), result.getMsg()));
throw new RenException(result.getCode());
}
Object RegisterResult = result.getData();
JSONObject jsonObject = JSON.parseObject(RegisterResult.toString());
//2.用户不存在时不允许登陆
Map<String,Object> map1 = (Map)jsonObject.get("paUserResult");
PaUserDTO userDTO = ConvertUtils.mapToEntity(map1, PaUserDTO.class);
if (null == userDTO || StringUtils.isBlank(userDTO.getId())) {
throw new RenException(EpmetErrorCode.PUBLIC_NOT_EXISTS.getCode());
}
//3.校验验证码是否正确
String rightSmsCode = captchaRedis.getPublicSmsCode(formDTO.getPhone());
if (!formDTO.getSmsCode().equals(rightSmsCode)) {
logger.error(String.format("验证码错误code[%s],msg[%s]", EpmetErrorCode.MOBILE_CODE_ERROR.getCode(), EpmetErrorCode.MOBILE_CODE_ERROR.getMsg()));
throw new RenException(EpmetErrorCode.MOBILE_CODE_ERROR.getCode());
}
//生成的token是根据登陆手机号对应的user生成的token,访问记录表记录的是那个user根据自己或他人的手机号登陆的
//4.直接生成一个新的token放入缓存中(不管缓存中是否存在旧的token,都重新生成)
//4-1.生成token
String token = this.generateGovWxmpToken(userDTO.getId());
//4-2.判断是否存在信息,给customerId赋值
Map<String,Object> map2 = (Map)jsonObject.get("paCustomerResult");
PaCustomerDTO customerDTO = ConvertUtils.mapToEntity(map2, PaCustomerDTO.class);
String customerId = "";
if (null != customerDTO && !StringUtils.isBlank(customerDTO.getId())) {
customerId = customerDTO.getId();
}
//4-3.token存入redis
Map<String,Object> map3 = (Map)jsonObject.get("paUserWechatResult");
PaUserWechatDTO wechatDTO = ConvertUtils.mapToEntity(map3, PaUserWechatDTO.class);
String openid = wechatDTO.getWxOpenId();
String unionId = (null == wechatDTO.getUnionId() ? "" : wechatDTO.getUnionId());
this.saveLatestGovTokenDto(customerId, userDTO.getId(), openid, unionId, token);
//5.登陆成功,访问记录表新增访问记录(访问记录新增失败不应影响用户登陆)
SaveUserVisitedFormDTO visited = new SaveUserVisitedFormDTO();
visited.setUserId(userDTO.getId());
visited.setLogonUserId(tokenDTO.getUserId());
visited.setPhone(formDTO.getPhone());
visited.setSource(formDTO.getSource());
String data1 = HttpClientManager.getInstance().sendPostByJSON(ThirdApiConstant.THIRD_PAUSERVISITED_SAVEUSERVISITED, JSON.toJSONString(visited)).getData();
JSONObject json = JSON.parseObject(data1);
Result visitedResult = ConvertUtils.mapToEntity(json, Result.class);
if (!visitedResult.success()) {
logger.error(PublicUserLoginConstant.SAVE_VISITED_EXCEPTION);
}
//6.返回token
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 公众号-手机号注册
**/
@Override
public UserTokenResultDTO register(RegisterFormDTO formDTO) {
//1.调用epmet-third服务,完成信息注册
String data = HttpClientManager.getInstance().sendPostByJSON(AuthHttpUrlConstant.REGISTER_URL, JSON.toJSONString(formDTO)).getData();
JSONObject toResult = JSON.parseObject(data);
Result result = ConvertUtils.mapToEntity(toResult, Result.class);
if (!result.success()) {
logger.error(String.format("调用epmet_third服务初始化用户信息失败,数据来源[%s],手机号[%s],userId:[%S]", formDTO.getSource(), formDTO.getPhone(), formDTO.getUserId()));
throw new RenException(result.getCode());
}
Object RegisterResult = result.getData();
JSONObject jsonObject = JSON.parseObject(RegisterResult.toString());
RegisterResultDTO resultDTO = ConvertUtils.mapToEntity(jsonObject, RegisterResultDTO.class);
//2.直接生成一个新的token放入缓存中(不管缓存中是否存在旧的token,都重新生成)
//2-1.生成token
String token = this.generateGovWxmpToken(resultDTO.getUserId());
//2-2.token存入redis
String openid = resultDTO.getOpenId();
String unionId = (null == resultDTO.getUnionId() ? "" : resultDTO.getUnionId());
this.saveLatestGovTokenDto("", resultDTO.getUserId(), openid, unionId, token);
//3.返回token
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
}
}

546
epmet-auth/src/main/java/com/epmet/service/impl/ThirdLoginServiceImpl.java

@ -0,0 +1,546 @@
package com.epmet.service.impl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.epmet.common.token.constant.LoginConstant;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.exception.EpmetErrorCode;
import com.epmet.commons.tools.exception.ExceptionUtils;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.security.dto.GovTokenDto;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.security.password.PasswordUtils;
import com.epmet.commons.tools.utils.*;
import com.epmet.constant.AuthHttpUrlConstant;
import com.epmet.dto.*;
import com.epmet.dto.form.*;
import com.epmet.dto.result.*;
import com.epmet.feign.EpmetUserOpenFeignClient;
import com.epmet.feign.GovOrgOpenFeignClient;
import com.epmet.jwt.JwtTokenProperties;
import com.epmet.jwt.JwtTokenUtils;
import com.epmet.redis.CaptchaRedis;
import com.epmet.service.ThirdLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author sun
* @Description 第三方-居民端政府端登陆服务
*/
@Slf4j
@Service
public class ThirdLoginServiceImpl implements ThirdLoginService {
private static final Logger logger = LoggerFactory.getLogger(ThirdLoginServiceImpl.class);
@Autowired
private JwtTokenUtils jwtTokenUtils;
@Autowired
private CaptchaRedis captchaRedis;
@Autowired
private JwtTokenProperties jwtTokenProperties;
@Autowired
private CpUserDetailRedis cpUserDetailRedis;
@Autowired
private EpmetUserOpenFeignClient epmetUserOpenFeignClient;
@Autowired
private GovOrgOpenFeignClient govOrgOpenFeignClient;
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-居民端微信小程序登录
**/
@Override
public UserTokenResultDTO resiLogin(LoginFormDTO formDTO) {
//1.调用epmet_third服务,校验appId是否有效以及是否授权,校验通过的调用微信API获取用户基本信息
WxLoginFormDTO resiLoginFormDTO = new WxLoginFormDTO();
resiLoginFormDTO.setAppId(formDTO.getAppId());
resiLoginFormDTO.setWxCode(formDTO.getWxCode());
UserWechatDTO userWechatDTO = this.getUserWeChat(resiLoginFormDTO);
//2.调用epmet-user服务,新增用户信息(先判断用户是否存在,不存在则新增存在则更新)
WxUserFormDTO wxUserFormDTO = new WxUserFormDTO();
wxUserFormDTO.setWechatDTO(userWechatDTO);
wxUserFormDTO.setApp(formDTO.getApp());
Result<UserDTO> userResult = epmetUserOpenFeignClient.saveWxUser(wxUserFormDTO);
if (!userResult.success()) {
throw new RenException(userResult.getCode());
}
UserDTO userDTO = userResult.getData();
//3.生成业务token
String userId = userDTO.getId();
String token = this.generateToken(formDTO, userId);
//4.存放Redis
this.saveTokenDto(formDTO, userId, userWechatDTO, token);
//5.接口返参
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
}
/**
* @Description 居民端登陆生成业务token的key
**/
private String generateToken(LoginCommonFormDTO formDTO, String userId) {
Map<String, Object> map = new HashMap<>();
map.put("app", formDTO.getApp());
map.put("client", formDTO.getClient());
map.put("userId", userId);
String token = jwtTokenUtils.createToken(map);
logger.info("app:" + formDTO.getApp() + ";client:" + formDTO.getClient() + ";userId:" + userId + ";生成token[" + token + "]");
return token;
}
/**
* @Description 将token存入redis
**/
private String saveTokenDto(LoginCommonFormDTO formDTO, String userId, UserWechatDTO userWechatDTO, String token) {
int expire = jwtTokenProperties.getExpire();
TokenDto tokenDto = new TokenDto();
tokenDto.setApp(formDTO.getApp());
tokenDto.setClient(formDTO.getClient());
tokenDto.setUserId(userId);
tokenDto.setOpenId(userWechatDTO.getWxOpenId());
tokenDto.setSessionKey(userWechatDTO.getSessionKey());
tokenDto.setUnionId(userWechatDTO.getUnionId());
tokenDto.setToken(token);
tokenDto.setUpdateTime(System.currentTimeMillis());
tokenDto.setExpireTime(jwtTokenUtils.getExpiration(token).getTime());
cpUserDetailRedis.set(tokenDto, expire);
logger.info("截止时间:" + DateUtils.format(jwtTokenUtils.getExpiration(token), "yyyy-MM-dd HH:mm:ss"));
return token;
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-政府端微信小程序登录
**/
@Override
public UserTokenResultDTO workLogin(LoginFormDTO formDTO) {
//1.调用epmet_third服务,校验appId是否有效以及是否授权,校验通过的调用微信API获取用户基本信息
WxLoginFormDTO resiLoginFormDTO = new WxLoginFormDTO();
resiLoginFormDTO.setAppId(formDTO.getAppId());
resiLoginFormDTO.setWxCode(formDTO.getWxCode());
UserWechatDTO userWechatDTO = this.getUserWeChat(resiLoginFormDTO);
//2.根据openid查询用户是否存在历史登陆信息
Result<StaffLatestAgencyResultDTO> latestStaffWechat = epmetUserOpenFeignClient.getLatestStaffWechatLoginRecord(userWechatDTO.getWxOpenId());
if (!latestStaffWechat.success() || null == latestStaffWechat.getData()) {
logger.error(String.format("没有获取到用户最近一次登录账户信息,code[%s],msg[%s]", EpmetErrorCode.PLEASE_LOGIN.getCode(), EpmetErrorCode.PLEASE_LOGIN.getMsg()));
throw new RenException(EpmetErrorCode.PLEASE_LOGIN.getCode());
}
StaffLatestAgencyResultDTO staffLatestAgencyResultDTO = latestStaffWechat.getData();
//3.记录staff_wechat
this.savestaffwechat(staffLatestAgencyResultDTO.getStaffId(), userWechatDTO.getWxOpenId());
//4.记录登录日志
this.saveStaffLoginRecord(staffLatestAgencyResultDTO);
//5.获取用户token
String token = this.generateGovWxmpToken(staffLatestAgencyResultDTO.getStaffId());
//6.保存到redis
this.saveLatestGovTokenDto(staffLatestAgencyResultDTO, userWechatDTO, token);
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
}
/**
* @param userId openid
* @return
* @Author sun
* @Description 保存微信和当前登录用户关系
**/
private Result savestaffwechat(String userId, String openid) {
StaffWechatFormDTO staffWechatFormDTO = new StaffWechatFormDTO();
staffWechatFormDTO.setUserId(userId);
staffWechatFormDTO.setWxOpenId(openid);
return epmetUserOpenFeignClient.saveStaffWechat(staffWechatFormDTO);
}
/**
* @param latestStaffWechatLoginDTO
* @return
* @Author sun
* @Description 保存登录日志
**/
private Result saveStaffLoginRecord(StaffLatestAgencyResultDTO latestStaffWechatLoginDTO) {
StaffLoginAgencyRecordFormDTO staffLoginAgencyRecordFormDTO = new StaffLoginAgencyRecordFormDTO();
staffLoginAgencyRecordFormDTO.setCustomerId(latestStaffWechatLoginDTO.getCustomerId());
staffLoginAgencyRecordFormDTO.setStaffId(latestStaffWechatLoginDTO.getStaffId());
staffLoginAgencyRecordFormDTO.setWxOpenId(latestStaffWechatLoginDTO.getWxOpenId());
staffLoginAgencyRecordFormDTO.setMobile(latestStaffWechatLoginDTO.getMobile());
staffLoginAgencyRecordFormDTO.setAgencyId(latestStaffWechatLoginDTO.getAgencyId());
Result staffLoginRecordResult = epmetUserOpenFeignClient.saveStaffLoginRecord(staffLoginAgencyRecordFormDTO);
return staffLoginRecordResult;
}
/**
* @Description 生成政府端小程序业务token Key
* @Author sun
**/
private String generateGovWxmpToken(String staffId) {
Map<String, Object> map = new HashMap<>();
map.put("app", LoginConstant.APP_GOV);
map.put("client", LoginConstant.CLIENT_WXMP);
map.put("userId", staffId);
String token = jwtTokenUtils.createToken(map);
logger.info("app:" + LoginConstant.APP_GOV + ";client:" + LoginConstant.CLIENT_WXMP + ";userId:" + staffId + ";生成token[" + token + "]");
return token;
}
/**
* @Description 保存tokenDto到redis
* @Author sun
**/
private void saveLatestGovTokenDto(StaffLatestAgencyResultDTO staffLatestAgency, UserWechatDTO userWechatDTO, String token) {
int expire = jwtTokenProperties.getExpire();
GovTokenDto govTokenDto = new GovTokenDto();
govTokenDto.setApp(LoginConstant.APP_GOV);
govTokenDto.setClient(LoginConstant.CLIENT_WXMP);
govTokenDto.setUserId(staffLatestAgency.getStaffId());
govTokenDto.setOpenId(userWechatDTO.getWxOpenId());
govTokenDto.setSessionKey(userWechatDTO.getSessionKey());
govTokenDto.setUnionId(userWechatDTO.getUnionId());
govTokenDto.setToken(token);
govTokenDto.setUpdateTime(System.currentTimeMillis());
govTokenDto.setExpireTime(jwtTokenUtils.getExpiration(token).getTime());
govTokenDto.setRootAgencyId(staffLatestAgency.getAgencyId());
govTokenDto.setCustomerId(staffLatestAgency.getCustomerId());
//设置部门,网格,角色列表
govTokenDto.setDeptIdList(getDeptartmentIdList(staffLatestAgency.getStaffId()));
govTokenDto.setGridIdList(getGridIdList(staffLatestAgency.getStaffId()));
CustomerAgencyDTO agency = getAgencyByStaffId(staffLatestAgency.getStaffId());
if (agency != null) {
govTokenDto.setAgencyId(agency.getId());
govTokenDto.setRoleList(queryGovStaffRoles(staffLatestAgency.getStaffId(), agency.getId()));
}
govTokenDto.setOrgIdPath(getOrgIdPath(staffLatestAgency.getStaffId()));
cpUserDetailRedis.set(govTokenDto, expire);
logger.info("截止时间:" + DateUtils.format(jwtTokenUtils.getExpiration(token), "yyyy-MM-dd HH:mm:ss"));
}
public Set<String> getDeptartmentIdList(String staffId) {
try {
Result<List<DepartmentListResultDTO>> deptListResult = govOrgOpenFeignClient.getDepartmentListByStaffId(staffId);
if (deptListResult.success()) {
if (!CollectionUtils.isEmpty(deptListResult.getData())) {
Set<String> deptIdLists = deptListResult.getData().stream().map(dept -> dept.getDepartmentId()).collect(Collectors.toSet());
return deptIdLists;
}
} else {
logger.error("登录:查询部门列表,远程调用返回错误:{}", deptListResult.getMsg());
}
} catch (Exception e) {
String errorStackTrace = ExceptionUtils.getErrorStackTrace(e);
logger.error("登录:查询部门列表异常:{}", errorStackTrace);
}
return null;
}
/**
* 根据工作人员ID查询网格ID列表
*
* @param staffId
* @return
*/
public Set<String> getGridIdList(String staffId) {
Result<List<GridByStaffResultDTO>> result = govOrgOpenFeignClient.listGridsbystaffid(staffId);
if (!result.success()) {
logger.error("登录:查询网格列表,远程调用返回错误:{}", result.getMsg());
return null;
} else {
List<GridByStaffResultDTO> grids = result.getData();
return grids.stream().map(grid -> grid.getGridId()).collect(Collectors.toSet());
}
}
/**
* 根据staffId查询所属的组织机构
*
* @param staffId
*/
public CustomerAgencyDTO getAgencyByStaffId(String staffId) {
Result<CustomerAgencyDTO> result = govOrgOpenFeignClient.getAgencyByStaff(staffId);
if (!result.success()) {
logger.error("登录:查询登录人所属的机关OrgIdPath失败:{}", result.getMsg());
return null;
}
return result.getData();
}
/**
* 查询人员在某机关单位下的角色列表
*
* @param staffId orgId
*/
public List<GovTokenDto.Role> queryGovStaffRoles(String staffId, String orgId) {
StaffRoleFormDTO formDTO = new StaffRoleFormDTO();
formDTO.setStaffId(staffId);
formDTO.setOrgId(orgId);
Result<List<GovStaffRoleDTO>> gridResult = epmetUserOpenFeignClient.getRolesOfStaff(formDTO);
if (!CollectionUtils.isEmpty(gridResult.getData())) {
//return gridResult.getData().stream().map(role -> role.getId()).collect(Collectors.toSet());
return ConvertUtils.sourceToTarget(gridResult.getData(), GovTokenDto.Role.class);
}
return null;
}
/**
* 查询工作人员的OrgIdPath
*
* @param staffId
* @return
*/
public String getOrgIdPath(String staffId) {
Result<CustomerAgencyDTO> result = govOrgOpenFeignClient.getAgencyByStaff(staffId);
if (!result.success()) {
logger.error("登录:查询登录人所属的机关OrgIdPath失败:{}", result.getMsg());
return null;
}
CustomerAgencyDTO agency = result.getData();
if (agency != null) {
if ("0".equals(agency.getPid())) {
// 顶级
return agency.getId();
} else {
return agency.getPids().concat(":").concat(agency.getId());
}
}
return null;
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-选择组织进入首页
**/
@Override
public UserTokenResultDTO enterOrg(ThirdWxmpEnteOrgFormDTO formDTO) {
//1、需要校验要登录的客户,是否被禁用
CustomerStaffFormDTO customerStaffFormDTO = new CustomerStaffFormDTO();
customerStaffFormDTO.setCustomerId(formDTO.getCustomerId());
customerStaffFormDTO.setMobile(formDTO.getMobile());
Result<CustomerStaffDTO> customerStaffDTOResult = epmetUserOpenFeignClient.getCustomerStaffInfo(customerStaffFormDTO);
if (!customerStaffDTOResult.success() || null == customerStaffDTOResult.getData()) {
logger.error(String.format("获取工作人员信息失败,手机号[%s],客户id:[%s],code[%s],msg[%s]", formDTO.getMobile(), formDTO.getCustomerId(), customerStaffDTOResult.getCode(), customerStaffDTOResult.getMsg()));
throw new RenException(customerStaffDTOResult.getCode());
}
CustomerStaffDTO customerStaff = customerStaffDTOResult.getData();
//2020.7.24 获取微信信息接口调整,改调用微信api的方式 sun start
//2.调用epmet_third服务,校验appId是否有效以及是否授权,校验通过的调用微信API获取用户基本信息
WxLoginFormDTO resiLoginFormDTO = new WxLoginFormDTO();
resiLoginFormDTO.setAppId(formDTO.getAppId());
resiLoginFormDTO.setWxCode(formDTO.getWxCode());
UserWechatDTO userWechatDTO = this.getUserWeChat(resiLoginFormDTO);
WxMaJscode2SessionResult wxMaJscode2SessionResult = new WxMaJscode2SessionResult();
wxMaJscode2SessionResult.setOpenid(userWechatDTO.getWxOpenId());
wxMaJscode2SessionResult.setSessionKey(userWechatDTO.getSessionKey());
wxMaJscode2SessionResult.setUnionid("");
// end
//3、记录staff_wechat,并记录用户激活状态,激活时间
this.savestaffwechat(customerStaff.getUserId(), userWechatDTO.getWxOpenId());
//4、记录登录日志
StaffLatestAgencyResultDTO staffLatestAgencyResultDTO = new StaffLatestAgencyResultDTO();
staffLatestAgencyResultDTO.setCustomerId(formDTO.getCustomerId());
staffLatestAgencyResultDTO.setStaffId(customerStaff.getUserId());
staffLatestAgencyResultDTO.setWxOpenId(userWechatDTO.getWxOpenId());
staffLatestAgencyResultDTO.setMobile(formDTO.getMobile());
staffLatestAgencyResultDTO.setAgencyId(formDTO.getRootAgencyId());
this.saveStaffLoginRecord(staffLatestAgencyResultDTO);
//5.1、获取用户token
String token = this.generateGovWxmpToken(customerStaff.getUserId());
//5.2、保存到redis
StaffLatestAgencyResultDTO staffLatestAgency = new StaffLatestAgencyResultDTO();
staffLatestAgency.setAgencyId(formDTO.getRootAgencyId());
staffLatestAgency.setCustomerId(formDTO.getCustomerId());
staffLatestAgency.setStaffId(customerStaff.getUserId());
this.saveLatestGovTokenDto(staffLatestAgency, userWechatDTO, token);
UserTokenResultDTO userTokenResultDTO = new UserTokenResultDTO();
userTokenResultDTO.setToken(token);
return userTokenResultDTO;
}
/**
* @param formDTO
* @return
* @Author sun
* @Description 单客户-手机验证码获取组织
**/
@Override
public List<StaffOrgsResultDTO> getMyOrg(ThirdStaffOrgsFormDTO formDTO) {
//0、验证码是否正确
String rightSmsCode = captchaRedis.getSmsCode(formDTO.getMobile());
if (!formDTO.getSmsCode().equals(rightSmsCode)) {
logger.error(String.format("验证码错误code[%s],msg[%s]",EpmetErrorCode.MOBILE_CODE_ERROR.getCode(),EpmetErrorCode.MOBILE_CODE_ERROR.getMsg()));
throw new RenException(EpmetErrorCode.MOBILE_CODE_ERROR.getCode());
}
//1.根据appId查询对应客户Id
PaCustomerDTO customer = this.getCustomerInfo(formDTO.getAppId());
//7.28 根据appId只能存在一个客户Id,后边的批量操作逻辑
//2.根据手机号查询到用户信息
ThirdCustomerStaffFormDTO dto = new ThirdCustomerStaffFormDTO();
dto.setCustomerId(customer.getId());
dto.setMobile(formDTO.getMobile());
Result<List<CustomerStaffDTO>> customerStaffResult = epmetUserOpenFeignClient.getCustsomerStaffByIdAndPhone(dto);
if (!customerStaffResult.success()) {
logger.error(String.format("手机验证码登录异常,手机号[%s],code[%s],msg[%s]", formDTO.getMobile(), customerStaffResult.getCode(), customerStaffResult.getMsg()));
throw new RenException(customerStaffResult.getCode());
}
//3、查询用户所有的组织信息
List<String> customerIdList = new ArrayList<>();
for (CustomerStaffDTO customerStaffDTO : customerStaffResult.getData()) {
customerIdList.add(customerStaffDTO.getCustomerId());
}
StaffOrgFormDTO staffOrgFormDTO = new StaffOrgFormDTO();
staffOrgFormDTO.setCustomerIdList(customerIdList);
Result<List<StaffOrgsResultDTO>> result = govOrgOpenFeignClient.getStaffOrgList(staffOrgFormDTO);
if(result.success()&&null!=result.getData()){
return result.getData();
}
logger.error(String .format("手机验证码获取组织,调用%s服务失败,入参手机号%s,验证码%s,返回错误码%s,错误提示信息%s", ServiceConstant.GOV_ORG_SERVER,formDTO.getMobile(),formDTO.getSmsCode(),result.getCode(),result.getMsg()));
return new ArrayList<>();
}
/**
* @param formDTO
* @return
* @author sun
* @description 单客户-手机号密码获取组织
**/
@Override
public List<StaffOrgsResultDTO> getMyOrgByPassword(ThirdStaffOrgsFormDTO formDTO) {
//0.根据appId查询对应客户Id
// Result<PublicCustomerResultDTO> resultDTO = epmetThirdFeignClient.getCustomerMsg(formDTO.getAppId());
PaCustomerDTO customer = this.getCustomerInfo(formDTO.getAppId());
//7.28 上边根据appId只能锁定一条客户id,后边的批量循环操作暂不做调整,还是使用之前的代码 sun
//1、根据手机号查询到用户信息
ThirdCustomerStaffFormDTO dto = new ThirdCustomerStaffFormDTO();
dto.setCustomerId(customer.getId());
dto.setMobile(formDTO.getMobile());
Result<List<CustomerStaffDTO>> customerStaffResult = epmetUserOpenFeignClient.getCustsomerStaffByIdAndPhone(dto);
if (!customerStaffResult.success()) {
logger.error(String.format("手机密码登录异常,手机号[%s],code[%s],msg[%s]", formDTO.getMobile(), customerStaffResult.getCode(), customerStaffResult.getMsg()));
throw new RenException(customerStaffResult.getCode());
}
//2、密码是否正确
List<CustomerStaffDTO> customerStaffList=customerStaffResult.getData();
//3、查询用户所有的组织信息
List<String> customerIdList = new ArrayList<>();
//是否设置过密码
boolean havePasswordFlag=false;
//密码是否正确
boolean passwordRightFlag=false;
for (CustomerStaffDTO customerStaffDTO : customerStaffList) {
if(StringUtils.isNotBlank(customerStaffDTO.getPassword())){
havePasswordFlag=true;
}else{
logger.warn(String.format("当前用户:手机号%s,客户Id%s下未设置密码.",formDTO.getMobile(),customerStaffDTO.getCustomerId()));
continue;
}
if (!PasswordUtils.matches(formDTO.getPassword(), customerStaffDTO.getPassword())) {
logger.warn(String.format("当前用户:手机号%s,客户Id%s密码匹配错误.",formDTO.getMobile(),customerStaffDTO.getCustomerId()));
}else{
logger.warn(String.format("当前用户:手机号%s,客户Id%s密码匹配正确.",formDTO.getMobile(),customerStaffDTO.getCustomerId()));
passwordRightFlag=true;
customerIdList.add(customerStaffDTO.getCustomerId());
}
}
//根据手机号查出来所有用户,密码都为空,表明用户未激活账户,未设置密码
if(!havePasswordFlag){
logger.error(String.format("当前手机号(%s)下所有账户都未设置密码,请先使用验证码登录激活账户",formDTO.getMobile()));
throw new RenException(EpmetErrorCode.PASSWORD_ERROR.getCode());
}
//密码错误
if(!passwordRightFlag){
logger.error(String.format("根据当前手机号(%s)密码未找到所属组织,密码错误",formDTO.getMobile()));
throw new RenException(EpmetErrorCode.PASSWORD_ERROR.getCode());
}
StaffOrgFormDTO staffOrgFormDTO = new StaffOrgFormDTO();
staffOrgFormDTO.setCustomerIdList(customerIdList);
Result<List<StaffOrgsResultDTO>> result = govOrgOpenFeignClient.getStaffOrgList(staffOrgFormDTO);
if(result.success()&&null!=result.getData()){
return result.getData();
}
logger.error(String .format("手机验证码获取组织,调用%s服务失败,入参手机号%s,密码%s,返回错误码%s,错误提示信息%s",
ServiceConstant.GOV_ORG_SERVER,
formDTO.getMobile(),
formDTO.getPassword(),
result.getCode(),
result.getMsg()));
return new ArrayList<>();
}
/**
* @Description 获取客户信息
* @param appId
* @author zxc
*/
public PaCustomerDTO getCustomerInfo(String appId){
JSONObject jsonObject = new JSONObject();
String data = HttpClientManager.getInstance().sendPostByJSON(AuthHttpUrlConstant.CUSTOMER_MSG_URL + appId, JSON.toJSONString(jsonObject)).getData();
logger.info("ThirdLoginServiceImpl.getCustomerInfo:httpclient->url:"+AuthHttpUrlConstant.CUSTOMER_MSG_URL+",结果->"+data);
JSONObject toResult = JSON.parseObject(data);
Result mapToResult = ConvertUtils.mapToEntity(toResult, Result.class);
if (!mapToResult.success()) {
logger.error(String.format("根据appId查询客户Id失败,对应appId->" + appId));
throw new RenException(mapToResult.getMsg());
}
Object PublicCustomerResultDTO = mapToResult.getData();
JSONObject json = JSON.parseObject(PublicCustomerResultDTO.toString());
Map<String,Object> map = (Map)json.get("customer");
PaCustomerDTO customer = ConvertUtils.mapToEntity(map, PaCustomerDTO.class);
logger.info("小程序登陆third服务获取客户用户信息PaCustomerDTO->"+customer);
return customer;
}
/**
* @Description 获取UserWechatDTO
* @param resiLoginFormDTO
* @author zxc
*/
public UserWechatDTO getUserWeChat(WxLoginFormDTO resiLoginFormDTO){
String data = HttpClientManager.getInstance().sendPostByJSON(AuthHttpUrlConstant.RESI_AND_WORK_LOGIN_URL, JSON.toJSONString(resiLoginFormDTO)).getData();
logger.info("ThirdLoginServiceImpl.getUserWeChat:httpclient->url:"+AuthHttpUrlConstant.RESI_AND_WORK_LOGIN_URL+",结果->"+data);
JSONObject toResult = JSON.parseObject(data);
Result mapToResult = ConvertUtils.mapToEntity(toResult, Result.class);
if (!mapToResult.success()) {
logger.error("居民端小程序登陆,调用epmet_third服务获取数据失败");
throw new RenException(mapToResult.getCode());
}
Object UserWeChatDTO = mapToResult.getData();
JSONObject json = JSON.parseObject(UserWeChatDTO.toString());
UserWechatDTO userWechatDTO = ConvertUtils.mapToEntity(json, UserWechatDTO.class);
logger.info("小程序登陆third服务获取微信用户信息userWechatDTO->"+userWechatDTO);
return userWechatDTO;
}
}

43
epmet-auth/src/main/resources/bootstrap.yml

@ -72,8 +72,6 @@ feign:
loggerLevel: BASIC
httpclient:
enabled: true
max-connections: 200
max-connections-per-route: 50
hystrix:
command:
@ -87,8 +85,39 @@ ribbon:
ReadTimeout: 300000
ConnectTimeout: 300000
jwt:
#秘钥
# secret: 7016867071f0ebf1c46f123eaaf4b9d6[elink.epmet]
secret: f4e2e52034348f86b67cde5[www.renren.io]
#token有效时长,默认7天,单位秒
expire: 604800
token:
#秘钥
secret: 7016867071f0ebf1c46f123eaaf4b9d6[elink.epmet]
#token有效时长,默认7天,单位秒
expire: 604800
wx:
mp:
configs:
- appId: @wx.mp.configs.appId@
secret: @wx.mp.configs.secret@
token: @wx.mp.configs.token@
aesKey: @wx.mp.configs.aesKey@
ma:
configs:
- appid: @resi.wx.ma.appId@
secret: @resi.wx.ma.secret@
token: #微信小程序消息服务器配置的token
aesKey: #微信小程序消息服务器配置的EncodingAESKey
msgDataFormat: JSON
- appid: @gov.wx.ma.appId@
secret: @gov.wx.ma.secret@
token: #微信小程序消息服务器配置的token
aesKey: #微信小程序消息服务器配置的EncodingAESKey
msgDataFormat: JSON
# - appid: @oper.wx.ma.appId@
# secret: @oper.wx.ma.secret@
# token: #微信小程序消息服务器配置的token
# aesKey: #微信小程序消息服务器配置的EncodingAESKey
# msgDataFormat: JSON
appId:
# 党群e事通-居民端小程序配置appId
resi: @resi.wx.ma.appId@
# 党群e事通-政府端小程序配置的appId
gov: @gov.wx.ma.appId@
# 党群e事通-运营端小程序配置的appId
#oper: @oper.wx.ma.appId@

13
epmet-auth/src/main/resources/logback-spring.xml

@ -4,6 +4,11 @@
<property name="log.path" value="logs/auth"/>
<springProperty scope="context" name="appname" source="spring.application.name"/>
<!-- 日志上下文名称 -->
<contextName>${appname}</contextName>
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN"
value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
@ -28,7 +33,7 @@
<file>${log.path}/debug.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%contextName] [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
@ -55,7 +60,7 @@
<file>${log.path}/info.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%contextName] [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
@ -82,7 +87,7 @@
<file>${log.path}/warn.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%contextName] [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
@ -108,7 +113,7 @@
<file>${log.path}/error.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%contextName] [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->

101
epmet-auth/src/test/java/com/epmet/TokenGenTest.java

@ -0,0 +1,101 @@
package com.epmet;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.epmet.common.token.constant.LoginConstant;
import com.epmet.commons.tools.security.dto.GovTokenDto;
import com.epmet.commons.tools.utils.CpUserDetailRedis;
import com.epmet.commons.tools.utils.DateUtils;
import com.epmet.dto.CustomerAgencyDTO;
import com.epmet.dto.result.StaffLatestAgencyResultDTO;
import com.epmet.jwt.JwtTokenProperties;
import com.epmet.jwt.JwtTokenUtils;
import com.epmet.service.impl.GovLoginServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TokenGenTest {
@Autowired
private JwtTokenProperties jwtTokenProperties;
@Autowired
private JwtTokenUtils jwtTokenUtils;
@Autowired
private CpUserDetailRedis cpUserDetailRedis;
@Autowired
private GovLoginServiceImpl govLoginService;
@Test
public void genToken() {
String staffId = "wxz";
String tokenStr = generateGovWxmpToken(staffId);
int expire = jwtTokenProperties.getExpire();
GovTokenDto govTokenDto = new GovTokenDto();
govTokenDto.setApp(LoginConstant.APP_GOV);
govTokenDto.setClient(LoginConstant.CLIENT_WXMP);
govTokenDto.setUserId(staffId);
govTokenDto.setOpenId("");
govTokenDto.setSessionKey("");
govTokenDto.setUnionId("");
govTokenDto.setToken(tokenStr);
govTokenDto.setUpdateTime(System.currentTimeMillis());
govTokenDto.setExpireTime(jwtTokenUtils.getExpiration(tokenStr).getTime());
govTokenDto.setAgencyId("1");
govTokenDto.setDeptIdList(new HashSet<>(Arrays.asList("1","2","3")));
govTokenDto.setCustomerId("f76def116c9c2dc0269cc17867af122c");
cpUserDetailRedis.set(govTokenDto, expire);
}
@Test
public void saveLatestGovTokenDto() {
String staffId = "wxz";
String token = generateGovWxmpToken(staffId);
int expire = jwtTokenProperties.getExpire();
GovTokenDto govTokenDto = new GovTokenDto();
govTokenDto.setApp(LoginConstant.APP_GOV);
govTokenDto.setClient(LoginConstant.CLIENT_WXMP);
govTokenDto.setToken(token);
govTokenDto.setUserId(staffId);
govTokenDto.setUpdateTime(System.currentTimeMillis());
govTokenDto.setExpireTime(jwtTokenUtils.getExpiration(token).getTime());
//govTokenDto.setAgencyId(staffLatestAgency.getAgencyId());
//govTokenDto.setCustomerId(staffLatestAgency.getCustomerId());
//设置部门,网格,角色列表
govTokenDto.setDeptIdList(govLoginService.getDeptartmentIdList(staffId));
govTokenDto.setGridIdList(govLoginService.getGridIdList(staffId));
CustomerAgencyDTO agency = govLoginService.getAgencyByStaffId(staffId);
if (agency != null) {
govTokenDto.setRoleList(govLoginService.queryGovStaffRoles(staffId, agency.getId()));
}
govTokenDto.setOrgIdPath(govLoginService.getOrgIdPath(staffId));
cpUserDetailRedis.set(govTokenDto, expire);
}
/**
* @Description 生成token
* @Date 2020/4/18 23:04
**/
private String generateGovWxmpToken(String staffId) {
Map<String, Object> map = new HashMap<>();
map.put("app", LoginConstant.APP_GOV);
map.put("client", LoginConstant.CLIENT_WXMP);
map.put("userId", staffId);
String token = jwtTokenUtils.createToken(map);
return token;
}
}

6
epmet-cloud-generator/src/main/resources/application.yml

@ -9,9 +9,9 @@ spring:
type: com.alibaba.druid.pool.DruidDataSource
#MySQL配置
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://47.104.224.45:3308/epmet_oper_crm?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: epmet
password: elink@833066
url: jdbc:mysql://192.168.1.130:3306/epmet_gov_voice?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: epmet_dba
password: EpmEt-dbA-UsEr
#oracle配置
# driverClassName: oracle.jdbc.OracleDriver
# url: jdbc:oracle:thin:@192.168.10.10:1521:helowin

2
epmet-cloud-generator/src/main/resources/generator.properties

@ -3,7 +3,7 @@
main=
#관츰
package=com.epmet
moduleName=customer
moduleName=
#鱗諒
author=generator
#경굶뵀

125
epmet-commons/epmet-common-clienttoken/pom.xml

@ -0,0 +1,125 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>epmet-commons</artifactId>
<groupId>com.epmet</groupId>
<version>2.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>epmet-common-clienttoken</artifactId>
<packaging>jar</packaging>
<name>epmet-common-clienttoken</name>
<url>http://www.example.com</url>
<description>客户端token</description>
<dependencies>
<dependency>
<groupId>com.epmet</groupId>
<artifactId>epmet-commons-tools</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<parameters>true</parameters>
<source>${maven.compiler.source}</source> <!-- 源代码使用的开发版本 -->
<target>${maven.compiler.target}</target> <!-- 需要生成的目标class文件的编译版本 -->
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
</plugin>
<!-- jar插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
</build>
</project>

31
epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/annotation/Login.java

@ -0,0 +1,31 @@
/**
* Copyright 2018 人人开源 http://www.renren.io
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.epmet.common.token.annotation;
import java.lang.annotation.*;
/**
* 登录效验
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2017/9/23 14:30
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Login {
}

13
epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/annotation/NeedClientToken.java

@ -0,0 +1,13 @@
package com.epmet.common.token.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.CLASS)//生命注释保留时长,这里无需反射使用,使用CLASS级别
@Target(ElementType.METHOD)//生命可以使用此注解的元素级别类型(如类、方法变量等)
public @interface NeedClientToken {
boolean value() default true;
}

43
epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/constant/LoginConstant.java

@ -0,0 +1,43 @@
package com.epmet.common.token.constant;
/**
* @Description appclient
* @Author yinzuomei
* @Date 2020/3/14 20:12
*/
public interface LoginConstant {
/**
* 政府端
*/
String APP_GOV = "gov";
/**
* 居民端
*/
String APP_RESI = "resi";
/**
* 运营端
*/
String APP_OPER = "oper";
/**
* 公众号
*/
String APP_PUBLIC = "public";
/**
* web
*/
String CLIENT_WEB = "web";
/**
* 微信小程序
*/
String CLIENT_WXMP = "wxmp";
/**
* E事通服务号
*/
String CLIENT_MP = "mp";
}

23
epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/property/TokenPropertise.java

@ -0,0 +1,23 @@
package com.epmet.common.token.property;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author rongchao
* @Date 18-12-3
*/
@Component
@ConfigurationProperties(prefix = "token")
public class TokenPropertise {
private long expire = 7200L;
public long getExpire() {
return expire;
}
public void setExpire(long expire) {
this.expire = expire;
}
}

49
epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/util/TokenUtil.java

@ -0,0 +1,49 @@
package com.epmet.common.token.util;
import com.epmet.common.token.property.TokenPropertise;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.utils.CpUserDetailRedis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* token服务类
*
* @author rongchao
* @Date 18-10-31
*/
@Component
public class TokenUtil {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private TokenPropertise tokenPropertise;
@Autowired
private CpUserDetailRedis redisUtils;
public void expireToken(String app,String client,String userId) {
redisUtils.logout(app,client,userId);
}
public boolean delayToken(String app,String client,String userId) {
return redisUtils.expire(app, client,userId,tokenPropertise.getExpire());
}
/**
* 获取token过期时间
*
* @param app
* @param client
* @param userId
* @return long
* @author yujintao
* @date 2019/9/9 14:19
*/
public long getExpire(String app,String client,String userId) {
return redisUtils.getExpire(app,client,userId);
}
}

55
epmet-commons/epmet-common-clienttoken/src/main/java/com/epmet/common/token/util/UserUtil.java

@ -0,0 +1,55 @@
package com.epmet.common.token.util;
import com.epmet.commons.tools.constant.Constant;
import com.epmet.commons.tools.security.dto.TokenDto;
import com.epmet.commons.tools.utils.WebUtil;
/**
* 用户工具类
*
* @author rongchao
* @Date 18-11-20
*/
public class UserUtil {
/**
* 获取当前用户信息
*
* @return
*/
public static TokenDto getCurrentUser() {
return (TokenDto) WebUtil.getAttributesFromRequest(Constant.APP_USER_KEY);
}
/**
* 获取当前用户信息
*
* @return com.elink.esua.common.token.dto.UserTokenDto
* @author yujintao
* @date 2018/12/5 9:24
*/
public static TokenDto getCurrentUserInfo() {
TokenDto tokenDto = getCurrentUser();
if (tokenDto == null) {
return null;
}
return tokenDto;
}
/**
* 获取当前用户ID
*
* @return
*/
public static String getCurrentUserId() {
TokenDto tokenDto = getCurrentUser();
if (tokenDto == null) {
return null;
}
return tokenDto.getUserId();
}
public static void setCurrentUser(TokenDto user) {
WebUtil.setAttributesFromRequest(Constant.APP_USER_KEY, user);
}
}

13
epmet-commons/epmet-commons-mybatis/pom.xml

@ -63,6 +63,19 @@
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<!--分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
<!--flyway 数据库迁移工具-->
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
</dependencies>
<build>

25
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/annotation/DataFilter.java

@ -23,26 +23,21 @@ public @interface DataFilter {
/**
* 表的别名
*/
String tableAlias() default "";
String[] tableAliases() default "";
/**
* 查询条件前缀可选值有[whereand]
* 网格ID参数名
* 如果权限管理中配置开启了"网格内"权限过滤那此处必须指定并且在方法列表中使用该方法名传参供过滤器使用
* 例如 @DataFilter(gridIdArgName="gridId")
* public void test(String a, String b, String gridId) {...}
* @return
*/
String prefix() default "";
String gridIdsArgName() default "";
/**
* 用户ID
* 部门ID参数名
* @return
*/
String userId() default "creator";
/**
* 部门ID
*/
String deptId() default "dept_id";
/**
* 是否拼接用户ID
*/
boolean isPendingCreator() default true;
String deptIdsArgName() default "";
}

147
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/aspect/DataFilterAspect.java

@ -1,32 +1,25 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有侵权必究
*/
package com.epmet.commons.mybatis.aspect;
import cn.hutool.core.collection.CollUtil;
import com.epmet.commons.mybatis.annotation.DataFilter;
import com.epmet.commons.mybatis.entity.DataScope;
import com.epmet.commons.tools.constant.Constant;
import com.epmet.commons.tools.enums.SuperAdminEnum;
import com.epmet.commons.tools.exception.ErrorCode;
import com.epmet.commons.mybatis.feign.MybatisGovAccessFeignClient;
import com.epmet.commons.mybatis.dto.form.*;
import com.epmet.commons.tools.constant.AppClientConstant;
import com.epmet.commons.tools.constant.ThreadLocalConstant;
import com.epmet.commons.tools.exception.RenException;
import com.epmet.commons.tools.security.user.SecurityUser;
import com.epmet.commons.tools.security.user.UserDetail;
import com.epmet.commons.tools.security.user.LoginUserUtil;
import com.epmet.commons.tools.utils.Result;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 数据过滤切面处理类
@ -37,69 +30,85 @@ import java.util.Map;
@Aspect
@Component
public class DataFilterAspect {
@Pointcut("@annotation(com.epmet.commons.mybatis.annotation.DataFilter)")
public void dataFilterCut() {
}
private static final Logger log = LoggerFactory.getLogger(DataFilterAspect.class);
@Before("dataFilterCut()")
public void dataFilter(JoinPoint point) {
Object params = point.getArgs()[0];
if(params != null && params instanceof Map){
UserDetail user = SecurityUser.getUser();
//如果不是超级管理员,则进行数据过滤
if(user.getSuperAdmin() == SuperAdminEnum.NO.value()){
Map map = (Map)params;
String sqlFilter = getSqlFilter(user, point);
map.put(Constant.SQL_FILTER, new DataScope(sqlFilter));
}
@Autowired
private LoginUserUtil loginUserUtil;
return ;
}
@Autowired
private MybatisGovAccessFeignClient mybatisGovAccessFeignClient;
throw new RenException(ErrorCode.DATA_SCOPE_PARAMS_ERROR);
}
@Before("@annotation(com.epmet.commons.mybatis.annotation.DataFilter)")
public void dataFilter(JoinPoint point) {
/**
* 获取数据过滤的SQL
*/
private String getSqlFilter(UserDetail user, JoinPoint point){
MethodSignature signature = (MethodSignature) point.getSignature();
DataFilter dataFilter = signature.getMethod().getAnnotation(DataFilter.class);
//获取表的别名
String tableAlias = dataFilter.tableAlias();
if(StringUtils.isNotBlank(tableAlias)){
tableAlias += ".";
if (!AppClientConstant.APP_GOV.equals(loginUserUtil.getLoginUserApp())) {
// 只校验gov,否则放行
return;
}
StringBuilder sqlFilter = new StringBuilder();
//查询条件前缀
String prefix = dataFilter.prefix();
if(StringUtils.isNotBlank(prefix)){
sqlFilter.append(" ").append(prefix);
// 从ThreadLocal中取所需权限
String requirePermission = ThreadLocalConstant.requirePermissionTl.get();
// 没有配置所需权限,不做操作,打印提示日志
if (StringUtils.isBlank(requirePermission)) {
log.warn("接口缺少所需权限配置,请在Controller方法上使用@RequirePermission注解完成所需权限配置");
return;
}
sqlFilter.append(" (");
//部门ID列表
List<Long> deptIdList = user.getDeptIdList();
if(CollUtil.isNotEmpty(deptIdList)){
sqlFilter.append(tableAlias).append(dataFilter.deptId());
sqlFilter.append(" in(").append(StringUtils.join(deptIdList, ",")).append(")");
// 取到注解属性
MethodSignature methodSignature = (MethodSignature) point.getSignature();
DataFilter dataFilterAnno = methodSignature.getMethod().getAnnotation(DataFilter.class);
String tableAlias = dataFilterAnno.tableAliases()[0];
String gridIdsArgName = dataFilterAnno.gridIdsArgName();
String deptIdsArgName = dataFilterAnno.deptIdsArgName();
String[] parameterNames = methodSignature.getParameterNames();
// 取出注解参数中指定的gridId和deptId的入参的值
Set<String> gridIds = null;
Set<String> deptIds = null;
if (StringUtils.isNotBlank(gridIdsArgName)) {
int gridIdArgIndex = ArrayUtils.indexOf(parameterNames, gridIdsArgName);
if (gridIdArgIndex >-1){
gridIds = (Set<String>) point.getArgs()[gridIdArgIndex];
}
}
//查询本人数据
if (dataFilter.isPendingCreator()) {
if(CollUtil.isNotEmpty(deptIdList)){
sqlFilter.append(" or ");
if (StringUtils.isNotBlank(deptIdsArgName)) {
int deptArgIndex = ArrayUtils.indexOf(parameterNames, deptIdsArgName);
if (deptArgIndex > -1) {
deptIds = (Set<String>) point.getArgs()[deptArgIndex];
}
sqlFilter.append(tableAlias).append(dataFilter.userId()).append("=").append(user.getId());
}
sqlFilter.append(")");
return sqlFilter.toString();
//LoginUserInfoResultDTO loginUserInfo = getLoginUserInfo();
GetSQLFilterFormDTO form = new GetSQLFilterFormDTO();
form.setApp(loginUserUtil.getLoginUserApp());
form.setClient(loginUserUtil.getLoginUserClient());
form.setUserId(loginUserUtil.getLoginUserId());
form.setDepartmentIds(deptIds);
form.setGridIds(gridIds);
form.setOperationKey(requirePermission);
form.setTableAlias(tableAlias);
Result<String> sqlFilterSegmentRst = mybatisGovAccessFeignClient.getSqlFilterSegment(form);
// 方式1.填充到Service方法列表中的DataScope对象中。如果dao入参是用DTO的话,那么再加一个DataScope入参,sql中会报错提示#{}参数找不到,因此改用方法2
//Object[] methodArgs = point.getArgs();
//for (Object methodArg : methodArgs) {
// if (methodArg instanceof DataScope) {
// ((DataScope) methodArg).setSqlFilter(sqlFilterSegment);
// return;
// }
//}
// 方式2,采用ThreadLocal传参到DataFilterInterceptor中
if (!sqlFilterSegmentRst.success()) {
throw new RenException("DataFilterAspect调用Access服务生成SqlFilterSegment失败:" + sqlFilterSegmentRst.getMsg());
}
if (StringUtils.isNotBlank(sqlFilterSegmentRst.getData())) {
ThreadLocalConstant.sqlFilter.set(sqlFilterSegmentRst.getData());
}
}
}

9
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/AccessSettingFormDTO.java

@ -0,0 +1,9 @@
package com.epmet.commons.mybatis.dto.form;
import lombok.Data;
@Data
public class AccessSettingFormDTO {
private String roleId;
private String operationKey;
}

49
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/DepartmentListResultDTO.java

@ -0,0 +1,49 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.commons.mybatis.dto.form;
import lombok.Data;
import java.io.Serializable;
/**
* 组织首页-获取机关下部门列表-部门详情数据
*
* @author sun
*/
@Data
public class DepartmentListResultDTO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 部门Id
*/
private String departmentId;
/**
* 部门名称
*/
private String departmentName;
/**
* 部门下总人数
*/
private Integer totalUser;
}

29
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/GetSQLFilterFormDTO.java

@ -0,0 +1,29 @@
package com.epmet.commons.mybatis.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.util.Set;
@Data
public class GetSQLFilterFormDTO {
@NotBlank
private String operationKey;
@NotBlank
private String userId;
@NotBlank
private String app;
@NotBlank
private String client;
private String tableAlias;
private Set<String> gridIds;
private Set<String> departmentIds;
}

92
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/OperationScopeDTO.java

@ -0,0 +1,92 @@
/**
* Copyright 2018 人人开源 https://www.renren.io
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.epmet.commons.mybatis.dto.form;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 权限范围表
*
* @author generator generator@elink-cn.com
* @since v1.0.0 2020-04-24
*/
@Data
public class OperationScopeDTO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
private String id;
/**
* 角色id
*/
private String roleId;
/**
* 范围key
*/
private String scopeKey;
/**
* 范围名称
*/
private String scopeName;
/**
* 范围序号
*/
private String scopeIndex;
/**
* 是否删除0未删除1已删除
*/
private Integer delFlag;
/**
* 乐观锁
*/
private Integer revision;
/**
* 创建者id
*/
private String createdBy;
/**
* 创建时间
*/
private Date createdTime;
/**
* 更新者id
*/
private String updatedBy;
/**
* 更新时间
*/
private Date updatedTime;
}

18
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/OperationScopeFormDTO.java

@ -0,0 +1,18 @@
package com.epmet.commons.mybatis.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class OperationScopeFormDTO {
public interface ListOperationScopeGroup {}
@NotBlank(message = "角色ID不能为空", groups = {ListOperationScopeGroup.class})
private String roleId;
@NotBlank(message = "操作的key不能为空", groups = {ListOperationScopeGroup.class})
private String operationKey;
}

33
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/RoleOpeScopeResultDTO.java

@ -0,0 +1,33 @@
package com.epmet.commons.mybatis.dto.form;
import lombok.Data;
@Data
public class RoleOpeScopeResultDTO {
/**
* 角色ID
*/
private String roleId;
/**
* 操作key
*/
private String operationKey;
/**
* 范围key
*/
private String scopeKey;
/**
* 范围名称
*/
private String scopeName;
/**
* 范围序号
*/
private String scopeIndex;
}

59
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/StaffPermCacheFormDTO.java

@ -0,0 +1,59 @@
package com.epmet.commons.mybatis.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.util.Set;
@Data
public class StaffPermCacheFormDTO {
/**
* 更新权限缓存分组
*/
public interface UpdatePermissionCache {}
/**
* 查询当前权限列表
*/
public interface GetStaffCurrPermissions {}
/**
* 工作人员 id
*/
@NotBlank(message = "工作人员ID不能为空", groups = {UpdatePermissionCache.class, GetStaffCurrPermissions.class})
private String staffId;
/**
* 登录头信息app
*/
@NotBlank(message = "登录头信息app不能为空", groups = {UpdatePermissionCache.class, GetStaffCurrPermissions.class})
private String app;
/**
* 登录头信息client
*/
@NotBlank(message = "登录头信息client不能为空", groups = {UpdatePermissionCache.class, GetStaffCurrPermissions.class})
private String client;
/**
* 组织ID路径
*/
private String orgIdPath;
/**
* 权限列表
*/
private Set<String> permissions;
/**
* 角色列表
*/
private Set<String> roleIdList;
/**
* 当前所在网格id
*/
private String gridId;
}

37
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/StaffPermCacheResultDTO.java

@ -0,0 +1,37 @@
package com.epmet.commons.mybatis.dto.form;
import lombok.Data;
import java.util.Set;
@Data
public class StaffPermCacheResultDTO {
/**
* 权限列表
*/
private Set<String> permissions;
/**
* 角色列表
*/
private Set<String> roleIdList;
/**
* 部门id列表
*/
private Set<String> deptIdList;
/**
* 机构Id
*/
private String orgIdPath;
/**
* 网格ID
*/
private String gridId;
private String gridIdList;
}

26
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/dto/form/StaffPermissionFormDTO.java

@ -0,0 +1,26 @@
package com.epmet.commons.mybatis.dto.form;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.util.Set;
@Data
public class StaffPermissionFormDTO {
/**
* 工作人员 id
*/
private String staffId;
/**
* 登录头信息app
*/
private String app;
/**
* 登录头信息client
*/
private String client;
}

9
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/entity/DataScope.java

@ -1,8 +1,8 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* <p>
* https://www.renren.io
*
* <p>
* 版权所有侵权必究
*/
@ -15,8 +15,13 @@ package com.epmet.commons.mybatis.entity;
* @since 1.0.0
*/
public class DataScope {
private String sqlFilter;
public static DataScope getDefault() {
return new DataScope("");
}
public DataScope(String sqlFilter) {
this.sqlFilter = sqlFilter;
}

30
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/feign/MybatisGovAccessFeignClient.java

@ -0,0 +1,30 @@
package com.epmet.commons.mybatis.feign;
import com.epmet.commons.mybatis.dto.form.*;
import com.epmet.commons.mybatis.feign.fallback.MybatisGovAccessFeignClientFallback;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.utils.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
import java.util.Set;
/**
* @Description
* @Author sun
*/
//@FeignClient(name = ServiceConstant.GOV_ACCESS_SERVER, fallback = MybatisGovAccessFeignClientFallback.class, url = "localhost:8099")
@FeignClient(name = ServiceConstant.GOV_ACCESS_SERVER, fallback = MybatisGovAccessFeignClientFallback.class)
public interface MybatisGovAccessFeignClient {
/**
* 查询sql过滤片段
* @param form
* @return
*/
@PostMapping("/gov/access/access/getSqlFilterSegment")
Result<String> getSqlFilterSegment(@RequestBody GetSQLFilterFormDTO form);
}

29
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/feign/MybatisGovOrgFeignClient.java

@ -0,0 +1,29 @@
package com.epmet.commons.mybatis.feign;
import com.epmet.commons.mybatis.dto.form.*;
import com.epmet.commons.mybatis.feign.fallback.MybatisGovOrgFeignClientFallback;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.utils.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;
import java.util.Set;
/**
* @Description
* @Author sun
*/
//, url = "localhost:8092"
@FeignClient(name = ServiceConstant.GOV_ORG_SERVER, fallback = MybatisGovOrgFeignClientFallback.class)
public interface MybatisGovOrgFeignClient {
/**
* 查询人员部门列表
* @param staffId
* @return
*/
@PostMapping("/gov/org/department/staff/{staffId}/departmentlist")
Result<List<DepartmentListResultDTO>> getDepartmentListByStaffId(@PathVariable("staffId") String staffId);
}

28
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/feign/fallback/MybatisGovAccessFeignClientFallback.java

@ -0,0 +1,28 @@
package com.epmet.commons.mybatis.feign.fallback;
import com.epmet.commons.mybatis.dto.form.*;
import com.epmet.commons.mybatis.feign.MybatisGovAccessFeignClient;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.utils.ModuleUtils;
import com.epmet.commons.tools.utils.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 调用政府端权限
* @Author wxz
* @Description
* @Date 2020/4/24 11:17
**/
@Component
public class MybatisGovAccessFeignClientFallback implements MybatisGovAccessFeignClient {
@Override
public Result<String> getSqlFilterSegment(GetSQLFilterFormDTO form) {
return ModuleUtils.feignConError(ServiceConstant.GOV_ACCESS_SERVER, "getSqlFilterSegment", form);
}
}

26
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/feign/fallback/MybatisGovOrgFeignClientFallback.java

@ -0,0 +1,26 @@
package com.epmet.commons.mybatis.feign.fallback;
import com.epmet.commons.mybatis.dto.form.*;
import com.epmet.commons.mybatis.feign.MybatisGovOrgFeignClient;
import com.epmet.commons.tools.constant.ServiceConstant;
import com.epmet.commons.tools.utils.ModuleUtils;
import com.epmet.commons.tools.utils.Result;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Set;
/**
* 调用政府端权限
* @Author wxz
* @Description
* @Date 2020/4/24 11:17
**/
@Component
public class MybatisGovOrgFeignClientFallback implements MybatisGovOrgFeignClient {
@Override
public Result<List<DepartmentListResultDTO>> getDepartmentListByStaffId(String staffId) {
return ModuleUtils.feignConError(ServiceConstant.GOV_ACCESS_SERVER, "getDepartmentListByStaffId", staffId);
}
}

77
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/handler/FieldMetaObjectHandler.java

@ -17,9 +17,12 @@ import com.epmet.commons.mybatis.enums.EpmetDelFlagEnum;
import com.epmet.commons.tools.constant.Constant;
import com.epmet.commons.tools.constant.FieldConstant;
import com.epmet.commons.tools.constant.NumConstant;
import com.epmet.commons.tools.security.user.LoginUserUtil;
import com.epmet.commons.tools.security.user.SecurityUser;
import com.epmet.commons.tools.security.user.UserDetail;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
@ -38,23 +41,26 @@ public class FieldMetaObjectHandler implements MetaObjectHandler {
private final static String UPDATER = "updater";
private final static String DEPT_ID = "deptId";
@Autowired
private LoginUserUtil loginUserUtil;
@Override
public void insertFill(MetaObject metaObject) {
UserDetail user = SecurityUser.getUser();
Date date = new Date();
if (metaObject.getOriginalObject() instanceof BaseEpmetEntity) {
String userId = user == null ? Constant.APP_USER_FLAG : String.valueOf(user.getId());
Long deptId = user == null ? null : user.getDeptId();
setFieldValByName(FieldConstant.CREATED_TIME_HUMP, date, metaObject);
setFieldValByName(FieldConstant.CREATED_BY_HUMP, userId, metaObject);
setFieldValByName(FieldConstant.UPDATED_TIME_HUMP, date, metaObject);
setFieldValByName(FieldConstant.UPDATED_BY_HUMP, userId, metaObject);
// epmet项目新增的
setFieldValByName(FieldConstant.CREATED_TIME_HUMP, getCreatedTimeByFieldValue(metaObject), metaObject);
setFieldValByName(FieldConstant.CREATED_BY_HUMP, getCreatedByFieldValue(metaObject), metaObject);
setFieldValByName(FieldConstant.UPDATED_TIME_HUMP, getUpdatedTimeByFieldValue(metaObject), metaObject);
setFieldValByName(FieldConstant.UPDATED_BY_HUMP, getUpdatedByFieldValue(metaObject), metaObject);
setFieldValByName(FieldConstant.REVISION_HUMP, NumConstant.ZERO, metaObject);
//删除标识
setFieldValByName(FieldConstant.DEL_FLAG_HUMP, EpmetDelFlagEnum.NORMAL.value(), metaObject);
// 数据权限标志
setInsertFieldValByName(DEPT_ID, deptId, metaObject);
} else {
//setInsertFieldValByName(DEPT_ID, deptId, metaObject);
} else if (metaObject.getOriginalObject() instanceof BaseEntity) {
UserDetail user = SecurityUser.getUser();
// renren自带的
if (user == null) {
return;
}
@ -73,11 +79,58 @@ public class FieldMetaObjectHandler implements MetaObjectHandler {
}
}
public Object getCreatedByFieldValue(MetaObject metaObject) {
Object value = loginUserUtil.getLoginUserId();
if (value == null) {
if (metaObject.hasGetter(FieldConstant.CREATED_BY_HUMP)) {
value = metaObject.getValue(FieldConstant.CREATED_BY_HUMP);
}
if (value == null) {
value = Constant.APP_USER_FLAG;
}
}
return value;
}
public Object getCreatedTimeByFieldValue(MetaObject metaObject) {
Object createdTime = null;
if (metaObject.hasGetter(FieldConstant.CREATED_TIME_HUMP)) {
createdTime = metaObject.getValue(FieldConstant.CREATED_TIME_HUMP);
}
if (createdTime == null) {
createdTime = new Date();
}
return createdTime;
}
public Object getUpdatedTimeByFieldValue(MetaObject metaObject) {
Object createdTime = null;
if (metaObject.hasGetter(FieldConstant.CREATED_TIME_HUMP)) {
createdTime = metaObject.getValue(FieldConstant.CREATED_TIME_HUMP);
}
if (createdTime == null) {
createdTime = new Date();
}
return createdTime;
}
public Object getUpdatedByFieldValue(MetaObject metaObject) {
Object value = loginUserUtil.getLoginUserId();
if (value == null) {
if (metaObject.hasGetter(FieldConstant.UPDATED_BY_HUMP)) {
value = metaObject.getValue(FieldConstant.UPDATED_BY_HUMP);
}
if (value == null) {
value = Constant.APP_USER_FLAG;
}
}
return value;
}
@Override
public void updateFill(MetaObject metaObject) {
Object originalObject = metaObject.getOriginalObject();
Long id = SecurityUser.getUserId();
boolean fillEntity = false;
boolean fillEsuaEntity = false;
@ -96,14 +149,14 @@ public class FieldMetaObjectHandler implements MetaObjectHandler {
}
}
if (fillEntity) {
Long id = SecurityUser.getUserId();
id = null == id ? NumConstant.ZERO_L : id;
//更新者
setFieldValByName(UPDATER, id, metaObject);
//更新时间
setFieldValByName(UPDATE_DATE, new Date(), metaObject);
} else if (fillEsuaEntity) {
String userId = null == id ? Constant.APP_USER_FLAG : String.valueOf(id);
setFieldValByName(FieldConstant.UPDATED_BY_HUMP, userId, metaObject);
setFieldValByName(FieldConstant.UPDATED_BY_HUMP, getUpdatedByFieldValue(metaObject), metaObject);
setFieldValByName(FieldConstant.UPDATED_TIME_HUMP, new Date(), metaObject);
}
}

46
epmet-commons/epmet-commons-mybatis/src/main/java/com/epmet/commons/mybatis/interceptor/DataFilterInterceptor.java

@ -9,9 +9,10 @@
package com.epmet.commons.mybatis.interceptor;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.epmet.commons.mybatis.entity.DataScope;
import com.epmet.commons.mybatis.aspect.DataFilterAspect;
import com.epmet.commons.tools.constant.ThreadLocalConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
@ -21,7 +22,6 @@ import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import java.sql.Connection;
import java.util.Map;
import java.util.Properties;
/**
@ -41,26 +41,32 @@ public class DataFilterInterceptor extends AbstractSqlParserHandler implements I
// SQL解析
this.sqlParser(metaObject);
// 先判断是不是SELECT操作
// 先判断是不是INSERT操作,insert不过滤
MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
if (SqlCommandType.INSERT.equals(mappedStatement.getSqlCommandType())) {
return invocation.proceed();
}
// 针对定义了rowBounds,做为mapper接口方法的参数
BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
String originalSql = boundSql.getSql();
Object paramObj = boundSql.getParameterObject();
// 判断参数里是否有DataScope对象
DataScope scope = null;
//Object paramObj = boundSql.getParameterObject();
// 方式1.判断参数里是否有DataScope对象
/*DataScope scope = null;
if (paramObj instanceof DataScope) {
// 直接传入DataScope,不分页?
scope = (DataScope) paramObj;
} else if (paramObj instanceof Map) {
// 入参是一个Map
for (Object arg : ((Map) paramObj).values()) {
if (arg instanceof DataScope) {
scope = (DataScope) arg;
break;
} else if (arg instanceof QueryWrapper) {
// 通过Mybatis-plus封装的通用方法进行查询
break;
}
}
}
@ -69,16 +75,34 @@ public class DataFilterInterceptor extends AbstractSqlParserHandler implements I
if (scope == null) {
return invocation.proceed();
}
String sqlFilter = scope.getSqlFilter();
*/
// 方式2.从ThreadLocal中取sqlFilter
String sqlFilter = ThreadLocalConstant.sqlFilter.get();
if (StringUtils.isBlank(sqlFilter)) {
return invocation.proceed();
}
// 没有where就拼接where,有了where就拼接AND
if (originalSql.indexOf("WHERE") == 0) {
// 不包含where,需要手动拼接上
sqlFilter = " WHERE ".concat(sqlFilter);
} else {
sqlFilter = " AND (".concat(sqlFilter).concat(")");
}
// 拼接新SQL
String orderBy = "ORDER BY";
String groupBy = "GROUP BY";
if (originalSql.indexOf(groupBy) > -1) {
originalSql = originalSql.replace(groupBy, scope.getSqlFilter() + groupBy);
originalSql = originalSql.replace(groupBy, sqlFilter + groupBy);
} else if (originalSql.indexOf(orderBy) > -1) {
originalSql = originalSql.replace(orderBy, scope.getSqlFilter() + orderBy);
originalSql = originalSql.replace(orderBy, sqlFilter + orderBy);
} else {
originalSql = originalSql + scope.getSqlFilter();
originalSql = originalSql.concat(sqlFilter);
}
// 重写SQL

33
epmet-commons/epmet-commons-service-call/pom.xml

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>epmet-commons</artifactId>
<groupId>com.epmet</groupId>
<version>2.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>epmet-commons-service-call</artifactId>
<version>0.3.1</version>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- 替换Feign原生httpclient -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>10.3.0</version>
</dependency>
</dependencies>
</project>

94
epmet-commons/epmet-commons-service-call/src/main/java/com/epmet/loadbalancer/EpmetRequestLoadBalancerRule.java

@ -0,0 +1,94 @@
package com.epmet.loadbalancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidanceRule;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* Epmet负载均衡算法规则类当前支持读取环境变量将请求重定向到指定的HOST:PORT
*
* @RibbonClient(name = "MS-PROXY", configuration = EpmetRequestLoadBalancerRule.class)
*
* @Bean
* @LoadBalanced
* public RestTemplate getRestTemplate() {
* return new RestTemplate();
* }
*
* @Bean
* public IRule getMyLoadBalancerRule(Environment env) {
* EpmetRequestLoadBalancerRule rule = new EpmetRequestLoadBalancerRule();
* rule.setEnv(env);
* return rule;
* }
*
*/
public class EpmetRequestLoadBalancerRule extends ZoneAvoidanceRule {
private static Logger logger = LoggerFactory.getLogger(EpmetRequestLoadBalancerRule.class);
private Environment env;
public EpmetRequestLoadBalancerRule() {
}
public void setEnv(Environment env) {
this.env = env;
}
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
}
/**
* 此处会取环境变量中"测试服务器"的值
* @param key
* @return
*/
@Override
public Server choose(Object key) {
ILoadBalancer loadBalancer = getLoadBalancer();
List<Server> servers = loadBalancer.getReachableServers();
if (CollectionUtils.isEmpty(servers)) {
logger.error("自定义负载均衡器:ReachableServers列表为空");
return super.choose(key);
}
Server server = servers.get(0);
String appName = server.getMetaInfo().getAppName();
String serviceName = appName.split("@@")[1];
String hostEnvKey = getHostEnvKey(serviceName);
String portEnvKey = getPortEnvKey(serviceName);
String epmetGovOrgHost = env.getProperty(hostEnvKey);
String epmetGovOrgPort = env.getProperty(portEnvKey);
if (StringUtils.isAnyBlank(epmetGovOrgHost, epmetGovOrgPort)) {
// 没有配置,走父类均衡器
return super.choose(key);
}
server.setHost(epmetGovOrgHost);
server.setPort(Integer.valueOf(epmetGovOrgPort));
return server;
}
/**
* 获取host环境变量Key
* @param serviceName
* @return
*/
public String getHostEnvKey(String serviceName) {
return serviceName.replace("-", "_").concat("_HOST").toUpperCase();
}
public String getPortEnvKey(String serviceName) {
return serviceName.replace("-", "_").concat("_PORT").toUpperCase();
}
}

41
epmet-commons/epmet-commons-tools-phone/pom.xml

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>epmet-commons</artifactId>
<groupId>com.epmet</groupId>
<version>2.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>epmet-commons-tools-phone</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>8.8.8</version>
</dependency>
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>carrier</artifactId>
<version>1.75</version>
</dependency>
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>2.85</version>
</dependency>
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>prefixmapper</artifactId>
<version>2.85</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
</build>
</project>

79
epmet-commons/epmet-commons-tools-phone/src/main/java/com/epmet/commons/tools/utils/PhoneDto.java

@ -0,0 +1,79 @@
package com.epmet.commons.tools.utils;
/**
* 电话DTO
*
* @author rongchao
* @Date 18-12-11
*/
public class PhoneDto {
/**
* 省份名称
*/
private String provinceName;
/**
* 城市名称
*/
private String cityName;
/**
* 运营商移动/电信/联通
*/
private String carrier;
/**
* 省份名称
*
* @return 获取provinceName属性值
*/
public String getProvinceName() {
return provinceName;
}
/**
* 省份名称
*
* @param provinceName 设置 provinceName 属性值为参数值 provinceName
*/
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
/**
* 城市名称
*
* @return 获取cityName属性值
*/
public String getCityName() {
return cityName;
}
/**
* 城市名称
*
* @param cityName 设置 cityName 属性值为参数值 cityName
*/
public void setCityName(String cityName) {
this.cityName = cityName;
}
/**
* 运营商移动/电信/联通
*
* @return 获取carrier属性值
*/
public String getCarrier() {
return carrier;
}
/**
* 运营商移动/电信/联通
*
* @param carrier 设置 carrier 属性值为参数值 carrier
*/
public void setCarrier(String carrier) {
this.carrier = carrier;
}
}

178
epmet-commons/epmet-commons-tools-phone/src/main/java/com/epmet/commons/tools/utils/PhoneUtil.java

@ -0,0 +1,178 @@
package com.epmet.commons.tools.utils;
/**
* @author rongchao
* @Date 18-12-11
*/
import com.google.i18n.phonenumbers.PhoneNumberToCarrierMapper;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder;
import java.util.Locale;
/**
* 手机号归属地查询
* jar依赖com.googlecode.libphonenumber(LibphonenumberGeocoderPrefixmapper
* Carrier) pom依赖http://mvnrepository.com/search?q=libphonenumber
* 项目地址https://github.com/googlei18n/libphonenumber
*
* @author rongchao
* @Date 18-12-11
*/
public class PhoneUtil {
/**
* 直辖市
*/
private final static String[] MUNICIPALITY = {"北京市", "天津市", "上海市", "重庆市"};
/**
* 自治区
*/
private final static String[] AUTONOMOUS_REGION = {"新疆", "内蒙古", "西藏", "宁夏", "广西"};
private static PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil
.getInstance();
/**
* 提供与电话号码相关的运营商信息
*/
private static PhoneNumberToCarrierMapper carrierMapper = PhoneNumberToCarrierMapper
.getInstance();
/**
* 提供与电话号码有关的地理信息
*/
private static PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder
.getInstance();
/**
* 中国大陆区区号
*/
private final static int COUNTRY_CODE = 86;
/**
* 根据手机号 判断手机号是否有效
*
* @param phoneNumber 手机号码
* @return true-有效 false-无效
*/
public static boolean checkPhoneNumber(String phoneNumber) {
long phone = Long.parseLong(phoneNumber);
PhoneNumber pn = new PhoneNumber();
pn.setCountryCode(COUNTRY_CODE);
pn.setNationalNumber(phone);
return phoneNumberUtil.isValidNumber(pn);
}
/**
* 根据手机号 判断手机运营商
*
* @param phoneNumber 手机号码
* @return 广东省广州市移动
*/
public static String getCarrier(String phoneNumber) {
long phone = Long.parseLong(phoneNumber);
PhoneNumber pn = new PhoneNumber();
pn.setCountryCode(COUNTRY_CODE);
pn.setNationalNumber(phone);
// 返回结果只有英文,自己转成成中文
String carrierEn = carrierMapper.getNameForNumber(pn, Locale.ENGLISH);
String carrierZh = "";
switch (carrierEn) {
case "China Mobile":
carrierZh += "移动";
break;
case "China Unicom":
carrierZh += "联通";
break;
case "China Telecom":
carrierZh += "电信";
break;
default:
break;
}
return carrierZh;
}
/**
* 根据手机号 获取手机归属地
*
* @param phoneNumber 手机号码
* @return 广东省广州市
*/
public static String getGeo(String phoneNumber) {
long phone = Long.parseLong(phoneNumber);
Phonenumber.PhoneNumber pn = new Phonenumber.PhoneNumber();
pn.setCountryCode(COUNTRY_CODE);
pn.setNationalNumber(phone);
return geocoder.getDescriptionForNumber(pn, Locale.CHINESE);
}
/**
* 根据手机号 获取手机信息模型
*
* <pre>
* 若返回值为null则说明该号码无效
* </pre>
*
* @param phoneNumber 手机号码
* @return 手机信息模型PhoneModel
*/
public static PhoneDto getPhoneDto(String phoneNumber) {
if (checkPhoneNumber(phoneNumber)) {
String geo = getGeo(phoneNumber);
PhoneDto phoneDto = new PhoneDto();
String carrier = getCarrier(phoneNumber);
phoneDto.setCarrier(carrier);
// 直辖市
for (String val : MUNICIPALITY) {
if (geo.equals(val)) {
phoneDto.setProvinceName(val.replace("市", ""));
phoneDto.setCityName(val);
return phoneDto;
}
}
// 自治区
for (String val : AUTONOMOUS_REGION) {
if (geo.startsWith(val)) {
phoneDto.setProvinceName(val);
phoneDto.setCityName(geo.replace(val, ""));
return phoneDto;
}
}
// 其它
String[] splitArr = geo.split("省");
if (splitArr != null && splitArr.length == 2) {
phoneDto.setProvinceName(splitArr[0]);
phoneDto.setCityName(splitArr[1]);
return phoneDto;
}
}
return null;
}
public static void main(String[] args) {
PhoneDto phoneDto = PhoneUtil.getPhoneDto("13701001254");
if (phoneDto != null) {
System.out.println(phoneDto.getProvinceName());
System.out.println(phoneDto.getCityName());
System.out.println(phoneDto.getCarrier());
} else {
System.err.println("该号码无效");
}
}
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save