浏览代码

Merge branch 'dev' of http://192.168.1.220:10080/jiwei/jw2.0

yeshijie 7 年之前
父节点
当前提交
e5618c5300
共有 96 个文件被更改,包括 4047 次插入228 次删除
  1. 39 0
      base/common-security/pom.xml
  2. 124 0
      base/common-security/readme.MD
  3. 0 13
      base/common-security/src/main/java/com.yihu.base.security/AuthorizationServerConfig.java
  4. 0 14
      base/common-security/src/main/java/com.yihu.base.security/ResourceServerConfig.java
  5. 25 0
      base/common-security/src/main/java/com.yihu.base.security/SercurityConfig.java
  6. 102 0
      base/common-security/src/main/java/com.yihu.base.security/config/AuthorizationServerConfig.java
  7. 62 0
      base/common-security/src/main/java/com.yihu.base.security/config/ResourceServerConfig.java
  8. 19 17
      base/common-security/src/main/java/com.yihu.base.security/hander/BaseAuthenticationSuccessHandler.java
  9. 20 22
      base/common-security/src/main/java/com.yihu.base.security/hander/BseAuthenctiationFailureHandler.java
  10. 34 0
      base/common-security/src/main/java/com.yihu.base.security/properties/AccessTokenPorperties.java
  11. 21 0
      base/common-security/src/main/java/com.yihu.base.security/properties/SecurityProperties.java
  12. 34 0
      base/common-security/src/main/java/com.yihu.base.security/properties/SmsValidateProperties.java
  13. 9 0
      base/common-security/src/main/java/com.yihu.base.security/rbas/ClientServiceProvider.java
  14. 1 1
      base/common-security/src/main/java/com.yihu.base.security/rbas/RbasService.java
  15. 11 0
      base/common-security/src/main/java/com.yihu.base.security/rbas/provider/AuthorizeConfigProvider.java
  16. 24 0
      base/common-security/src/main/java/com.yihu.base.security/rbas/provider/AuthorizeConfigProviderManager.java
  17. 28 0
      base/common-security/src/main/java/com.yihu.base.security/rbas/provider/PerssionAllAuthorizeConfigProvider.java
  18. 20 0
      base/common-security/src/main/java/com.yihu.base.security/rbas/provider/RbasAuthorizeConfigProvider.java
  19. 112 0
      base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationFilter.java
  20. 64 0
      base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationProvider.java
  21. 49 0
      base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationSecurityConfig.java
  22. 81 0
      base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationToken.java
  23. 40 0
      base/common-security/src/main/java/com.yihu.base.security/sms/controller/SmsController.java
  24. 23 0
      base/common-security/src/main/java/com.yihu.base.security/sms/exception/ValidateCodeException.java
  25. 71 0
      base/common-security/src/main/java/com.yihu.base.security/sms/filter/SmsvalidateCodeFilter.java
  26. 41 0
      base/common-security/src/main/java/com.yihu.base.security/sms/generator/SmsValidateCodeGenerator.java
  27. 17 0
      base/common-security/src/main/java/com.yihu.base.security/sms/generator/ValidateCodeGenerator.java
  28. 160 0
      base/common-security/src/main/java/com.yihu.base.security/sms/process/SmsValidateCodeProcessor.java
  29. 32 0
      base/common-security/src/main/java/com.yihu.base.security/sms/process/ValidateCodeProcessor.java
  30. 25 0
      base/common-security/src/main/java/com.yihu.base.security/sms/sender/DefaultSmsCodeSender.java
  31. 14 0
      base/common-security/src/main/java/com.yihu.base.security/sms/sender/SmsCodeSender.java
  32. 62 0
      base/common-security/src/main/java/com.yihu.base.security/sms/vo/ValidateCode.java
  33. 25 0
      base/common-security/src/main/java/com.yihu.base.security/vo/SimpleResponse.java
  34. 40 0
      base/common-security/src/main/resources/template.yml
  35. 18 0
      common/common-entity/src/main/java/META-INF/persistence.xml
  36. 0 1
      common/common-entity/src/main/java/com/yihu/jw/base/user/BaseEmployRoleDO.java
  37. 31 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseLoginRequestMapping.java
  38. 52 1
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseRequestMapping.java
  39. 81 2
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseUserRequestMapping.java
  40. 23 1
      svr-lib-parent-pom/pom.xml
  41. 6 1
      svr/svr-base/pom.xml
  42. 17 0
      svr/svr-base/src/main/java/META-INF/persistence.xml
  43. 6 0
      svr/svr-base/src/main/java/com/yihu/jw/business/base/controller/SystemController.java
  44. 12 0
      svr/svr-base/src/main/java/com/yihu/jw/business/base/dao/SystemDictDao.java
  45. 12 0
      svr/svr-base/src/main/java/com/yihu/jw/business/base/dao/SystemDictListDao.java
  46. 13 0
      svr/svr-base/src/main/java/com/yihu/jw/business/base/service/SystemDictListService.java
  47. 11 0
      svr/svr-base/src/main/java/com/yihu/jw/business/base/service/SystemDictService.java
  48. 17 1
      svr/svr-base/src/main/java/com/yihu/jw/business/login/dao/BaseLoginAccountDao.java
  49. 75 0
      svr/svr-base/src/main/java/com/yihu/jw/business/login/service/BaseLoginAccountService.java
  50. 95 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/BaseMenuController.java
  51. 1 1
      svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/BaseRoleController.java
  52. 81 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/EmployController.java
  53. 0 33
      svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/EmployeeController.java
  54. 32 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseMenuDao.java
  55. 20 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseRoleMenuDao.java
  56. 24 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployDao.java
  57. 18 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployRoleDao.java
  58. 0 12
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployeeDao.java
  59. 0 12
      svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployeeRoleDao.java
  60. 137 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseMenuService.java
  61. 100 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseRoleMenuService.java
  62. 1 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseRoleService.java
  63. 104 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployRoleService.java
  64. 124 0
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployService.java
  65. 0 10
      svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployeeService.java
  66. 4 0
      svr/svr-demo/pom.xml
  67. 88 1
      svr/svr-demo/readme.MD
  68. 5 1
      svr/svr-demo/src/main/java/com/yihu/DemoApplication.java
  69. 2 1
      svr/svr-demo/src/main/java/com/yihu/jw/model/MyUser.java
  70. 80 2
      svr/svr-demo/src/main/java/com/yihu/jw/model/SaasDO.java
  71. 25 9
      svr/svr-demo/src/main/java/com/yihu/jw/service/ClientService.java
  72. 48 0
      svr/svr-demo/src/main/java/com/yihu/jw/service/RbasService.java
  73. 28 6
      svr/svr-demo/src/main/java/com/yihu/jw/service/UserService.java
  74. 10 1
      svr/svr-demo/src/main/resources/application.yml
  75. 1 26
      svr/svr-demo/src/main/resources/resources/denglu.html
  76. 20 0
      web-gateway/src/main/java/com/yihu/jw/commnon/base/base/BaseContants.java
  77. 45 0
      web-gateway/src/main/java/com/yihu/jw/commnon/base/user/BaseUserContants.java
  78. 2 6
      web-gateway/src/main/java/com/yihu/jw/config/security/roleService/ClientService.java
  79. 2 2
      web-gateway/src/main/java/com/yihu/jw/config/security/roleService/UserService.java
  80. 52 0
      web-gateway/src/main/java/com/yihu/jw/controller/base/base/SystemDictController.java
  81. 53 0
      web-gateway/src/main/java/com/yihu/jw/controller/base/base/SystemDictListController.java
  82. 147 0
      web-gateway/src/main/java/com/yihu/jw/controller/base/user/BaseMenuController.java
  83. 135 0
      web-gateway/src/main/java/com/yihu/jw/controller/base/user/BaseRoleController.java
  84. 135 0
      web-gateway/src/main/java/com/yihu/jw/controller/base/user/EmployController.java
  85. 0 2
      web-gateway/src/main/java/com/yihu/jw/feign/base/base/FunctionFeign.java
  86. 46 0
      web-gateway/src/main/java/com/yihu/jw/feign/base/base/SystemDictFeign.java
  87. 49 0
      web-gateway/src/main/java/com/yihu/jw/feign/base/base/SystemDictListFeign.java
  88. 65 0
      web-gateway/src/main/java/com/yihu/jw/feign/base/user/BaseMenuFeign.java
  89. 46 0
      web-gateway/src/main/java/com/yihu/jw/feign/base/user/BaseRoleFeign.java
  90. 48 0
      web-gateway/src/main/java/com/yihu/jw/feign/base/user/EmployFeign.java
  91. 0 25
      web-gateway/src/main/java/com/yihu/jw/feign/base/user/EmployeeFeign.java
  92. 74 0
      web-gateway/src/main/java/com/yihu/jw/feign/fallbackfactory/base/base/SystemDictFeignFallbackFactory.java
  93. 80 0
      web-gateway/src/main/java/com/yihu/jw/feign/fallbackfactory/base/base/SystemDictListFeignFallbackFactory.java
  94. 82 0
      web-gateway/src/main/java/com/yihu/jw/feign/fallbackfactory/base/user/BaseMenuFeignFallbackFactory.java
  95. 73 0
      web-gateway/src/main/java/com/yihu/jw/feign/fallbackfactory/base/user/BaseRoleFeignFallbackFactory.java
  96. 62 4
      web-gateway/src/main/java/com/yihu/jw/feign/fallbackfactory/base/user/EmployeeFeignFallbackFactory.java

+ 39 - 0
base/common-security/pom.xml

@ -19,10 +19,39 @@
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.0.14.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
@ -31,10 +60,20 @@
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.5</version>
        </dependency>
    </dependencies>
</project>

+ 124 - 0
base/common-security/readme.MD

@ -0,0 +1,124 @@
**授权码模式:(一直开放API用)**
获取code
http://localhost:8060/oauth/authorize?response_type=code&client_id=cwd&redirect_uri=http://example.com&scope=all
获取token post请求
http://localhost:8060/oauth/token
header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
  
{
     "grant_type":"authorization_code",  
     "client_id":"cwd",
     "code":"第一步请求获取的code",
     "redirect_uri":"http://example.com",
     "scope":"all"
}
返回值
{
    "access_token":"bd677e24-2de5-4862-a5e1-8f90a074db42",
    "token_type":"bearer",
    "refresh_token":"1427b997-ef94-4061-8940-c71da6549acd",
    "expires_in":43199,
    "scope":"all"
}
**密码模式(一般自己公司系统用)**
获取token post请求
http://localhost:8060/oauth/token
header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
  
{
     "grant_type":"password",  
     "username":"jojo",
     "password":"123456",
     "scope":"all"
}
返回值
{
    "access_token":"630e2ccc-a5ce-4486-a855-ba755eb3d0d2",
    "token_type":"bearer",
    "refresh_token":"bbb36b54-61b2-4d86-aed3-91c5135174c3",
    "expires_in":43199,
    "scope":"all"
}
**刷新token **
获取token post请求
http://localhost:8060/oauth/token
header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
  
{
     "grant_type":"refresh_token",
     "refresh_token":"all"
}
返回值
{
    "access_token":"630e2ccc-a5ce-4486-a855-ba755eb3d0d2",
    "token_type":"bearer",
    "refresh_token":"bbb36b54-61b2-4d86-aed3-91c5135174c3",
    "expires_in":43199,
    "scope":"all"
}
**自定义账号密码登陆**
POST
http://localhost:8060/authentication/form
header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
body
{
    "username":"test",
    "password":"123456"
}
返回值
{
    "access_token":"630e2ccc-a5ce-4486-a855-ba755eb3d0d2",
    "token_type":"bearer",
    "refresh_token":"bbb36b54-61b2-4d86-aed3-91c5135174c3",
    "expires_in":43199,
    "scope":"all"
}
**自定义手机号短信验证码登陆**
获取短信
GET
http://localhost:8060/code/sms
body
{
    "mobile":"13612345678"
}
POST
http://localhost:8060/authentication/mobile
header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
body
{
    "mobile":"test",
    "sms":"246053"
}
返回值
{
    "access_token":"630e2ccc-a5ce-4486-a855-ba755eb3d0d2",
    "token_type":"bearer",
    "refresh_token":"bbb36b54-61b2-4d86-aed3-91c5135174c3",
    "expires_in":43199,
    "scope":"all"
}
**访问方式**
http://localhost:8060/user
header 
{
"Authorization":"bearer 5fe6b2c3-f69c-4ddc-a36a-367cdf9479a3"      即 bearer accesstoken
}

+ 0 - 13
base/common-security/src/main/java/com.yihu.base.security/AuthorizationServerConfig.java

@ -1,13 +0,0 @@
package com.yihu.base.security;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
/**
 * Created by chenweida on 2017/12/4.
 */
@Configuration
@EnableAuthorizationServer  //开启授权服务器
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
}

+ 0 - 14
base/common-security/src/main/java/com.yihu.base.security/ResourceServerConfig.java

@ -1,14 +0,0 @@
package com.yihu.base.security;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
/**
 * Created by chenweida on 2017/12/4.
 */
@Configuration
@EnableResourceServer  //开启资源服务器
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
}

+ 25 - 0
base/common-security/src/main/java/com.yihu.base.security/SercurityConfig.java

@ -0,0 +1,25 @@
package com.yihu.base.security;
import com.yihu.base.security.sms.sender.DefaultSmsCodeSender;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
 * Created by chenweida on 2017/12/4.
 */
@Configuration
public class SercurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    @ConditionalOnMissingBean
    public DefaultSmsCodeSender defaultSmsCodeSender() {
        return new DefaultSmsCodeSender();
    }
}

+ 102 - 0
base/common-security/src/main/java/com.yihu.base.security/config/AuthorizationServerConfig.java

@ -0,0 +1,102 @@
package com.yihu.base.security.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.base.security.properties.AccessTokenPorperties;
import com.yihu.base.security.properties.SecurityProperties;
import com.yihu.base.security.rbas.ClientServiceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import javax.annotation.Resource;
import javax.sql.DataSource;
/**
 * Created by chenweida on 2017/12/4.
 */
@Configuration
@EnableAuthorizationServer  //开启授权服务器
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private ClientServiceProvider clientDetailsService;
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private AccessTokenPorperties accessTokenPorperties;
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(oAuth2AuthenticationManager())
                .tokenStore(tokenStore())
                .userDetailsService(userDetailsService)
                .tokenServices(defaultTokenServices());
        //endpoints.setClientDetailsService(clientDetailsService);
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource)
                .passwordEncoder(passwordEncoder)
                .clients(clientDetailsService)
        ;
    }
    @Bean
    ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper;
    }
    @Bean
    @Primary
    OAuth2AuthenticationManager oAuth2AuthenticationManager() {
        OAuth2AuthenticationManager oAuth2AuthenticationManager = new OAuth2AuthenticationManager();
        oAuth2AuthenticationManager.setClientDetailsService(clientDetailsService);
        oAuth2AuthenticationManager.setTokenServices(defaultTokenServices());
        return oAuth2AuthenticationManager;
    }
    //==========================token相关配置=================================
    @Bean
    @Primary
    DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setAccessTokenValiditySeconds(60 * 60 * accessTokenPorperties.getAccessTokenValidityHours()); //默认2小时
        defaultTokenServices.setRefreshTokenValiditySeconds(60 * 60 * accessTokenPorperties.getRefreshTokenValidityHours());//默认2小时
        return defaultTokenServices;
    }
    @Bean
    @Primary
    TokenStore tokenStore() {
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        redisTokenStore.setPrefix(SecurityProperties.prefix_accesstoken);
        return redisTokenStore;
    }
}

+ 62 - 0
base/common-security/src/main/java/com.yihu.base.security/config/ResourceServerConfig.java

@ -0,0 +1,62 @@
package com.yihu.base.security.config;
import com.yihu.base.security.properties.SecurityProperties;
import com.yihu.base.security.rbas.IRbasService;
import com.yihu.base.security.rbas.provider.AuthorizeConfigProviderManager;
import com.yihu.base.security.sms.SmsCodeAuthenticationSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
/**
 * Created by chenweida on 2017/12/4.
 */
@Configuration
@EnableResourceServer  //开启资源服务器
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Autowired
    protected AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    protected AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private OAuth2AuthenticationManager authenticationManager;
    @Autowired
    private TokenStore redisTokenStore;
    @Autowired
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;
    @Autowired
    private AuthorizeConfigProviderManager authorizeConfigProviderManager;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()//设置验证码 账号密码登陆
                    .loginPage(SecurityProperties.formLoginPage)
                    .loginProcessingUrl(SecurityProperties.formLogin)
                    .successHandler(authenticationSuccessHandler)
                    .failureHandler(authenticationFailureHandler)
                .and()
                    .apply(smsCodeAuthenticationSecurityConfig)  //添加自定义短信登陆
                .and()
                    .csrf().disable();
        //验证路径
        authorizeConfigProviderManager.condfig(http.authorizeRequests());
    }
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.
                authenticationManager(authenticationManager).
                tokenStore(redisTokenStore);
    }
}

+ 19 - 17
base/common-security/src/main/java/com.yihu.base.security/hander/BaseAuthenticationSuccessHandler.java

@ -4,11 +4,13 @@
package com.yihu.base.security.hander;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.base.security.rbas.ClientServiceProvider;
import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.codec.Base64;
@ -16,9 +18,11 @@ import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -27,33 +31,34 @@ import java.io.UnsupportedEncodingException;
/**
 * @author chenweida
 * <p>
 * 账号密码提交需要在 head 中添加 Basic clientID:cliengSecurty
 *         <p>
 *         账号密码提交需要在 head 中添加 Basic clientID:cliengSecurty
 */
@Component("BaseAuthenticationSuccessHandler")
public class BaseAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private ClientDetailsService clientDetailsService;
    private ObjectMapper objectMapper;
    @Autowired
    private AuthorizationServerTokenServices authorizationServerTokenServices;
    private ClientServiceProvider clientDetailsService;
    @Autowired
    private AuthorizationServerTokenServices defaultTokenServices;
    /*
     * (non-Javadoc)
     *
     * @see org.springframework.security.web.authentication.
     * AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.
     * HttpServletRequest, javax.servlet.http.HttpServletResponse,
     * org.springframework.security.core.Authentication)
     */
         * (non-Javadoc)
         *
         * @see org.springframework.security.web.authentication.
         * AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.
         * HttpServletRequest, javax.servlet.http.HttpServletResponse,
         * org.springframework.security.core.Authentication)
         */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Basic ")) {
        if (org.springframework.util.StringUtils.isEmpty(header) || (!header.startsWith("Basic "))) {
            throw new UnapprovedClientAuthenticationException("请求头没有client信息");
        }
        //解析头部的basic信息
@ -77,7 +82,7 @@ public class BaseAuthenticationSuccessHandler extends SavedRequestAwareAuthentic
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        OAuth2AccessToken token = defaultTokenServices.createAccessToken(oAuth2Authentication);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(token));
@ -115,7 +120,4 @@ public class BaseAuthenticationSuccessHandler extends SavedRequestAwareAuthentic
        return new String[]{token.substring(0, delim), token.substring(delim + 1)};
    }
    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(new String(Base64.encode("cwd:cwd".getBytes()), "UTF-8"));//   Y3dkOmN3ZA==
    }
}

+ 20 - 22
base/common-security/src/main/java/com.yihu.base.security/hander/BseAuthenctiationFailureHandler.java

@ -1,12 +1,14 @@
/**
 * 
 *
 */
package com.yihu.base.security.hander;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.base.security.vo.SimpleResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
@ -17,30 +19,26 @@ import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @author zhailiang
 *
 * @author chenweida
 */
@Component("BseAuthenctiationFailureHandler")
public class BseAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ObjectMapper objectMapper;
	
	/* (non-Javadoc)
	 * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
	 */
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
										AuthenticationException exception) throws IOException, ServletException {
		
		logger.info("登录失败");
		
		
	}
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        logger.info("登录失败");
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(exception.getMessage())));
    }
}

+ 34 - 0
base/common-security/src/main/java/com.yihu.base.security/properties/AccessTokenPorperties.java

@ -0,0 +1,34 @@
package com.yihu.base.security.properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
 * Created by chenweida on 2017/12/5.
 */
@Component
public class AccessTokenPorperties {
    @Value("${security.oauth2.token.accessTokenValidityHours}")
    private Integer accessTokenValidityHours = 2; //accesstoken超时时间
    @Value("${security.oauth2.token.refreshTokenValidityHours}")
    private Integer refreshTokenValidityHours = 2;//刷新token过期时间
    public Integer getAccessTokenValidityHours() {
        return accessTokenValidityHours;
    }
    public void setAccessTokenValidityHours(Integer accessTokenValidityHours) {
        this.accessTokenValidityHours = accessTokenValidityHours;
    }
    public Integer getRefreshTokenValidityHours() {
        return refreshTokenValidityHours;
    }
    public void setRefreshTokenValidityHours(Integer refreshTokenValidityHours) {
        this.refreshTokenValidityHours = refreshTokenValidityHours;
    }
}

+ 21 - 0
base/common-security/src/main/java/com.yihu.base.security/properties/SecurityProperties.java

@ -0,0 +1,21 @@
package com.yihu.base.security.properties;
/**
 * Created by chenweida on 2017/12/4.\
 * 安全框架配置信息
 */
public class SecurityProperties {
    //放在redis中的前缀
    public final static String prefix_accesstoken = "security:oauth2:";  //oauth2 的前缀
    public final static String prefix_sms = "security:oauth2:smsLogin:";  //短信验证码的前缀
    //表单登陆相关信息
    public final static String formLogin = "/authentication/form";//账号密码的路径
    public final static String formLoginPage = "/denglu.html";
    //短信登陆相关信息
    public final static String mobileLogin = "/authentication/mobile"; //手机号短信登陆的路径
    public final static String mobileLoginAccountKey = "mobile";
    public final static String mobileLoginSmsKey = "sms";
    public final static String mobileSendSms = "/code/sms";     //发送短信接口的路径
}

+ 34 - 0
base/common-security/src/main/java/com.yihu.base.security/properties/SmsValidateProperties.java

@ -0,0 +1,34 @@
package com.yihu.base.security.properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
 * Created by chenweida on 2017/12/5.
 */
@Component
public class SmsValidateProperties {
    @Value("${security.oauth2.sms.expireIn}")
    private Integer expireIn = 1; //短信验证码过期时间
    @Value("${security.oauth2.sms.length}")
    private Integer length = 6; //短信验证码过期时间
    public Integer getExpireIn() {
        return expireIn;
    }
    public void setExpireIn(Integer expireIn) {
        this.expireIn = expireIn;
    }
    public Integer getLength() {
        return length;
    }
    public void setLength(Integer length) {
        this.length = length;
    }
}

+ 9 - 0
base/common-security/src/main/java/com.yihu.base.security/rbas/ClientServiceProvider.java

@ -0,0 +1,9 @@
package com.yihu.base.security.rbas;
import org.springframework.security.oauth2.provider.ClientDetailsService;
/**
 * Created by chenweida on 2017/12/5.
 */
public interface ClientServiceProvider extends ClientDetailsService {
}

+ 1 - 1
base/common-security/src/main/java/com.yihu.base.security/rbas/RbasService.java

@ -8,7 +8,7 @@ import javax.servlet.http.HttpServletRequest;
 * Created by chenweida on 2017/12/1.
 * 需要权限认证的使用这个接口
 */
public interface RbasService {
public interface IRbasService {
     Boolean hasPerssion(HttpServletRequest request, Authentication authentication) ;
}

+ 11 - 0
base/common-security/src/main/java/com.yihu.base.security/rbas/provider/AuthorizeConfigProvider.java

@ -0,0 +1,11 @@
package com.yihu.base.security.rbas.provider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
/**
 * Created by chenweida on 2017/12/5.
 */
public interface AuthorizeConfigProvider {
    void condfig(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config);
}

+ 24 - 0
base/common-security/src/main/java/com.yihu.base.security/rbas/provider/AuthorizeConfigProviderManager.java

@ -0,0 +1,24 @@
package com.yihu.base.security.rbas.provider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.stereotype.Component;
import java.util.Set;
/**
 * Created by chenweida on 2017/12/5.
 * 授权路径
 */
@Component
public class AuthorizeConfigProviderManager {
    @Autowired
    Set<AuthorizeConfigProvider> authorizeConfigProviders;
   public void condfig(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {
        for (AuthorizeConfigProvider authorizeConfigProvider : authorizeConfigProviders) {
            authorizeConfigProvider.condfig(config);
        }
    }
}

+ 28 - 0
base/common-security/src/main/java/com.yihu.base.security/rbas/provider/PerssionAllAuthorizeConfigProvider.java

@ -0,0 +1,28 @@
package com.yihu.base.security.rbas.provider;
import com.yihu.base.security.properties.SecurityProperties;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.stereotype.Component;
/**
 * Created by chenweida on 2017/12/5.
 * 允许通过的路径
 */
@Component
@Order(Integer.MIN_VALUE)
public class PerssionAllAuthorizeConfigProvider implements AuthorizeConfigProvider {
    @Override
    public void condfig(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {
        config
                .antMatchers(
                        SecurityProperties.formLogin,
                        SecurityProperties.formLoginPage,
                        SecurityProperties.mobileLogin,
                        SecurityProperties.mobileSendSms
                ).permitAll();
    }
}

+ 20 - 0
base/common-security/src/main/java/com.yihu.base.security/rbas/provider/RbasAuthorizeConfigProvider.java

@ -0,0 +1,20 @@
package com.yihu.base.security.rbas.provider;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.stereotype.Component;
/**
 * Created by chenweida on 2017/12/5.
 * 角色认证
 */
@Component
@Order(Integer.MAX_VALUE)
public class RbasAuthorizeConfigProvider implements AuthorizeConfigProvider {
    @Override
    public void condfig(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {
        // config.anyRequest().access("@rbasService.hasPerssion(request,authentication)");
        config.anyRequest().access("@rbasbean.hello()");
    }
}

+ 112 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationFilter.java

@ -0,0 +1,112 @@
/**
 * 
 */
package com.yihu.base.security.sms;
import com.yihu.base.security.properties.SecurityProperties;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author zhailiang
 *
 */
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	// ~ Static fields/initializers
	// =====================================================================================
	private String mobileParameter = SecurityProperties.mobileLoginAccountKey;
	private boolean postOnly = true;
	// ~ Constructors
	// ===================================================================================================
	public SmsCodeAuthenticationFilter() {
		super(new AntPathRequestMatcher(SecurityProperties.mobileLogin, "POST"));
	}
	// ~ Methods
	// ========================================================================================================
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		if (postOnly && !request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}
		String mobile = obtainMobile(request);
		if (mobile == null) {
			mobile = "";
		}
		mobile = mobile.trim();
		SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile);
		// Allow subclasses to set the "details" property
		setDetails(request, authRequest);
		return this.getAuthenticationManager().authenticate(authRequest);
	}
	/**
	 * 获取手机号
	 */
	protected String obtainMobile(HttpServletRequest request) {
		return request.getParameter(mobileParameter);
	}
	/**
	 * Provided so that subclasses may configure what is put into the
	 * authentication request's details property.
	 *
	 * @param request
	 *            that an authentication request is being created for
	 * @param authRequest
	 *            the authentication request object that should have its details
	 *            set
	 */
	protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) {
		authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
	}
	/**
	 * Sets the parameter name which will be used to obtain the username from
	 * the login request.
	 *
	 * @param usernameParameter
	 *            the parameter name. Defaults to "username".
	 */
	public void setMobileParameter(String usernameParameter) {
		Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
		this.mobileParameter = usernameParameter;
	}
	/**
	 * Defines whether only HTTP POST requests will be allowed by this filter.
	 * If set to true, and an authentication request is received which is not a
	 * POST request, an exception will be raised immediately and authentication
	 * will not be attempted. The <tt>unsuccessfulAuthentication()</tt> method
	 * will be called as if handling a failed authentication.
	 * <p>
	 * Defaults to <tt>true</tt> but may be overridden by subclasses.
	 */
	public void setPostOnly(boolean postOnly) {
		this.postOnly = postOnly;
	}
	public final String getMobileParameter() {
		return mobileParameter;
	}
}

+ 64 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationProvider.java

@ -0,0 +1,64 @@
/**
 * 
 */
package com.yihu.base.security.sms;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
 * @author zhailiang
 *
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {
	private UserDetailsService userDetailsService;
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.authentication.AuthenticationProvider#
	 * authenticate(org.springframework.security.core.Authentication)
	 */
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
		
		UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
		if (user == null) {
			throw new InternalAuthenticationServiceException("无法获取用户信息");
		}
		
		SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user, user.getAuthorities());
		
		authenticationResult.setDetails(authenticationToken.getDetails());
		return authenticationResult;
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.authentication.AuthenticationProvider#
	 * supports(java.lang.Class)
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
	}
	public UserDetailsService getUserDetailsService() {
		return userDetailsService;
	}
	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}
}

+ 49 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationSecurityConfig.java

@ -0,0 +1,49 @@
/**
 * 
 */
package com.yihu.base.security.sms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
/**
 * @author zhailiang
 *
 */
@Component
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
	
	@Autowired
	private AuthenticationSuccessHandler authenticationSuccessHandler;
	
	@Autowired
	private AuthenticationFailureHandler authenticationFailureHandler;
	
	@Autowired
	private UserDetailsService userDetailsService;
	
	@Override
	public void configure(HttpSecurity http) throws Exception {
		
		SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
		smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
		smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
		smsCodeAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
		
		SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
		smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService);
		
		http.authenticationProvider(smsCodeAuthenticationProvider)
			.addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
		
	}
}

+ 81 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/SmsCodeAuthenticationToken.java

@ -0,0 +1,81 @@
/**
 * 
 */
package com.yihu.base.security.sms;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import java.util.Collection;
/**
 * @author zhailiang
 *
 */
public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {
	private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
	// ~ Instance fields
	// ================================================================================================
	private final Object principal;
	// ~ Constructors
	// ===================================================================================================
	/**
	 * This constructor can be safely used by any code that wishes to create a
	 * <code>UsernamePasswordAuthenticationToken</code>, as the {@link #isAuthenticated()}
	 * will return <code>false</code>.
	 *
	 */
	public SmsCodeAuthenticationToken(String mobile) {
		super(null);
		this.principal = mobile;
		setAuthenticated(false);
	}
	/**
	 * This constructor should only be used by <code>AuthenticationManager</code> or
	 * <code>AuthenticationProvider</code> implementations that are satisfied with
	 * producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>)
	 * authentication token.
	 *
	 * @param principal
	 * @param credentials
	 * @param authorities
	 */
	public SmsCodeAuthenticationToken(Object principal,
			Collection<? extends GrantedAuthority> authorities) {
		super(authorities);
		this.principal = principal;
		super.setAuthenticated(true); // must use super, as we override
	}
	// ~ Methods
	// ========================================================================================================
	public Object getCredentials() {
		return null;
	}
	public Object getPrincipal() {
		return this.principal;
	}
	public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
		if (isAuthenticated) {
			throw new IllegalArgumentException(
					"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
		}
		super.setAuthenticated(false);
	}
	@Override
	public void eraseCredentials() {
		super.eraseCredentials();
	}
}

+ 40 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/controller/SmsController.java

@ -0,0 +1,40 @@
package com.yihu.base.security.sms.controller;
import com.yihu.base.security.properties.SecurityProperties;
import com.yihu.base.security.sms.process.SmsValidateCodeProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by chenweida on 2017/12/5.
 */
@RestController
public class SmsController {
    @Autowired
    private SmsValidateCodeProcessor smsValidateCodeProcessor;
    /**
     * 创建验证码
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping(SecurityProperties.mobileSendSms)
    public void createCode(
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        //获取手机号
        String mobile = request.getParameter(SecurityProperties.mobileLoginAccountKey);
        //发送短信验证码并且保存到redis中
        smsValidateCodeProcessor.create(new ServletWebRequest(request, response));
    }
}

+ 23 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/exception/ValidateCodeException.java

@ -0,0 +1,23 @@
/**
 * 
 */
package com.yihu.base.security.sms.exception;
import org.springframework.security.core.AuthenticationException;
/**
 * @author chenweida
 *
 */
public class ValidateCodeException extends AuthenticationException {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7285211528095468156L;
	public ValidateCodeException(String msg) {
		super(msg);
	}
}

+ 71 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/filter/SmsvalidateCodeFilter.java

@ -0,0 +1,71 @@
/**
 *
 */
package com.yihu.base.security.sms.filter;
import com.yihu.base.security.properties.SecurityProperties;
import com.yihu.base.security.sms.exception.ValidateCodeException;
import com.yihu.base.security.sms.process.SmsValidateCodeProcessor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @author chenweida
 */
@Component("smsvalidateCodeFilter")
public class SmsvalidateCodeFilter extends OncePerRequestFilter implements InitializingBean {
    /**
     * 验证码校验失败处理器
     */
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    /**
     * 验证请求url与配置的url是否匹配的工具类
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();
    @Autowired
    private SmsValidateCodeProcessor smsValidateCodeProcessor;
    /*
     * (non-Javadoc)
     *
     * @see
     * org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(
     * javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        if (!StringUtils.equalsIgnoreCase(request.getMethod(), "get")) {
            if (pathMatcher.match(SecurityProperties.mobileSendSms, request.getRequestURI())) {
                logger.info("校验请求(" + request.getRequestURI() + ")中的验证码");
                try {
                    smsValidateCodeProcessor
                            .validate(new ServletWebRequest(request, response));
                    logger.info("验证码校验通过");
                } catch (ValidateCodeException exception) {
                    authenticationFailureHandler.onAuthenticationFailure(request, response, exception);
                    return;
                }
            }
        }
        chain.doFilter(request, response);
    }
}

+ 41 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/generator/SmsValidateCodeGenerator.java

@ -0,0 +1,41 @@
package com.yihu.base.security.sms.generator;
import com.yihu.base.security.properties.SmsValidateProperties;
import com.yihu.base.security.sms.vo.ValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import java.util.Random;
/**
 * Created by chenweida on 2017/12/5.
 * 短信验证码生成器
 */
@Component
public class SmsValidateCodeGenerator implements ValidateCodeGenerator {
    @Autowired
    private SmsValidateProperties smsValidateProperties;
    @Override
    public ValidateCode generate(ServletWebRequest request) {
        String code = getFixLenthString(smsValidateProperties.getLength());
        ValidateCode validateCode = new ValidateCode(code, smsValidateProperties.getExpireIn());
        return validateCode;
    }
    /*
 * 返回长度为【strLength】的随机数,在前面补0
 */
    private String getFixLenthString(int strLength) {
        Random rm = new Random();
        // 获得随机数
        double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
        // 将获得的获得随机数转化为字符串
        String fixLenthString = String.valueOf(pross);
        // 返回固定的长度的随机数
        return fixLenthString.substring(1, strLength + 1);
    }
}

+ 17 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/generator/ValidateCodeGenerator.java

@ -0,0 +1,17 @@
/**
 * 
 */
package com.yihu.base.security.sms.generator;
import com.yihu.base.security.sms.vo.ValidateCode;
import org.springframework.web.context.request.ServletWebRequest;
/**
 * @author chenweida
 *
 */
public interface ValidateCodeGenerator {
	ValidateCode generate(ServletWebRequest request);
	
}

+ 160 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/process/SmsValidateCodeProcessor.java

@ -0,0 +1,160 @@
/**
 *
 */
package com.yihu.base.security.sms.process;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.yihu.base.security.properties.SecurityProperties;
import com.yihu.base.security.sms.exception.ValidateCodeException;
import com.yihu.base.security.sms.generator.SmsValidateCodeGenerator;
import com.yihu.base.security.sms.generator.ValidateCodeGenerator;
import com.yihu.base.security.sms.sender.SmsCodeSender;
import com.yihu.base.security.sms.vo.ValidateCode;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import java.util.Map;
/**
 * @author chenweida
 */
@Component
public class SmsValidateCodeProcessor implements ValidateCodeProcessor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SmsCodeSender smsCodeSender;
    @Autowired
    private SmsValidateCodeGenerator smsValidateCodeGenerator;
    /*
     * (non-Javadoc)
     *
     * @see
     * com.imooc.security.core.validate.code.ValidateCodeProcessor#create(org.
     * springframework.web.context.request.ServletWebRequest)
     */
    @Override
    public void create(ServletWebRequest request) throws Exception {
        ValidateCode validateCode = generate(request);
        save(request, validateCode);
        send(request, validateCode);
    }
    /**
     * 生成校验码
     *
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    private ValidateCode generate(ServletWebRequest request) {
        return smsValidateCodeGenerator.generate(request);
    }
    /**
     * 保存校验码
     *
     * @param request
     * @param validateCode
     */
    private void save(ServletWebRequest request, ValidateCode validateCode) {
        JSONObject jo = new JSONObject();
        jo.put("code", validateCode.getCode());
        jo.put("expireTime", validateCode.getExpireTimeString());
        redisTemplate.opsForValue().set(key(request), jo.toString());
    }
    /**
     * 删除严验证码
     *
     * @param request
     */
    private void reomve(ServletWebRequest request) {
        redisTemplate.delete((key(request)));
    }
    /**
     * 获取校验码
     *
     * @param request
     */
    private ValidateCode get(ServletWebRequest request) {
        String joStr = redisTemplate.opsForValue().get(key(request));
        if (StringUtils.isNotBlank(joStr)) {
            JSONObject jo = JSONObject.fromObject(joStr);
            ValidateCode validateCode = new ValidateCode();
            validateCode.setCode(jo.getString("code"));
            validateCode.setExpireTimeString(jo.getString("expireTime"));
            return validateCode;
        } else {
            return null;
        }
    }
    /**
     * 拼凑放在redis的key
     *
     * @param request
     * @return
     */
    private String key(ServletWebRequest request) {
        return SecurityProperties.prefix_sms + request.getParameter(SecurityProperties.mobileLoginAccountKey);
    }
    /**
     * 发送校验码,由子类实现
     *
     * @param request
     * @param validateCode
     * @throws Exception
     */
    protected void send(ServletWebRequest request, ValidateCode validateCode) throws Exception {
        smsCodeSender.send(request.getParameter(SecurityProperties.mobileLoginAccountKey), validateCode.getCode());
    }
    @SuppressWarnings("unchecked")
    @Override
    public void validate(ServletWebRequest request) {
        String sessionKey = key(request);
        //获取验证码
        ValidateCode validateCode = get(request);
        String codeInRequest;
        //获取请求中的验证码
        try {
            codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),
                    SecurityProperties.mobileSendSms);
        } catch (ServletRequestBindingException e) {
            throw new ValidateCodeException("获取验证码的值失败");
        }
        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码的值不能为空");
        }
        if (validateCode == null) {
            throw new ValidateCodeException("验证码不存在");
        }
        if (validateCode.isExpried()) {
            reomve(request);
            throw new ValidateCodeException("验证码已过期");
        }
        if (!StringUtils.equals(validateCode.getCode(), codeInRequest)) {
            throw new ValidateCodeException("验证码不匹配");
        }
        //验证成功删除验证码
        reomve(request);
    }
}

+ 32 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/process/ValidateCodeProcessor.java

@ -0,0 +1,32 @@
/**
 * 
 */
package com.yihu.base.security.sms.process;
import org.springframework.web.context.request.ServletWebRequest;
/**
 * 校验码处理器,封装不同校验码的处理逻辑
 * 
 * @author chenweida
 *
 */
public interface ValidateCodeProcessor {
	/**
	 * 创建校验码
	 * 
	 * @param request
	 * @throws Exception
	 */
	void create(ServletWebRequest request) throws Exception;
	/**
	 * 校验验证码
	 * 
	 * @param servletWebRequest
	 * @throws Exception
	 */
	void validate(ServletWebRequest servletWebRequest);
}

+ 25 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/sender/DefaultSmsCodeSender.java

@ -0,0 +1,25 @@
/**
 *
 */
package com.yihu.base.security.sms.sender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
 * @author chenweida
 *         默认的短信发送 没有具体实现
 */
public class DefaultSmsCodeSender implements SmsCodeSender {
    private Logger logger = LoggerFactory.getLogger(DefaultSmsCodeSender.class);
    /* (non-Javadoc)
     * @see com.imooc.security.core.validate.code.sms.SmsCodeSender#send(java.lang.String, java.lang.String)
     */
    @Override
    public void send(String mobile, String code) {
        logger.info("向手机" + mobile + "发送短信验证码" + code);
    }
}

+ 14 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/sender/SmsCodeSender.java

@ -0,0 +1,14 @@
/**
 * 
 */
package com.yihu.base.security.sms.sender;
/**
 * @author chenweida
 *
 */
public interface SmsCodeSender {
	
	void send(String mobile, String code);
}

+ 62 - 0
base/common-security/src/main/java/com.yihu.base.security/sms/vo/ValidateCode.java

@ -0,0 +1,62 @@
/**
 *
 */
package com.yihu.base.security.sms.vo;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
 * @author chenweida
 */
public class ValidateCode implements Serializable {
    private String code;
    private LocalDateTime expireTime;
    public ValidateCode() {
    }
    public ValidateCode(String code, int expireIn) {
        this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
    }
    public ValidateCode(String code, LocalDateTime expireTime) {
        this.code = code;
        this.expireTime = expireTime;
    }
    public boolean isExpried() {
        return LocalDateTime.now().isAfter(expireTime);
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public LocalDateTime getExpireTime() {
        return expireTime;
    }
    public void setExpireTime(LocalDateTime expireTime) {
        this.expireTime = expireTime;
    }
    public String getExpireTimeString() {
        return expireTime.format(DateTimeFormatter.ISO_DATE_TIME);
    }
    public void setExpireTimeString(String strTime) {
        expireTime = LocalDateTime.parse(strTime, DateTimeFormatter.ISO_DATE_TIME);
    }
}

+ 25 - 0
base/common-security/src/main/java/com.yihu.base.security/vo/SimpleResponse.java

@ -0,0 +1,25 @@
/**
 * 
 */
package com.yihu.base.security.vo;
/**
 * chenweida
 */
public class SimpleResponse {
	
	public SimpleResponse(Object content){
		this.content = content;
	}
	
	private Object content;
	public Object getContent() {
		return content;
	}
	public void setContent(Object content) {
		this.content = content;
	}
	
}

+ 40 - 0
base/common-security/src/main/resources/template.yml

@ -0,0 +1,40 @@
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    max-active: 50
    max-idle: 50 #最大空闲连接
    min-idle: 10 #最小空闲连接
    validation-query-timeout: 20
    log-validation-errors: true
    validation-interval: 60000 #避免过度验证,保证验证不超过这个频率——以毫秒为单位。如果一个连接应该被验证,但上次验证未达到指定间隔,将不再次验证。
    validation-query: SELECT 1 #SQL 查询, 用来验证从连接池取出的连接, 在将连接返回给调用者之前。 如果指定, 则查询必须是一个SQL SELECT 并且必须返回至少一行记录
    test-on-borrow: true #指明是否在从池中取出连接前进行检验, 如果检验失败, 则从池中去除连接并尝试取出另一个。注意: 设置为true 后如果要生效,validationQuery 参数必须设置为非空字符串
    test-on-return: true #指明是否在归还到池中前进行检验 注意: 设置为true 后如果要生效validationQuery 参数必须设置为非空字符串
    idle-timeout: 30000
    connection-test-query: SELECT 1
    num-tests-per-eviction-run: 50 #在每次空闲连接回收器线程(如果有)运行时检查的连接数量,最好和maxActive
    test-while-idle: true #指明连接是否被空闲连接回收器(如果有)进行检验,如果检测失败,则连接将被从池中去除
    min-evictable-idle-time-millis: 3600000 #连接池中连接,在时间段内一直空闲,被逐出连接池的时间(1000*60*60),以毫秒为单位
    time-between-eviction-runs-millis: 300000 #在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位,一般比minEvictableIdleTimeMillis小
    url: jdbc:mysql://127.0.0.1/oauth?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: root
    password: 123456
  redis:
    host: 172.19.103.88 # Redis server host.
    port: 6379 # Redis server port.
    database: 1
  aop:
    proxy-target-class: true
security:
  oauth2:
    token:
      accessTokenValidityHours: 2 # 2小时
      refreshTokenValidityHours: 2 # 2小时
    sms:
      expireIn: 1 ##1分钟
      length: 6 #验证码长度

+ 18 - 0
common/common-entity/src/main/java/META-INF/persistence.xml

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="NewPersistenceUnit">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>com.yihu.jw.base.user.BaseLoginAccountDO</class>
        <properties>
            <property name="hibernate.connection.url" value="jdbc:mysql://172.19.103.77:3306/"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.username" value=""/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

+ 0 - 1
common/common-entity/src/main/java/com/yihu/jw/base/user/BaseEmployRoleDO.java

@ -4,7 +4,6 @@ import com.yihu.jw.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**

+ 31 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseLoginRequestMapping.java

@ -0,0 +1,31 @@
package com.yihu.jw.rm.base;
public class BaseLoginRequestMapping {
    public static final String api_common = BaseRequestMapping.api_base_common + "/login";
    /**
     * 用户账号类型
     */
    public static class BaseLoginAccount {
        public static final String api_create = "/baseLoginAccount";
        public static final String api_update = "/baseLoginAccount";
        public static final String api_delete = "/baseLoginAccount/{ids}";
        public static final String api_getById = "/baseLoginAccount/{id}";
        public static final String api_getOne="/baseLoginAccount";
        public static final String message_success_create = "baseLoginAccount create success";
        public static final String message_success_update = "baseLoginAccount update success";
        public static final String message_success_find = "baseLoginAccount find success";
        public static final String message_success_delete = "baseLoginAccount delete success";
        public static final String message_fail_id_is_null = "id is null";
        public static final String message_fail_saasid_is_null = "saasId is null";
        public static final String message_fail_id_no_exist = "id no exist";
        public static final String message_fail_saasid_no_exist = "saasId no exist";
        public static final String message_fail_role_no_exist = "baseLoginAccount no exist";
        public static final String message_param_id_is_null = "baseLoginAccount id param cannot be null";
        public static final String message_param_saasid_is_null = "baseLoginAccount saasId param cannot be null";
    }
}

+ 52 - 1
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseRequestMapping.java

@ -96,6 +96,57 @@ public class BaseRequestMapping {
    }
    //SystemDict常量
    public static class SystemDict{
        public static final String message_success_create="SystemDict create success";
        public static final String message_success_update="SystemDict update success";
        public static final String message_success_find="SystemDict find success";
        public static final String message_success_find_saass="SystemDict find success";
        public static final String message_success_delete="SystemDict delete success";
        public static final String message_fail_name_exist="SystemDict name exist";
        public static final String message_fail_name_is_null="name is null";
        public static final String message_fail_id_is_null="id is null";
        public static final String message_fail_id_no_exist="id no exist";
        public static final String api_create="/systemDict";
        public static final String api_update="/systemDict";
        public static final String api_delete="/systemDict";
        public static final String api_getById="/getById";
        public static final String api_getList="/systemDict/list";
        public static final String api_getListNoPage="/systemDict/listNoPage";
    }
    //SystemDictList常量
    public static class SystemDictList{
        public static final String message_success_create="SystemDictList create success";
        public static final String message_success_update="SystemDictList update success";
        public static final String message_success_find="SystemDictList find success";
        public static final String message_success_find_saass="SystemDictList find success";
        public static final String message_success_delete="SystemDictList delete success";
        public static final String message_fail_name_exist="SystemDictList name exist";
        public static final String message_fail_name_is_null="name is null";
        public static final String message_fail_id_is_null="id is null";
        public static final String message_fail_id_no_exist="id no exist";
        public static final String api_create="/systemDictList";
        public static final String api_update="/systemDictList";
        public static final String api_delete="/systemDictList";
        public static final String api_getById="/getById";
        public static final String api_getList="/systemDictList/list";
        public static final String api_getListNoPage="/systemDictList/listNoPage";
        public static final String api_getChildren="/systemDictList/children/{id}";
    }
/*
    //d行政人员模块
    public static class Employee{
        public static final String message_success_create="employee create success";
@ -119,5 +170,5 @@ public class BaseRequestMapping {
        public static final String api_getEmployeeByAccount="/getEmployeeByAccount";
        public static final String api_getEmployeeNoPage="/getEmployeeNoPage";
    }
    }*/
}

+ 81 - 2
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseUserRequestMapping.java

@ -12,7 +12,7 @@ public class BaseUserRequestMapping {
        public static final String api_delete = "/baseRole/{ids}";
        public static final String api_getById = "/baseRole/{id}";
        public static final String api_getList="/baseRole/list";
        public static final String api_getOne="/baseRole/one";
        public static final String api_getOne="/baseRole";
        public static final String api_getListNoPage="/baseRole/listNoPage";
        public static final String message_success_create = "baseRole create success";
@ -36,7 +36,7 @@ public class BaseUserRequestMapping {
    /**
     * 用户
     */
    public class Employee {
    public class BaseEmploy {
        public static final String api_create = "/employee";
        public static final String api_update = "/employee";
        public static final String api_delete = "/employee/{ids}";
@ -44,6 +44,8 @@ public class BaseUserRequestMapping {
        public static final String api_getByUserId = "/employeeById/{userId}";
        public static final String api_getList="/employee/list";
        public static final String api_getListNoPage="/employee/listNoPage";
        public static final String api_getByEmployId = "/employee/{employId}";
        public static final String message_success_create="Employee create success";
        public static final String message_success_update="update Employee success";
@ -54,6 +56,83 @@ public class BaseUserRequestMapping {
        public static final String message_fail_name_is_null = "baseRole is null";
        public static final String message_fail_id_is_null = "id is null";
        public static final String message_fail_id_no_exist = "id no exist";
        public static final String message_fail_saasid_is_null = "saasId is null";
        public static final String message_param_saasid_is_null = "baseRole saasId param cannot be null";
        public static final String message_fail_saasid_no_exist = "saasId no exist";
    }
    /**
     * 用户角色
     */
    public class BaseEmployRole {
        public static final String api_create = "/employeeRole";
        public static final String api_update = "/employeeRole";
        public static final String api_delete = "/employeeRole/{ids}";
        public static final String api_getList="/employeeRole/list";
        public static final String api_getListNoPage="/employeeRole/listNoPage";
        public static final String message_success_create="employeeRole create success";
        public static final String message_success_update="update employeeRole success";
        public static final String message_success_delete="employeeRole delete success";
        public static final String message_success_find="employeeRole find success";
        public static final String message_fail_roleId_is_null = "roleId is null";
        public static final String message_fail_employId_is_null = "employId is null";
        public static final String message_fail_id_is_null = "id is null";
        public static final String message_fail_same_roleId = "same roleId";
        public static final String message_fail_employeeRole_no_exist = "employeeRole no exist";
    }
    /**
     * 基础菜单
     */
    public class BaseMenu {
        public static final String api_create = "/baseMenu";
        public static final String api_update = "/baseMenu";
        public static final String api_delete = "/baseMenu/{ids}";
        public static final String api_getOne = "/baseMenu/{id}";
        public static final String api_getchildren = "/baseMenu/{id}";
        public static final String api_getList="/baseMenu/list";
        public static final String api_getListNoPage="/baseMenu/listNoPage";
        public static final String message_success_create="baseMenu create success";
        public static final String message_success_update="update baseMenu success";
        public static final String message_success_delete="baseMenu delete success";
        public static final String message_success_find="baseMenu find success";
        public static final String message_fail_saasId_is_null = "saasId is null";
        public static final String message_fail_menuId_is_null = "menuId is null";
        public static final String message_fail_id_is_null = "id is null";
        public static final String message_fail_id_no_exist = "id no exist";
        public static final String message_fail_saasId_no_exist = "saasId no exist";
        public static final String message_param_saasid_is_null = "baseMenu saasId param cannot be null";
        public static final String message_param_parentId_is_null = "baseMenu parentId param cannot be null";
    }
    /**
     * 角色菜单
     */
    public class BaseRoleMenu {
        public static final String api_create = "/baseRoleMenu";
        public static final String api_update = "/baseRoleMenu";
        public static final String api_delete = "/baseRoleMenu/{ids}";
        public static final String api_getList="/baseRoleMenu/list";
        public static final String api_getListNoPage="/baseRoleMenu/listNoPage";
        public static final String message_success_create="baseRoleMenu create success";
        public static final String message_success_update="update baseRoleMenu success";
        public static final String message_success_delete="baseRoleMenu delete success";
        public static final String message_success_find="baseRoleMenu find success";
        public static final String message_fail_roleId_is_null = "roleId is null";
        public static final String message_fail_menuId_is_null = "menuId is null";
        public static final String message_fail_id_is_null = "id is null";
        public static final String message_fail_same_menuId = "same menuId";
        public static final String message_fail_baseRoleMenu_no_exist = "baseRoleMenu no exist";
    }
}

+ 23 - 1
svr-lib-parent-pom/pom.xml

@ -50,7 +50,9 @@
        <version.mysql>5.1.38</version.mysql>
        <version.jackson>2.8.1</version.jackson>
        <version.myCommon>1.0.0</version.myCommon>
        <version.spring>4.3.8.RELEASE</version.spring>
        <version.spring>4.3.10.RELEASE</version.spring>
        <version.spring.security>4.2.3.RELEASE</version.spring.security>
        <version.spring-data-jpa>1.11.3.RELEASE</version.spring-data-jpa>
        <version.spring-data-common>1.13.3.RELEASE</version.spring-data-common>
        <version.zipkin>1.24.0</version.zipkin>
@ -320,6 +322,11 @@
                <artifactId>spring-boot-starter-jdbc</artifactId>
                <version>${version.springBoot}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <version>${version.springBoot}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-aop</artifactId>
@ -361,6 +368,21 @@
                <version>${version.spring}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-core</artifactId>
                <version>${version.spring.security}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
                <version>${version.spring.security}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
                <version>${version.spring.security}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>

+ 6 - 1
svr/svr-base/pom.xml

@ -29,7 +29,8 @@
            <artifactId>common-exception</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.base</groupId>            <artifactId>common-util</artifactId>
            <groupId>com.yihu.base</groupId>
            <artifactId>common-util</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
@ -127,6 +128,10 @@
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    </dependencies>
    <build>
        <finalName>svr-base</finalName>

+ 17 - 0
svr/svr-base/src/main/java/META-INF/persistence.xml

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="NewPersistenceUnit">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.connection.url" value=""/>
            <property name="hibernate.connection.driver_class" value=""/>
            <property name="hibernate.connection.username" value=""/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

+ 6 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/base/controller/SystemController.java

@ -0,0 +1,6 @@
package com.yihu.jw.business.base.controller;
/**
 * Created by LiTaohong on 2017/11/30.
 */
public class SystemController {
}

+ 12 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/base/dao/SystemDictDao.java

@ -0,0 +1,12 @@
package com.yihu.jw.business.base.dao;
import com.yihu.jw.base.base.SaasModuleDO;
import com.yihu.jw.base.base.SystemDictDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by LiTaohong on 2017/12/01.
 */
public interface SystemDictDao extends PagingAndSortingRepository<SystemDictDO, String>, JpaSpecificationExecutor<SystemDictDO> {
}

+ 12 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/base/dao/SystemDictListDao.java

@ -0,0 +1,12 @@
package com.yihu.jw.business.base.dao;
import com.yihu.jw.base.base.SystemDictDO;
import com.yihu.jw.base.base.SystemDictListDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by LiTaohong on 2017/12/01.
 */
public interface SystemDictListDao extends PagingAndSortingRepository<SystemDictListDO, String>, JpaSpecificationExecutor<SystemDictListDO> {
}

+ 13 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/base/service/SystemDictListService.java

@ -0,0 +1,13 @@
package com.yihu.jw.business.base.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.base.SystemDictDO;
import com.yihu.jw.base.base.SystemDictListDO;
import com.yihu.jw.business.base.dao.SystemDictDao;
import com.yihu.jw.business.base.dao.SystemDictListDao;
/**
 * Created by LiTaohong on 2017/12/01.
 */
public class SystemDictListService extends BaseJpaService<SystemDictListDO, SystemDictListDao> {
}

+ 11 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/base/service/SystemDictService.java

@ -0,0 +1,11 @@
package com.yihu.jw.business.base.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.base.SystemDictDO;
import com.yihu.jw.business.base.dao.SystemDictDao;
/**
 * Created by LiTaohong on 2017/12/01.
 */
public class SystemDictService extends BaseJpaService<SystemDictDO, SystemDictDao> {
}

+ 17 - 1
svr/svr-base/src/main/java/com/yihu/jw/business/login/dao/BaseLoginAccountDao.java

@ -2,10 +2,26 @@ package com.yihu.jw.business.login.dao;
import com.yihu.jw.base.login.BaseLoginAccountDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/6/20.
 * Created by LiTaohong on 2017/12/05.
 * 账户表,识别用户类型,医生,行政人员等
 */
public interface BaseLoginAccountDao extends PagingAndSortingRepository<BaseLoginAccountDO, String>, JpaSpecificationExecutor<BaseLoginAccountDO> {
    /**
     * 删除用户账号
     * @param id
     */
    @Query("update BaseLoginAccountDO ba set ba.accountStatus = -1 where ba.id = ?1")
    void deleteAccount(String id);
    /**
     * 锁定用户账号
     * @param id
     */
    @Query("update BaseLoginAccountDO ba set ba.accountStatus = -2 where ba.id = ?1")
    void updateAccount(String id);
}

+ 75 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/login/service/BaseLoginAccountService.java

@ -0,0 +1,75 @@
package com.yihu.jw.business.login.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.login.BaseLoginAccountDO;
import com.yihu.jw.business.login.dao.BaseLoginAccountDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
/**
 * Created by LiTaohong on 2017/12/5.
 * 用户账户功能
 */
@Service
public class BaseLoginAccountService extends BaseJpaService<BaseLoginAccountDO,BaseLoginAccountDao> {
    @Autowired
    private BaseLoginAccountDao baseLoginAccountDao;
    /**
     * 创建账户
     * @param baseLoginAccountDO
     * @return
     */
    @Transactional
    public BaseLoginAccountDO createBaseLoginAccount(BaseLoginAccountDO baseLoginAccountDO){
        if (StringUtils.isEmpty(baseLoginAccountDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseLoginAccountDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseLoginAccountDao.save(baseLoginAccountDO);
    }
    /**
     * 修改账户
     * @param baseLoginAccountDO
     * @return
     */
    @Transactional
    public BaseLoginAccountDO updateBaseLoginAccount(BaseLoginAccountDO baseLoginAccountDO){
        return this.baseLoginAccountDao.save(baseLoginAccountDO);
    }
    /**
     * 锁定账户
     * @param id
     * @return
     */
    @Transactional
    public void lockBaseLoginAccount(String id){
         this.baseLoginAccountDao.updateAccount(id);
    }
    /**
     * 删除账户
     * @param id
     * @return
     */
    @Transactional
    public void deleteBaseLoginAccount(String id){
         this.baseLoginAccountDao.deleteAccount(id);
    }
}

+ 95 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/BaseMenuController.java

@ -0,0 +1,95 @@
package com.yihu.jw.business.user.contorller;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.business.user.service.BaseMenuService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
 * Created by LiTaohong on 2017/11/28.
 */
@RestController
@RequestMapping("/menu")
@Api(description = "基础菜单")
public class BaseMenuController extends EnvelopRestController {
    @Autowired
    private BaseMenuService baseMenuService;
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建菜单", notes = "创建单个菜单")
    public Envelop createBaseMenu(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_create,baseMenuService.createBaseMenu(baseMenuDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改菜单", notes = "修改菜单")
    public Envelop updateBaseMenu(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_update,baseMenuService.updateBaseMenuDO(baseMenuDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_getOne, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询单个菜单", notes = "根据菜单id查询菜单信息")
    public Envelop getOneMenuById(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_find,baseMenuService.findById(baseMenuDO.getId()));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_getchildren, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询单个菜单的所有子菜单信息", notes = "根据平台和菜单名称查询菜单信息")
    public Envelop getChlidrenMenuList(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestParam String saasId,
                                       @ApiParam(name = "json_data", value = "", defaultValue = "") @RequestParam String parentId){
        try{
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_find,baseMenuService.getChlidrenMenuList(saasId,parentId));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_getList, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "查询多个菜单", notes = "根据平台saasId查询所有菜单信息")
    public Envelop getMenuListBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_find,baseMenuService.findAllBySaasId(baseMenuDO.getSaasId()));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseMenu.api_delete, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "批量删除菜单", notes = "删除某一平台saasId下所有菜单信息")
    public Envelop deleteMenusBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseMenuDO baseMenuDO = toEntity(jsonData,BaseMenuDO.class);
            baseMenuService.deleteBaseMenusBySaasId(baseMenuDO.getSaasId());
            return Envelop.getSuccess(BaseUserRequestMapping.BaseMenu.message_success_delete);
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
}

+ 1 - 1
svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/BaseRoleController.java

@ -73,7 +73,7 @@ public class BaseRoleController extends EnvelopRestController {
    public Envelop getRoleListBySaasId(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseRoleDO baseRoleDO = toEntity(jsonData,BaseRoleDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,baseRoleService.getRoleListByName(baseRoleDO.getSaasId()));
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,baseRoleService.findAllBySaasId(baseRoleDO.getSaasId()));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }

+ 81 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/EmployController.java

@ -0,0 +1,81 @@
package com.yihu.jw.business.user.contorller;
import com.yihu.jw.base.user.BaseEmployDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.business.user.service.EmployService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.base.BaseSmsRequestMapping;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
 * Created by chenweida on 2017/5/11.
 */
@RestController
@RequestMapping(BaseUserRequestMapping.api_common)
@Api(description = "医生,行政人员等非患者用户(基础用户)")
public class EmployController extends EnvelopRestController {
    @Autowired
    private EmployService employService;
    @PostMapping(value = BaseUserRequestMapping.BaseEmploy.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建用户", notes = "创建单个用户")
    public Envelop createBaseEmployDO(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseEmployDO baseEmployDO = toEntity(jsonData,BaseEmployDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_create,employService.createBaseEmployDO(baseEmployDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @PostMapping(value = BaseUserRequestMapping.BaseEmploy.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "修改用户", notes = "修改用户")
    public Envelop updateBaseEmployDO(@ApiParam(name = "json_data", value = "", defaultValue = "") @RequestBody String jsonData){
        try{
            BaseEmployDO baseEmployDO = toEntity(jsonData,BaseEmployDO.class);
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_update,employService.updateBaseEmployDO(baseEmployDO));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据id查找用户")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getById)
    public Envelop getEmployeeById(@ApiParam(name = "id", value = "id", required = true) @RequestParam(value = "id", required = true) String id) {
        try{
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,this.employService.findById(id));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据saasId查找所有用户")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getList)
    public Envelop getAllEmployeeBySaasId(@ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId) {
        try{
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,this.employService.findAllBySaasId(saasId));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
    @ApiOperation(value = "根据name模糊查询某saasId平台下的所有用户")
    @GetMapping(value = BaseUserRequestMapping.BaseEmploy.api_getList)
    public Envelop getListByNameAndSaasId(@ApiParam(name = "saasId", value = "saasId", required = true) @RequestParam(value = "saasId", required = true) String saasId) {
        try{
            return Envelop.getSuccess(BaseUserRequestMapping.BaseRole.message_success_find,this.employService.findAllBySaasId(saasId));
        } catch (ApiException e){
            return Envelop.getError(e.getMessage(), e.getErrorCode());
        }
    }
}

+ 0 - 33
svr/svr-base/src/main/java/com/yihu/jw/business/user/contorller/EmployeeController.java

@ -1,33 +0,0 @@
package com.yihu.jw.business.user.contorller;
import com.yihu.jw.business.user.service.EmployeeService;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.base.BaseSmsRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by chenweida on 2017/5/11.
 */
@RestController
@RequestMapping(BaseSmsRequestMapping.api_common)
@Api(description = "医生,行政人员等非患者用户")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @ApiOperation(value = "根据行政人员账号查找用户")
    @GetMapping(value = BaseRequestMapping.Employee.api_getEmployeeByAccount)
    public String getEmployeeByAccount(
            @ApiParam(name = "userAccount", value = "用户账号", required = true) @RequestParam(value = "userAccount", required = true) String userAccount) {
        
        return "调用根据code查找患者";
    }
}

+ 32 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseMenuDao.java

@ -0,0 +1,32 @@
package com.yihu.jw.business.user.dao;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.base.user.BaseMenuDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by LiTaohong on 2017/12/05.
 */
public interface BaseMenuDao extends PagingAndSortingRepository<BaseMenuDO, String>, JpaSpecificationExecutor<BaseMenuDO> {
    //角色与saasId为一对多关系
    @Query("from BaseMenuDO b where b.saasId = ?1")
    List<BaseMenuDO> findAllBySaasId(String saasId);
    @Query("from BaseMenuDO b where b.saasId = ?1 and b.name = ?2")
    BaseMenuDO findOneBySaasIdAndName(String saasId, String name);
    @Query("from BaseMenuDO b where b.name like %?1%")
    List<BaseMenuDO> findAllByName(String name);
    @Query("from BaseMenuDO b where b.saasId = 1? and b.parentId = ?2")
    List<BaseMenuDO> getChildrenMenuList(String saasId,String parentId);
}

+ 20 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/BaseRoleMenuDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.business.user.dao;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.base.user.BaseRoleMenuDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by LiTaohong on 2017/11/28.
 */
public interface BaseRoleMenuDao extends PagingAndSortingRepository<BaseRoleMenuDO, String>, JpaSpecificationExecutor<BaseRoleMenuDO> {
    @Query("from BaseRoleMenuDO ba where ba.roleId = ?1")
    List<BaseRoleMenuDO> findRoleMenuListByRoleId(String employId);
}

+ 24 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployDao.java

@ -0,0 +1,24 @@
package com.yihu.jw.business.user.dao;
import com.yihu.jw.base.user.BaseEmployDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by chenweida on 2017/11/28.
 */
/**
 * 基础用户类接口
 */
public interface EmployDao extends PagingAndSortingRepository<BaseEmployDO, String>, JpaSpecificationExecutor<BaseEmployDO> {
    @Query("from BaseEmployDO ba where ba.saasId = ?1")
    List<BaseEmployDO> findAllBySaasId(String saasId);
    @Query("from BaseEmployDO ba where ba.name like ?1 and ba.saasId = ?2")
    List<BaseEmployDO> findAllByNameAndSaasId(String name,String saasId);
}

+ 18 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployRoleDao.java

@ -0,0 +1,18 @@
package com.yihu.jw.business.user.dao;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.base.user.BaseRoleDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by LiTaohong on 2017/11/28.
 */
public interface EmployRoleDao extends PagingAndSortingRepository<BaseEmployRoleDO, String>, JpaSpecificationExecutor<BaseEmployRoleDO> {
    @Query("from BaseEmployRoleDO ba where ba.employId = ?1")
    List<BaseEmployRoleDO> findRoleListByEmployId(String employId);
}

+ 0 - 12
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployeeDao.java

@ -1,12 +0,0 @@
package com.yihu.jw.business.user.dao;
import com.yihu.jw.base.user.BaseEmployDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/11/28.
 */
public interface EmployeeDao extends PagingAndSortingRepository<BaseEmployDO, String>, JpaSpecificationExecutor<BaseEmployDO> {
}

+ 0 - 12
svr/svr-base/src/main/java/com/yihu/jw/business/user/dao/EmployeeRoleDao.java

@ -1,12 +0,0 @@
package com.yihu.jw.business.user.dao;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.base.user.BaseRoleDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by LiTaohong on 2017/11/28.
 */
public interface EmployeeRoleDao extends PagingAndSortingRepository<BaseEmployRoleDO, String>, JpaSpecificationExecutor<BaseEmployRoleDO> {
}

+ 137 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseMenuService.java

@ -0,0 +1,137 @@
package com.yihu.jw.business.user.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.base.user.BaseMenuDO;
import com.yihu.jw.business.user.dao.BaseMenuDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
/**
 * Created by LiTaohong on 2017/12/5.
 * 基础菜单功能
 */
@Service
public class BaseMenuService extends BaseJpaService<BaseMenuDO,BaseMenuDao>{
    @Autowired
    private BaseMenuDao baseMenuDao;
    /**
     * 创建菜单
     * @param baseMenuDO
     * @return
     */
    @Transactional
    public BaseMenuDO createBaseMenu(BaseMenuDO baseMenuDO){
        if (StringUtils.isEmpty(baseMenuDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseMenuDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseMenuDao.save(baseMenuDO);
    }
    /**
     * 更新菜单
     * @param baseMenuDO
     * @return
     */
    @Transactional
    public BaseMenuDO updateBaseMenuDO(BaseMenuDO baseMenuDO){
        if (StringUtils.isEmpty(baseMenuDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseMenuDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseMenuDao.save(baseMenuDO);
    }
    /**
     * 根据Id查询菜单
     * @param id
     * @return
     */
    public BaseMenuDO findById(String id){
        if (StringUtils.isEmpty(id)) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
        BaseMenuDO baseRoleDO = this.baseMenuDao.findOne(id);
        if (null == baseRoleDO) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_no_exist,ExceptionCode.common_error_params_code);
        }
        return baseRoleDO;
    }
    /**
     * 查询某要saasId平台下的所有菜单
     * @param saasId
     * @return
     */
    public List<BaseMenuDO> findAllBySaasId(String saasId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null,ExceptionCode.common_error_params_code);
        }
        List<BaseMenuDO> list = this.baseMenuDao.findAllBySaasId(saasId);
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_no_exist,ExceptionCode.common_error_params_code);
        }
        return list;
    }
    /**
     * 根据Id删除菜单
     * @param baseMenuDO
     */
    @Transactional
    public void deleteBaseMenu(BaseMenuDO baseMenuDO){
        if (StringUtils.isEmpty(baseMenuDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseMenuDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        baseMenuDO.setStatus(-1);
        this.baseMenuDao.save(baseMenuDO);
    }
    /**
     * 删除某一saasId相关的所有菜单
     * @param saasId
     */
    @Transactional
    public void deleteBaseMenusBySaasId(String saasId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_fail_saasId_is_null, ExceptionCode.common_error_params_code);
        }
        List<BaseMenuDO> list = this.baseMenuDao.findAllBySaasId(saasId);
        for(BaseMenuDO baseMenuDO:list){
            baseMenuDO.setStatus(-1);
        }
        this.baseMenuDao.save(list);
    }
    /**
     * 获取某一平台下某一父级菜单的所有子菜单
     * @param saasId
     * @param parentId
     * @return
     */
    public List<BaseMenuDO> getChlidrenMenuList(String saasId,String parentId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_param_saasid_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(parentId)) {
            throw new ApiException(BaseUserRequestMapping.BaseMenu.message_param_parentId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseMenuDao.getChildrenMenuList(saasId,parentId);
    }
}

+ 100 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseRoleMenuService.java

@ -0,0 +1,100 @@
package com.yihu.jw.business.user.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.user.BaseRoleMenuDO;
import com.yihu.jw.business.user.dao.BaseRoleMenuDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
/**
 * Created by LiTaohong on 2017/12/05.
 * 基础角色菜单功能
 */
@Service
public class BaseRoleMenuService extends BaseJpaService<BaseRoleMenuDO,BaseRoleMenuDao> {
    @Autowired
    private BaseRoleMenuDao baseRoleMenuDao;
    /**
     * 新增角色菜单
     * @param baseEmployRoleDO
     * @return
     */
    @Transactional
    public BaseRoleMenuDO createBaseEmployRoleDO(BaseRoleMenuDO baseEmployRoleDO){
        if (StringUtils.isEmpty(baseEmployRoleDO.getRoleId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_roleId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.baseRoleMenuDao.save(baseEmployRoleDO);
    }
    /**
     * 批量新增角色菜单,一个角色拥有多个菜单的权限
     * @param list
     * @return
     */
    @Transactional
    public void createBatchBaseRoleMenuDO(List<BaseRoleMenuDO> list){
        this.baseRoleMenuDao.save(list);
    }
    /**
     * 修改角色菜单信息
     * @param baseRoleMenuDO
     * @return
     */
    @Transactional
    public BaseRoleMenuDO updateBaseEmployRoleDO(BaseRoleMenuDO baseRoleMenuDO){
        BaseRoleMenuDO OldbaseRoleMenuDO = this.baseRoleMenuDao.findOne(baseRoleMenuDO.getId());
        if(null == OldbaseRoleMenuDO){
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_baseRoleMenu_no_exist, ExceptionCode.common_error_params_code);
        }
        //菜单id一样,表示菜单没有变,则不修改
        if (baseRoleMenuDO.getMenuId().equals(OldbaseRoleMenuDO.getMenuId())) {
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_same_menuId, ExceptionCode.common_error_params_code);
        }
        return this.baseRoleMenuDao.save(baseRoleMenuDO);
    }
    /**
     * 查询某一角色的菜单列表(角色与菜单为一对多关系)
     * @param roleId
     * @return
     */
    public List<BaseRoleMenuDO> findAllByRoleId(String roleId){
        if (StringUtils.isEmpty(roleId)) {
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_roleId_is_null, ExceptionCode.common_error_params_code);
        }
        List<BaseRoleMenuDO> list = this.baseRoleMenuDao.findRoleMenuListByRoleId(roleId);
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_baseRoleMenu_no_exist,ExceptionCode.common_error_params_code);
        }
        return list;
    }
    /**
     * 删除用户角色
     * @param id
     * @return
     */
    @Transactional
    public void deleteBaseRoleMenuDO(String id){
        try{
            this.baseRoleMenuDao.delete(id);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseRoleMenu.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
}

+ 1 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/BaseRoleService.java

@ -17,6 +17,7 @@ import java.util.List;
/**
 * Created by LiTaohong on 2017/11/28.
 * 基础角色功能
 */
@Service
public class BaseRoleService extends BaseJpaService<BaseRoleDO,BaseRoleDao>{

+ 104 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployRoleService.java

@ -0,0 +1,104 @@
package com.yihu.jw.business.user.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.user.BaseEmployDO;
import com.yihu.jw.base.user.BaseEmployRoleDO;
import com.yihu.jw.business.user.dao.EmployRoleDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
/**
 * Created by chenweida on 2017/5/11.
 * 用户角色表功能
 */
@Service
public class EmployRoleService extends BaseJpaService<BaseEmployRoleDO,EmployRoleDao> {
    @Autowired
    private EmployRoleDao employRoleDao;
    /**
     * 新增用户角色
     * @param baseEmployRoleDO
     * @return
     */
    @Transactional
    public BaseEmployRoleDO createBaseEmployRoleDO(BaseEmployRoleDO baseEmployRoleDO){
        if (StringUtils.isEmpty(baseEmployRoleDO.getRoleId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_roleId_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(baseEmployRoleDO.getEmployId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employId_is_null, ExceptionCode.common_error_params_code);
        }
        return this.employRoleDao.save(baseEmployRoleDO);
    }
    /**
     * 批量新增用户角色,一个用户可能有多个角色
     * @param list
     * @return
     */
    @Transactional
    public void createBatchBaseEmployRoleDO(List<BaseEmployRoleDO> list){
        this.employRoleDao.save(list);
    }
    /**
     * 修改用户角色
     * @param baseEmployRoleDO
     * @return
     */
    @Transactional
    public BaseEmployRoleDO updateBaseEmployRoleDO(BaseEmployRoleDO baseEmployRoleDO){
        BaseEmployRoleDO OldbaseEmployRoleDO = this.employRoleDao.findOne(baseEmployRoleDO.getId());
        if(null == OldbaseEmployRoleDO){
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employeeRole_no_exist, ExceptionCode.common_error_params_code);
        }
        if (baseEmployRoleDO.getRoleId().equals(OldbaseEmployRoleDO.getRoleId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_same_roleId, ExceptionCode.common_error_params_code);
        }
        return this.employRoleDao.save(baseEmployRoleDO);
    }
    /**
     * 查询某一用户的角色列表(用户与角色为一对多关系)
     * @param employId
     * @return
     */
    public List<BaseEmployRoleDO> findAllByEmployId(String employId){
        if (StringUtils.isEmpty(employId)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employId_is_null, ExceptionCode.common_error_params_code);
        }
        List<BaseEmployRoleDO> list = this.employRoleDao.findRoleListByEmployId(employId);
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_employeeRole_no_exist,ExceptionCode.common_error_params_code);
        }
        return list;
    }
    /**
     * 删除用户角色
     * @param id
     * @return
     */
    @Transactional
    public void deleteBaseEmployRoleDO(String id){
        try{
            this.employRoleDao.delete(id);
        }
        catch (ApiException e){
            throw new ApiException(BaseUserRequestMapping.BaseEmployRole.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
    }
}

+ 124 - 0
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployService.java

@ -0,0 +1,124 @@
package com.yihu.jw.business.user.service;
import com.yihu.base.mysql.query.BaseJpaService;
import com.yihu.jw.base.user.BaseEmployDO;
import com.yihu.jw.base.user.BaseRoleDO;
import com.yihu.jw.business.user.dao.BaseRoleDao;
import com.yihu.jw.business.user.dao.EmployDao;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
/**
 * Created by chenweida on 2017/5/11.
 * 用户信息功能
 */
@Service
public class EmployService extends BaseJpaService<BaseEmployDO,EmployDao> {
    @Autowired
    private EmployDao employDao;
    /**
     * 创建用户
     * @param employeeDO
     * @return
     */
    @Transactional
    public BaseEmployDO createBaseEmployDO(BaseEmployDO employeeDO){
        if (StringUtils.isEmpty(employeeDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(employeeDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_saasid_is_null, ExceptionCode.common_error_params_code);
        }
        return this.employDao.save(employeeDO);
    }
    /**
     * 更新用户
     * @param employeeDO
     * @return
     */
    @Transactional
    public BaseEmployDO updateBaseEmployDO(BaseEmployDO employeeDO){
        if (StringUtils.isEmpty(employeeDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(employeeDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_saasid_is_null, ExceptionCode.common_error_params_code);
        }
        return this.employDao.save(employeeDO);
    }
    /**
     * 根据Id查询用户
     * @param id
     * @return
     */
    public BaseEmployDO findById(String id){
        if (StringUtils.isEmpty(id)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_id_is_null,ExceptionCode.common_error_params_code);
        }
        BaseEmployDO BaseEmployDO = this.employDao.findOne(id);
        if (null == BaseEmployDO) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_id_no_exist,ExceptionCode.common_error_params_code);
        }
        return BaseEmployDO;
    }
    /**
     * 查询某saasId平台下的所有用户
     * @param saasId
     * @return
     */
    public List<BaseEmployDO> findAllBySaasId(String saasId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_param_saasid_is_null,ExceptionCode.common_error_params_code);
        }
        List<BaseEmployDO> list = this.employDao.findAllBySaasId(saasId);
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_saasid_no_exist,ExceptionCode.common_error_params_code);
        }
        return list;
    }
    /**
     * 查询name模糊查询某saasId平台下的所有用户
     * @param saasId
     * @return
     */
    public List<BaseEmployDO> findAllByNameAndSaasId(String name,String saasId){
        if (StringUtils.isEmpty(saasId)) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_param_saasid_is_null,ExceptionCode.common_error_params_code);
        }
        List<BaseEmployDO> list = this.employDao.findAllByNameAndSaasId(name,saasId);
        if (null == list || list.size() == 0) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_saasid_no_exist,ExceptionCode.common_error_params_code);
        }
        return list;
    }
    /**
     * 根据Id删除用户
     * @param employDO
     */
    @Transactional
    public void deleteBaseEmploy(BaseEmployDO employDO){
        if (StringUtils.isEmpty(employDO.getId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_id_is_null, ExceptionCode.common_error_params_code);
        }
        if (StringUtils.isEmpty(employDO.getSaasId())) {
            throw new ApiException(BaseUserRequestMapping.BaseEmploy.message_fail_saasid_is_null, ExceptionCode.common_error_params_code);
        }
        employDO.setStatus(-1);
        this.employDao.save(employDO);
    }
}

+ 0 - 10
svr/svr-base/src/main/java/com/yihu/jw/business/user/service/EmployeeService.java

@ -1,10 +0,0 @@
package com.yihu.jw.business.user.service;
import org.springframework.stereotype.Service;
/**
 * Created by chenweida on 2017/5/11.
 */
@Service
public class EmployeeService {
}

+ 4 - 0
svr/svr-demo/pom.xml

@ -26,6 +26,10 @@
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.base</groupId>
            <artifactId>common-data-mysql</artifactId>

+ 88 - 1
svr/svr-demo/readme.MD

@ -1 +1,88 @@
http://localhost:8080/oauth/authorize?client_id=cwd&redirect_uri=localhost:8080&scope=all
**授权码模式:(一直开放API用)**
获取code
http://localhost:8060/oauth/authorize?response_type=code&client_id=cwd&redirect_uri=http://example.com&scope=all
获取token post请求
http://localhost:8060/oauth/token
header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
  
{
     "grant_type":"authorization_code",  
     "client_id":"cwd",
     "code":"第一步请求获取的code",
     "redirect_uri":"http://example.com",
     "scope":"all"
}
返回值
{
    "access_token":"bd677e24-2de5-4862-a5e1-8f90a074db42",
    "token_type":"bearer",
    "refresh_token":"1427b997-ef94-4061-8940-c71da6549acd",
    "expires_in":43199,
    "scope":"all"
}
**密码模式(一般自己公司系统用)**
获取token post请求
http://localhost:8060/oauth/token
header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
  
{
     "grant_type":"password",  
     "username":"jojo",
     "password":"123456",
     "scope":"all"
}
返回值
{
    "access_token":"630e2ccc-a5ce-4486-a855-ba755eb3d0d2",
    "token_type":"bearer",
    "refresh_token":"bbb36b54-61b2-4d86-aed3-91c5135174c3",
    "expires_in":43199,
    "scope":"all"
}
**刷新token **
获取token post请求
http://localhost:8060/oauth/token
header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
  
{
     "grant_type":"refresh_token",
     "refresh_token":"all"
}
返回值
{
    "access_token":"630e2ccc-a5ce-4486-a855-ba755eb3d0d2",
    "token_type":"bearer",
    "refresh_token":"bbb36b54-61b2-4d86-aed3-91c5135174c3",
    "expires_in":43199,
    "scope":"all"
}
**自定义账号密码登陆**
POST
http://localhost:8060/authentication/form
header
Authorization  Basic Y3dkOmN3ZA==
body
{
    "username":"test",
    "password":"123456"
}
**自定义手机号短信验证码登陆**
**访问方式**
http://localhost:8060/user
header 
{
"Authorization":"bearer 5fe6b2c3-f69c-4ddc-a36a-367cdf9479a3"      即 bearer accesstoken
}

+ 5 - 1
svr/svr-demo/src/main/java/com/yihu/DemoApplication.java

@ -1,16 +1,20 @@
package com.yihu;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
 * Created by chenweida on 2017/11/3.
 */
@SpringBootApplication
@ComponentScan(basePackages={"com"})
@ComponentScan(basePackages = {"com"})
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

+ 2 - 1
svr/svr-demo/src/main/java/com/yihu/jw/model/MyUser.java

@ -8,7 +8,8 @@ import java.util.Collection;
/**
 * Created by chenweida on 2017/11/29.
 */
public class MyUser implements UserDetails {
public class MyUser implements UserDetails
{
    /**
     * 权限
     * @return

+ 80 - 2
svr/svr-demo/src/main/java/com/yihu/jw/model/SaasDO.java

@ -140,12 +140,18 @@ public class SaasDO implements Serializable, ClientDetails {
    @Override
    public Set<String> getAuthorizedGrantTypes() {
        return null;
        Set<String> strings = new HashSet<>();
        strings.add("password");
        strings.add("custom_password");
        strings.add("authorization_code");
        strings.add("refresh_token");
        return strings;
    }
    @Override
    public Set<String> getRegisteredRedirectUri() {
        Set<String> strings=new HashSet<>();
        Set<String> strings = new HashSet<>();
        strings.add(url);
        return strings;
    }
@ -174,4 +180,76 @@ public class SaasDO implements Serializable, ClientDetails {
    public Map<String, Object> getAdditionalInformation() {
        return null;
    }
    public String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    public String getCreateUserName() {
        return createUserName;
    }
    public void setCreateUserName(String createUserName) {
        this.createUserName = createUserName;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public String getUpdateUser() {
        return updateUser;
    }
    public void setUpdateUser(String updateUser) {
        this.updateUser = updateUser;
    }
    public String getUpdateUserName() {
        return updateUserName;
    }
    public void setUpdateUserName(String updateUserName) {
        this.updateUserName = updateUserName;
    }
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    public String getAppSecret() {
        return appSecret;
    }
    public void setAppSecret(String appSecret) {
        this.appSecret = appSecret;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
}

+ 25 - 9
svr/svr-demo/src/main/java/com/yihu/jw/service/ClientService.java

@ -1,27 +1,43 @@
package com.yihu.jw.service;
import com.yihu.base.security.rbas.ClientServiceProvider;
import com.yihu.jw.dao.SaasDao;
import com.yihu.jw.model.SaasDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.HashSet;
import java.util.Set;
/**
 * Created by chenweida on 2017/12/1.
 */
@Service
public class ClientService implements ClientDetailsService {
    @Autowired
    private SaasDao saasDao;
@Component("baseClientDetailsService")
public class ClientService implements ClientServiceProvider {
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        SaasDO saasDO = saasDao.findByAppId(clientId);
        if (saasDO == null) {
            throw new ClientRegistrationException("用户没有注册");
        }
        return saasDO;
//        SaasDO saasDO = saasDao.findByAppId(clientId);
//        if (saasDO == null) {
//            throw new ClientRegistrationException("用户没有注册");
//        }
        SaasDO baseClientDetails = new SaasDO();
        baseClientDetails.setAppId("cwd");
        baseClientDetails.setAppSecret("cwd");
        baseClientDetails.getAuthorizedGrantTypes();
        return baseClientDetails;
    }
}

+ 48 - 0
svr/svr-demo/src/main/java/com/yihu/jw/service/RbasService.java

@ -0,0 +1,48 @@
package com.yihu.jw.service;
import com.yihu.base.security.rbas.IRbasService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;
/**
 * Created by chenweida on 2017/12/5.
 * 判断用户是否有权限访问该路径
 */
@Component("rbasbean")
public class RbasService implements IRbasService {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Boolean hasPerssion(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPerssion = false;
        if (principal instanceof UserDetails) {
            //获取用户名字
            String username = ((UserDetails) principal).getUsername();
            //获取用户全部权限
            Set<String> uris = new HashSet<>();
            for (String uri : uris) {
                if (antPathMatcher.match(uri, request.getRequestURI())) {
                    hasPerssion = true;
                    break;
                }
            }
        }
        return hasPerssion;
    }
    public Boolean hello() {
        return true;
    }
}

+ 28 - 6
svr/svr-demo/src/main/java/com/yihu/jw/service/UserService.java

@ -1,22 +1,33 @@
package com.yihu.jw.service;
import com.sun.javafx.scene.control.skin.VirtualFlow;
import com.yihu.jw.model.MyUser;
import com.yihu.jw.model.SaasDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
 * Created by chenweida on 2017/11/29.
 * 处理用户校验
 */
@Service
@Component
public class UserService implements UserDetailsService {
    @Autowired
@ -32,17 +43,28 @@ public class UserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        if ("admin".equals(userName)) {
            System.out.printf("password:"+passwordEncoder.encode("123456"));
            System.out.printf("password:" + passwordEncoder.encode("123456"));
            return new User("admin",
                    "123456",
                    passwordEncoder.encode("123456"),
                    true,
                    true,
                    true,
                    true
                    , AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_USER") //权限
            );
        } else if ((!StringUtils.isEmpty(userName))&&userName.length() == 11) {
            System.out.printf("password:" + passwordEncoder.encode("123456"));
            return new User("admin",
                    passwordEncoder.encode("123456"),
                    true,
                    true,
                    true,
                    new ArrayList<>()  //权限
                    true
                    , AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_USER") //权限
            );
        } else {
            throw new UsernameNotFoundException("用户不存在");
        }
    }
}

+ 10 - 1
svr/svr-demo/src/main/resources/application.yml

@ -32,7 +32,8 @@ spring:
    port: 6379 # Redis server port.
    database: 1
  aop:
    proxy-target-class: true
quartz:
@ -40,3 +41,11 @@ quartz:
  overwriteExistingJobs: true ##是否覆盖job
security:
  oauth2:
    token:
      accessTokenValidityHours: 2 # 2小时
      refreshTokenValidityHours: 2 # 2小时
    sms:
      expireIn: 1 ##1分钟
      length: 6 #验证码长度

+ 1 - 26
svr/svr-demo/src/main/resources/resources/denglu.html

@ -7,7 +7,7 @@
<body>
	<h2>标准登录页面</h2>
	<h3>表单登录</h3>
	<form action="/authentication/form" method="post">
<form action="/authentication/form" method="post">
		<table>
			<tr>
				<td>用户名:</td> 
@ -32,30 +32,5 @@
			</tr>
		</table>
	</form>
	
	<h3>短信登录</h3>
	<form action="/authentication/mobile" method="post">
		<table>
			<tr>
				<td>手机号:</td>
				<td><input type="text" name="mobile" value="13012345678"></td>
			</tr>
			<tr>
				<td>短信验证码:</td>
				<td>
					<input type="text" name="smsCode">
					<a href="/code/sms?mobile=13012345678">发送验证码</a>
				</td>
			</tr>
			<tr>
				<td colspan="2"><button type="submit">登录</button></td>
			</tr>
		</table>
	</form>
	<br>
	<h3>社交登录</h3>
	<a href="/qqLogin/callback.do">QQ登录</a>
	&nbsp;&nbsp;&nbsp;&nbsp;
	<a href="/qqLogin/weixin">微信登录</a>
</body>
</html>

+ 20 - 0
web-gateway/src/main/java/com/yihu/jw/commnon/base/base/BaseContants.java

@ -10,6 +10,8 @@ public class BaseContants {
    public static final String api_module = api_common+"/module";
    public static final String api_moduleFun = api_common+"/moduleFun";
    public static final String api_saas = api_common+"/saas";
    public static final String api_systemDict = api_common+"/systemDict";
    public static final String api_systemDictList = api_common+"/systemDictList";
    //功能模块常量
    public static class Function{
@ -47,4 +49,22 @@ public class BaseContants {
        public static final String api_getSaassNoPage="/getSaassNoPage";
    }
    //SystemDict常量
    public static class SystemDict{
        public static final String api_create="/";
        public static final String api_update="/";
        public static final String api_delete="/{id}";
        public static final String api_getSystemDictNoPage="/getSaassNoPage";
    }
    //SystemDictList常量
    public static class SystemDictList{
        public static final String api_create="/";
        public static final String api_update="/";
        public static final String api_delete="/{id}";
        public static final String api_getSystemDictListNoPage="/getSaassNoPage";
    }
}

+ 45 - 0
web-gateway/src/main/java/com/yihu/jw/commnon/base/user/BaseUserContants.java

@ -0,0 +1,45 @@
package com.yihu.jw.commnon.base.user;
/**
 * Created by LiTaohong on 2017/11/28.
 */
public class BaseUserContants {
    public static final String api_common = "/bases";
    public static final String api_baseRole = api_common+"/baseRole";
    public static final String api_employ = api_common+"/employee";
    public static final String api_baseMenu= api_common+"/employee";
    //角色常量
    public static class BaseRole{
        public static final String api_create="/";
        public static final String api_update="/";
        public static final String api_delete="/{id}";
        public static final String api_getById="/{id}";
        public static final String api_getListNoPage="/listNoPage";
        public static final String api_getList="/list";
        public static final String api_getChildren="/children/{id}";
    }
    //用户常量
    public static class Employee{
        public static final String api_create="/";
        public static final String api_update="/";
        public static final String api_delete="/{id}";
        public static final String api_getById="/{id}";
        public static final String api_getListNoPage="/listNoPage";
        public static final String api_getList="/list";
        public static final String api_getChildren="/children/{id}";
    }
    //菜单常量
    public static class BaseMenu{
        public static final String api_create="/";
        public static final String api_update="/";
        public static final String api_delete="/{id}";
        public static final String api_getById="/{id}";
        public static final String api_getListNoPage="/listNoPage";
        public static final String api_getList="/list";
        public static final String api_getChildren="/children/{id}";
    }
}

+ 2 - 6
web-gateway/src/main/java/com/yihu/jw/config/security/roleService/ClientService.java

@ -1,11 +1,7 @@
package com.yihu.jw.config.security.roleService;
import com.yihu.jw.feign.base.user.EmployeeFeign;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.feign.base.user.EmployFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
@ -18,7 +14,7 @@ import org.springframework.stereotype.Service;
@Service
public class ClientService implements ClientDetailsService {
    @Autowired
    private EmployeeFeign employeeFeign;
    private EmployFeign employeeFeign;
    @Override

+ 2 - 2
web-gateway/src/main/java/com/yihu/jw/config/security/roleService/UserService.java

@ -1,6 +1,6 @@
package com.yihu.jw.config.security.roleService;
import com.yihu.jw.feign.base.user.EmployeeFeign;
import com.yihu.jw.feign.base.user.EmployFeign;
import com.yihu.jw.restmodel.common.Envelop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
@ -15,7 +15,7 @@ import org.springframework.stereotype.Service;
@Service
public class UserService implements UserDetailsService {
    @Autowired
    private EmployeeFeign employeeFeign;
    private EmployFeign employeeFeign;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

+ 52 - 0
web-gateway/src/main/java/com/yihu/jw/controller/base/base/SystemDictController.java

@ -0,0 +1,52 @@
package com.yihu.jw.controller.base.base;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.yihu.jw.commnon.base.base.BaseContants;
import com.yihu.jw.feign.base.base.SaasFeign;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by LiTaohong on 2017/12/01.
 */
@RestController
@RequestMapping(BaseContants.api_systemDict)
@Api(description = "SystemDict相关")
public class SystemDictController extends EnvelopRestController {
    private Logger logger = LoggerFactory.getLogger(SystemDictController.class);
    @Autowired
    private SaasFeign saasFegin;
    @Autowired
    private Tracer tracer;
    @GetMapping(value = BaseContants.SystemDict.api_getSystemDictNoPage)
    @ApiOperation(value = "获取saas,不分页")
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    public Envelop getSaasNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) {
        return saasFegin.getList(fields, filters, sorts);
    }
}

+ 53 - 0
web-gateway/src/main/java/com/yihu/jw/controller/base/base/SystemDictListController.java

@ -0,0 +1,53 @@
package com.yihu.jw.controller.base.base;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.yihu.jw.commnon.base.base.BaseContants;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.base.base.SystemDictListFeign;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by LiTaohong on 2017/12/01.
 */
@RestController
@RequestMapping(BaseContants.api_systemDictList)
@Api(description = "SystemDictList相关")
public class SystemDictListController extends EnvelopRestController {
    private Logger logger= LoggerFactory.getLogger(SystemDictListController.class);
    @Autowired
    private SystemDictListFeign SystemDictListFegin;
    @Autowired
    private Tracer tracer;
    @GetMapping(value = BaseContants.SystemDictList.api_getSystemDictListNoPage)
    @ApiOperation(value = "获取SystemDictList,不分页")
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    public Envelop getSystemDictListNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,SystemDictListId,appId,appSecret,baseUrl,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) throws JiWeiException {
        return SystemDictListFegin.getListNoPage(fields, filters, sorts);
    }
}

+ 147 - 0
web-gateway/src/main/java/com/yihu/jw/controller/base/user/BaseMenuController.java

@ -0,0 +1,147 @@
package com.yihu.jw.controller.base.user;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.yihu.jw.commnon.base.user.BaseUserContants;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.base.user.BaseMenuFeign;
import com.yihu.jw.feign.base.user.BaseMenuFeign;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by LiTaohong on 2017/11/28.
 */
@RestController
@RequestMapping(BaseUserContants.api_baseMenu)
@Api(value = "基础菜单管理", description = "基础菜单管理")
public class BaseMenuController extends EnvelopRestController {
    @Autowired
    private BaseMenuFeign fegin;
    @Autowired
    private Tracer tracer;
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @PostMapping(value = BaseUserContants.BaseMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建菜单", notes = "创建菜单")
    public Envelop createBaseMenu(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws JiWeiException {
        return fegin.create(jsonData);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @PutMapping(value = BaseUserContants.BaseMenu.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新菜单", notes = "更新菜单")
    public Envelop updateBaseMenu(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws JiWeiException {
        return fegin.update(jsonData);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @DeleteMapping(value = BaseUserContants.BaseMenu.api_delete)
    @ApiOperation(value = "删除菜单", notes = "删除菜单")
    public Envelop deleteBaseMenu(
            @ApiParam(name = "id", value = "uuid")
            @RequestParam(value = "id", required = true) String id
    ) throws JiWeiException {
        return fegin.delete(id);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @GetMapping(value = BaseUserContants.BaseMenu.api_getById)
    @ApiOperation(value = "根据Id查找", notes = "根据uuid查找")
    public Envelop findById(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id", required = true) String id
    ) throws JiWeiException {
        return fegin.findById(id);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @GetMapping(value = BaseUserContants.BaseMenu.api_getById)
    @ApiOperation(value = "根据Id查找", notes = "根据uuid查找")
    public Envelop getChildren(@ApiParam(name = "saasId", value = "saasId") @RequestParam(value = "saasId", required = true) String saasId,
                               @ApiParam(name = "parentId", value = "parentId") @RequestParam(value = "parentId", required = true) String parentId) throws JiWeiException {
        return fegin.getChildren(saasId,parentId);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @RequestMapping(value = BaseUserContants.BaseMenu.api_getList, method = RequestMethod.GET)
    @ApiOperation(value = "获取功能列表(分页)")
    public Envelop getBaseMenus(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,saasId,createUser,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String filterStr = "";
        if(StringUtils.isNotBlank(filters)){
            JSONObject jsonResult = new JSONObject(filters);
            if(jsonResult.has("name")){
                filterStr+="name?"+jsonResult.get("name")+";";
            }
        }
        return fegin.getList(fields, filterStr, sorts, size, page);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @GetMapping(value = BaseUserContants.BaseMenu.api_getListNoPage)
    @ApiOperation(value = "获取功能列表,不分页")
    public Envelop getListNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,saasId,createUser,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        String filterStr = "";
        if(StringUtils.isNotBlank(filters)){
            JSONObject jsonResult = new JSONObject(filters);
            if(jsonResult.has("saasId")){
                filterStr+="saasId="+jsonResult.get("saasId")+";";
            }
        }
        return fegin.getListNoPage(fields, filterStr, sorts);
    }
}

+ 135 - 0
web-gateway/src/main/java/com/yihu/jw/controller/base/user/BaseRoleController.java

@ -0,0 +1,135 @@
package com.yihu.jw.controller.base.user;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.yihu.jw.commnon.base.base.BaseContants;
import com.yihu.jw.commnon.base.user.BaseUserContants;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.base.user.BaseRoleFeign;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by LiTaohong on 2017/11/28.
 */
@RestController
@RequestMapping(BaseUserContants.api_baseRole)
@Api(value = "角色管理", description = "角色管理")
public class BaseRoleController extends EnvelopRestController {
    @Autowired
    private BaseRoleFeign fegin;
    @Autowired
    private Tracer tracer;
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @PostMapping(value = BaseUserContants.BaseRole.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建角色", notes = "创建角色")
    public Envelop createFunction(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws JiWeiException {
        return fegin.create(jsonData);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @PutMapping(value = BaseUserContants.BaseRole.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新角色", notes = "更新角色")
    public Envelop updateFunction(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws JiWeiException {
        return fegin.update(jsonData);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @DeleteMapping(value = BaseUserContants.BaseRole.api_delete)
    @ApiOperation(value = "删除角色", notes = "删除角色")
    public Envelop deleteBaseRole(
            @ApiParam(name = "id", value = "uuid")
            @RequestParam(value = "id", required = true) String id
            ) throws JiWeiException {
        return fegin.delete(id);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @GetMapping(value = BaseUserContants.BaseRole.api_getById)
    @ApiOperation(value = "根据Id查找", notes = "根据uuid查找")
    public Envelop findById(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id", required = true) String id
    ) throws JiWeiException {
        return fegin.findById(id);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @RequestMapping(value = BaseUserContants.BaseRole.api_getList, method = RequestMethod.GET)
    @ApiOperation(value = "获取功能列表(分页)")
    public Envelop getBaseRoles(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,saasId,createUser,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String filterStr = "";
        if(StringUtils.isNotBlank(filters)){
            JSONObject jsonResult = new JSONObject(filters);
            if(jsonResult.has("name")){
                filterStr+="name?"+jsonResult.get("name")+";";
            }
        }
        return fegin.getList(fields, filterStr, sorts, size, page);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @GetMapping(value = BaseUserContants.BaseRole.api_getListNoPage)
    @ApiOperation(value = "获取功能列表,不分页")
    public Envelop getListNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,saasId,createUser,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        String filterStr = "";
        if(StringUtils.isNotBlank(filters)){
            JSONObject jsonResult = new JSONObject(filters);
            if(jsonResult.has("saasId")){
                filterStr+="saasId="+jsonResult.get("saasId")+";";
            }
        }
        return fegin.getListNoPage(fields, filterStr, sorts);
    }
}

+ 135 - 0
web-gateway/src/main/java/com/yihu/jw/controller/base/user/EmployController.java

@ -0,0 +1,135 @@
package com.yihu.jw.controller.base.user;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.yihu.jw.commnon.base.user.BaseUserContants;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.base.user.EmployFeign;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.EnvelopRestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by LiTaohong on 2017/11/30.
 */
@RestController
@RequestMapping(BaseUserContants.api_employ)
@Api(value = "用戶管理", description = "用戶管理")
public class EmployController extends EnvelopRestController {
    @Autowired
    private EmployFeign fegin;
    @Autowired
    private Tracer tracer;
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @PostMapping(value = BaseUserContants.Employee.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建用戶", notes = "创建用戶")
    public Envelop createFunction(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws JiWeiException {
        return fegin.create(jsonData);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @PutMapping(value = BaseUserContants.Employee.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "更新用戶", notes = "更新用戶")
    public Envelop updateFunction(
            @ApiParam(name = "json_data", value = "", defaultValue = "")
            @RequestBody String jsonData) throws JiWeiException {
        return fegin.update(jsonData);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @DeleteMapping(value = BaseUserContants.Employee.api_delete)
    @ApiOperation(value = "删除用戶", notes = "删除用戶")
    public Envelop deleteBaseRole(
            @ApiParam(name = "id", value = "uuid")
            @RequestParam(value = "id", required = true) String id
            ) throws JiWeiException {
        return fegin.delete(id);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @GetMapping(value = BaseUserContants.Employee.api_getById)
    @ApiOperation(value = "根据Id查找", notes = "根据uuid查找")
    public Envelop findById(
            @ApiParam(name = "id", value = "id")
            @PathVariable(value = "id", required = true) String id
    ) throws JiWeiException {
        return fegin.findById(id);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @RequestMapping(value = BaseUserContants.Employee.api_getList, method = RequestMethod.GET)
    @ApiOperation(value = "获取功能列表(分页)")
    public Envelop getEmployList(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,saasId,sex,phone,email,jxzc,lczcn,xlzc,xzzc,createUser,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String filterStr = "";
        if(StringUtils.isNotBlank(filters)){
            JSONObject jsonResult = new JSONObject(filters);
            if(jsonResult.has("name")){
                filterStr+="name?"+jsonResult.get("name")+";";
            }
        }
        return fegin.getList(fields, filterStr, sorts, size, page);
    }
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "-1"),//超时时间
            @HystrixProperty(name = "execution.timeout.enabled", value = "false") })
    @GetMapping(value = BaseUserContants.BaseRole.api_getListNoPage)
    @ApiOperation(value = "获取功能列表,不分页")
    public Envelop getListNoPage(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,name,saasId,sex,phone,email,jxzc,lczcn,xlzc,xzzc,createUser,remark")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
        String filterStr = "";
        if(StringUtils.isNotBlank(filters)){
            JSONObject jsonResult = new JSONObject(filters);
            if(jsonResult.has("saasId")){
                filterStr+="saasId="+jsonResult.get("saasId")+";";
            }
        }
        return fegin.getListNoPage(fields, filterStr, sorts);
    }
}

+ 0 - 2
web-gateway/src/main/java/com/yihu/jw/feign/base/base/FunctionFeign.java

@ -43,6 +43,4 @@ public interface FunctionFeign {
            @RequestParam(value = "filters", required = false) String filters,
            @RequestParam(value = "sorts", required = false) String sorts) throws JiWeiException;
    @GetMapping(value = BaseRequestMapping.Function.api_getChildren)
    Envelop getChildren(@PathVariable(value="id") String id) throws JiWeiException;
}

+ 46 - 0
web-gateway/src/main/java/com/yihu/jw/feign/base/base/SystemDictFeign.java

@ -0,0 +1,46 @@
package com.yihu.jw.feign.base.base;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.fallbackfactory.base.base.SystemDictFeignFallbackFactory;
import com.yihu.jw.feign.fallbackfactory.base.base.SystemDictFeignFallbackFactory;
import com.yihu.jw.restmodel.CommonContants;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@FeignClient(
        name = CommonContants.svr_base // name值是eurika的实例名字
        ,fallbackFactory  = SystemDictFeignFallbackFactory.class
)
@RequestMapping(value = BaseRequestMapping.api_base_common)
public interface SystemDictFeign {
    @RequestMapping(value = BaseRequestMapping.SystemDict.api_create,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    Envelop create(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseRequestMapping.SystemDict.api_update,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.PUT)
    Envelop update(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseRequestMapping.SystemDict.api_delete,method = RequestMethod.DELETE)
    Envelop delete(@PathVariable(value = "ids", required = true) String ids, @RequestParam(value = "userId") String userId, @RequestParam(value = "userName") String userName) throws JiWeiException;
    @GetMapping(value = BaseRequestMapping.SystemDict.api_getById)
    Envelop findById(@PathVariable(value = "id", required = true) String id) throws JiWeiException;
    @RequestMapping(value = BaseRequestMapping.SystemDict.api_getList, method = RequestMethod.GET)
    Envelop getList(
            @RequestParam(value = "fields", required = false) String fields,
            @RequestParam(value = "filters", required = false) String filters,
            @RequestParam(value = "sorts", required = false) String sorts,
            @RequestParam(value = "size", required = false) int size,
            @RequestParam(value = "page", required = false) int page) throws JiWeiException;
    @GetMapping(value = BaseRequestMapping.SystemDict.api_getListNoPage)
    Envelop getListNoPage(
            @RequestParam(value = "fields", required = false) String fields,
            @RequestParam(value = "filters", required = false) String filters,
            @RequestParam(value = "sorts", required = false) String sorts) throws JiWeiException;
}

+ 49 - 0
web-gateway/src/main/java/com/yihu/jw/feign/base/base/SystemDictListFeign.java

@ -0,0 +1,49 @@
package com.yihu.jw.feign.base.base;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.fallbackfactory.base.base.SystemDictListFeignFallbackFactory;
import com.yihu.jw.feign.fallbackfactory.base.base.SystemDictListFeignFallbackFactory;
import com.yihu.jw.restmodel.CommonContants;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@FeignClient(
        name = CommonContants.svr_base // name值是eurika的实例名字
        ,fallbackFactory  = SystemDictListFeignFallbackFactory.class
)
@RequestMapping(value = BaseRequestMapping.api_base_common)
public interface SystemDictListFeign {
    @RequestMapping(value = BaseRequestMapping.SystemDictList.api_create,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    Envelop create(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseRequestMapping.SystemDictList.api_update,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.PUT)
    Envelop update(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseRequestMapping.SystemDictList.api_delete,method = RequestMethod.DELETE)
    Envelop delete(@PathVariable(value = "ids", required = true) String ids, @RequestParam(value = "userId") String userId, @RequestParam(value = "userName") String userName) throws JiWeiException;
    @GetMapping(value = BaseRequestMapping.SystemDictList.api_getById)
    Envelop findById(@PathVariable(value = "id", required = true) String id) throws JiWeiException;
    @RequestMapping(value = BaseRequestMapping.SystemDictList.api_getList, method = RequestMethod.GET)
    Envelop getList(
            @RequestParam(value = "fields", required = false) String fields,
            @RequestParam(value = "filters", required = false) String filters,
            @RequestParam(value = "sorts", required = false) String sorts,
            @RequestParam(value = "size", required = false) int size,
            @RequestParam(value = "page", required = false) int page) throws JiWeiException;
    @GetMapping(value = BaseRequestMapping.SystemDictList.api_getListNoPage)
    Envelop getListNoPage(
            @RequestParam(value = "fields", required = false) String fields,
            @RequestParam(value = "filters", required = false) String filters,
            @RequestParam(value = "sorts", required = false) String sorts) throws JiWeiException;
    @GetMapping(value = BaseRequestMapping.SystemDictList.api_getChildren)
    Envelop getChildren(@PathVariable(value = "id") String id) throws JiWeiException;
}

+ 65 - 0
web-gateway/src/main/java/com/yihu/jw/feign/base/user/BaseMenuFeign.java

@ -0,0 +1,65 @@
package com.yihu.jw.feign.base.user;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.fallbackfactory.base.user.BaseMenuFeignFallbackFactory;
import com.yihu.jw.restmodel.CommonContants;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
 * Created by LiTaohong on 2017/12/05.
 */
@FeignClient(
        name = CommonContants.svr_base // name值是eurika的实例名字
        ,fallbackFactory  = BaseMenuFeignFallbackFactory.class
)
public interface BaseMenuFeign {
    
    @RequestMapping(value = BaseUserRequestMapping.BaseMenu.api_create,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    Envelop create(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseUserRequestMapping.BaseMenu.api_update,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.PUT)
    Envelop update(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseUserRequestMapping.BaseMenu.api_delete,method = RequestMethod.DELETE)
    Envelop delete(@PathVariable String id) throws JiWeiException;
    @GetMapping(value = BaseUserRequestMapping.BaseMenu.api_getOne)
    Envelop findById(@PathVariable(value = "id", required = true) String id) throws JiWeiException;
    @RequestMapping(value = BaseUserRequestMapping.BaseMenu.api_getList, method = RequestMethod.GET)
    Envelop getList(@RequestParam(value = "fields", required = false) String fields,
                    @RequestParam(value = "filters", required = false) String filters,
                    @RequestParam(value = "sorts", required = false) String sorts,
                    @RequestParam(value = "size", required = false) int size,
                    @RequestParam(value = "page", required = false) int page) throws JiWeiException;
    @GetMapping(value = BaseUserRequestMapping.BaseMenu.api_getListNoPage)
    Envelop getListNoPage(@RequestParam(value = "fields", required = false) String fields,
                          @RequestParam(value = "filters", required = false) String filters,
                          @RequestParam(value = "sorts", required = false) String sorts) throws JiWeiException;
    @GetMapping(value = BaseUserRequestMapping.BaseMenu.api_getchildren)
    Envelop getChildren(@RequestParam(value = "saasId", required = true) String saasId, @RequestParam(value = "parentId", required = true) String parentId) throws JiWeiException;
}

+ 46 - 0
web-gateway/src/main/java/com/yihu/jw/feign/base/user/BaseRoleFeign.java

@ -0,0 +1,46 @@
package com.yihu.jw.feign.base.user;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.fallbackfactory.base.user.BaseRoleFeignFallbackFactory;
import com.yihu.jw.restmodel.CommonContants;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
 * Created by LiTaohong on 2017/11/28.
 */
@FeignClient(
        name = CommonContants.svr_base // name值是eurika的实例名字
        ,fallbackFactory  = BaseRoleFeignFallbackFactory.class
)
public interface BaseRoleFeign {
    
    @RequestMapping(value = BaseUserRequestMapping.BaseRole.api_create,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    Envelop create(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseUserRequestMapping.BaseRole.api_update,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.PUT)
    Envelop update(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseUserRequestMapping.BaseRole.api_delete,method = RequestMethod.DELETE)
    Envelop delete(@PathVariable String id) throws JiWeiException;
    @GetMapping(value = BaseUserRequestMapping.BaseRole.api_getById)
    Envelop findById(@PathVariable(value = "id", required = true) String id) throws JiWeiException;
    @RequestMapping(value = BaseUserRequestMapping.BaseRole.api_getList, method = RequestMethod.GET)
    Envelop getList(
            @RequestParam(value = "fields", required = false) String fields,
            @RequestParam(value = "filters", required = false) String filters,
            @RequestParam(value = "sorts", required = false) String sorts,
            @RequestParam(value = "size", required = false) int size,
            @RequestParam(value = "page", required = false) int page) throws JiWeiException;
    @GetMapping(value = BaseUserRequestMapping.BaseRole.api_getListNoPage)
    Envelop getListNoPage(
            @RequestParam(value = "fields", required = false) String fields,
            @RequestParam(value = "filters", required = false) String filters,
            @RequestParam(value = "sorts", required = false) String sorts) throws JiWeiException;
}

+ 48 - 0
web-gateway/src/main/java/com/yihu/jw/feign/base/user/EmployFeign.java

@ -0,0 +1,48 @@
package com.yihu.jw.feign.base.user;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.fallbackfactory.base.user.EmployeeFeignFallbackFactory;
import com.yihu.jw.restmodel.CommonContants;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.base.BaseUserRequestMapping;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
 * Created by LiTaohong on 2017/11/30.
 */
@FeignClient(
        name = CommonContants.svr_base // name值是eurika的实例名字
        ,fallbackFactory  = EmployeeFeignFallbackFactory.class
)
@RequestMapping(value = BaseRequestMapping.api_base_common)
public interface EmployFeign {
    @RequestMapping(value = BaseUserRequestMapping.BaseRole.api_create,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.POST)
    Envelop create(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseUserRequestMapping.BaseRole.api_update,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,method = RequestMethod.PUT)
    Envelop update(@RequestBody String jsonData) throws JiWeiException;
    @RequestMapping(value =  BaseUserRequestMapping.BaseRole.api_delete,method = RequestMethod.DELETE)
    Envelop delete(@PathVariable String id) throws JiWeiException;
    @GetMapping(value = BaseUserRequestMapping.BaseRole.api_getById)
    Envelop findById(@PathVariable(value = "id", required = true) String id) throws JiWeiException;
    @RequestMapping(value = BaseUserRequestMapping.BaseRole.api_getList, method = RequestMethod.GET)
    Envelop getList(
            @RequestParam(value = "fields", required = false) String fields,
            @RequestParam(value = "filters", required = false) String filters,
            @RequestParam(value = "sorts", required = false) String sorts,
            @RequestParam(value = "size", required = false) int size,
            @RequestParam(value = "page", required = false) int page) throws JiWeiException;
    @GetMapping(value = BaseUserRequestMapping.BaseRole.api_getListNoPage)
    Envelop getListNoPage(
            @RequestParam(value = "fields", required = false) String fields,
            @RequestParam(value = "filters", required = false) String filters,
            @RequestParam(value = "sorts", required = false) String sorts) throws JiWeiException;
}

+ 0 - 25
web-gateway/src/main/java/com/yihu/jw/feign/base/user/EmployeeFeign.java

@ -1,25 +0,0 @@
package com.yihu.jw.feign.base.user;
import com.yihu.jw.feign.fallbackfactory.base.user.EmployeeFeignFallbackFactory;
import com.yihu.jw.restmodel.CommonContants;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
 * Created by chenweida on 2017/11/29.
 */
@FeignClient(
        name = CommonContants.svr_base // name值是eurika的实例名字
        ,fallbackFactory  = EmployeeFeignFallbackFactory.class
)
@RequestMapping(value = BaseRequestMapping.api_base_common)
public interface EmployeeFeign {
    @RequestMapping(value = BaseRequestMapping.Employee.api_getEmployeeByAccount, method = RequestMethod.GET)
    Envelop getEmployeeByAccount(@RequestParam(value = "userAccount",required = true)String userAccount);
}

+ 74 - 0
web-gateway/src/main/java/com/yihu/jw/feign/fallbackfactory/base/base/SystemDictFeignFallbackFactory.java

@ -0,0 +1,74 @@
package com.yihu.jw.feign.fallbackfactory.base.base;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.base.base.FunctionFeign;
import com.yihu.jw.feign.base.base.SystemDictFeign;
import com.yihu.jw.restmodel.common.Envelop;
import feign.hystrix.FallbackFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
@Component
public class SystemDictFeignFallbackFactory implements FallbackFactory<SystemDictFeign> {
    @Autowired
    private Tracer tracer;
    @Override
    public SystemDictFeign create(Throwable e) {
        return new SystemDictFeign() {
            @Override
            public Envelop create(@RequestBody String jsonData) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("创建系統字典失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("jsonData:"+jsonData);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop update(@RequestBody String jsonData) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("更新系統字典失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("jsonData:"+jsonData);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop delete(@PathVariable String codes, @RequestParam String userCode, @RequestParam String userName) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("删除系統字典失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("codes:"+codes);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop findById(String code) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找系統字典失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("code:"+code);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getList(String fields, String filterStr, String sorts, int size, int page) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("分页查找系統字典失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("fields:" + fields);
                tracer.getCurrentSpan().logEvent("filters:" + filterStr);
                tracer.getCurrentSpan().logEvent("sorts:" + sorts);
                tracer.getCurrentSpan().logEvent("size:" + size);
                tracer.getCurrentSpan().logEvent("page:" + page);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getListNoPage(String fields, String filters, String sorts) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找系統字典列表失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("fields:" + fields);
                tracer.getCurrentSpan().logEvent("filters:" + filters);
                tracer.getCurrentSpan().logEvent("sorts:" + sorts);
                throw new JiWeiException(e);
            }
        };
    }
}

+ 80 - 0
web-gateway/src/main/java/com/yihu/jw/feign/fallbackfactory/base/base/SystemDictListFeignFallbackFactory.java

@ -0,0 +1,80 @@
package com.yihu.jw.feign.fallbackfactory.base.base;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.base.base.FunctionFeign;
import com.yihu.jw.feign.base.base.SystemDictListFeign;
import com.yihu.jw.restmodel.common.Envelop;
import feign.hystrix.FallbackFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
@Component
public class SystemDictListFeignFallbackFactory implements FallbackFactory<SystemDictListFeign> {
    @Autowired
    private Tracer tracer;
    @Override
    public SystemDictListFeign create(Throwable e) {
        return new SystemDictListFeign() {
            @Override
            public Envelop create(@RequestBody String jsonData) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("创建系統字典集合失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("jsonData:"+jsonData);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop update(@RequestBody String jsonData) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("更新系統字典集合失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("jsonData:"+jsonData);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop delete(@PathVariable String codes, @RequestParam String userCode, @RequestParam String userName) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("删除系統字典集合失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("codes:"+codes);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop findById(String code) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找系統字典集合失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("code:"+code);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getList(String fields, String filterStr, String sorts, int size, int page) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("分页查找系統字典集合失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("fields:" + fields);
                tracer.getCurrentSpan().logEvent("filters:" + filterStr);
                tracer.getCurrentSpan().logEvent("sorts:" + sorts);
                tracer.getCurrentSpan().logEvent("size:" + size);
                tracer.getCurrentSpan().logEvent("page:" + page);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getListNoPage(String fields, String filters, String sorts) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找系統字典集合列表失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("fields:" + fields);
                tracer.getCurrentSpan().logEvent("filters:" + filters);
                tracer.getCurrentSpan().logEvent("sorts:" + sorts);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getChildren(String code) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找系統字典子项失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("code:" + code);
                throw new JiWeiException(e);
            }
        };
    }
}

+ 82 - 0
web-gateway/src/main/java/com/yihu/jw/feign/fallbackfactory/base/user/BaseMenuFeignFallbackFactory.java

@ -0,0 +1,82 @@
package com.yihu.jw.feign.fallbackfactory.base.user;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.base.user.BaseMenuFeign;
import com.yihu.jw.feign.base.user.BaseRoleFeign;
import com.yihu.jw.restmodel.common.Envelop;
import feign.hystrix.FallbackFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
/**
 * Created by LiTaohong on 2017/11/28.
 */
public class BaseMenuFeignFallbackFactory implements FallbackFactory<BaseMenuFeign> {
    @Autowired
    private Tracer tracer;
    @Override
    public BaseMenuFeign create(Throwable e) {
        return new BaseMenuFeign() {
            @Override
            public Envelop create(@RequestBody String jsonData) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("创建菜单失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("jsonData:"+jsonData);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop update(@RequestBody String jsonData) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("更新菜单失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("jsonData:"+jsonData);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop delete(@PathVariable String id) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("删除菜单失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("id:"+id);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop findById(String id) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找单个菜单失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("id:"+id);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getList(String fields, String filterStr, String sorts, int size, int page) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("分页查找菜单失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("fields:" + fields);
                tracer.getCurrentSpan().logEvent("filters:" + filterStr);
                tracer.getCurrentSpan().logEvent("sorts:" + sorts);
                tracer.getCurrentSpan().logEvent("size:" + size);
                tracer.getCurrentSpan().logEvent("page:" + page);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getListNoPage(String fields, String filters, String sorts) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找菜单列表失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("fields:" + fields);
                tracer.getCurrentSpan().logEvent("filters:" + filters);
                tracer.getCurrentSpan().logEvent("sorts:" + sorts);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getChildren(String saasId, String parentId) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找子菜单列表失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("filters:" + saasId);
                tracer.getCurrentSpan().logEvent("sorts:" + parentId);
                throw new JiWeiException(e);
            }
        };
    }
}

+ 73 - 0
web-gateway/src/main/java/com/yihu/jw/feign/fallbackfactory/base/user/BaseRoleFeignFallbackFactory.java

@ -0,0 +1,73 @@
package com.yihu.jw.feign.fallbackfactory.base.user;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.base.user.BaseRoleFeign;
import com.yihu.jw.restmodel.common.Envelop;
import feign.hystrix.FallbackFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
/**
 * Created by LiTaohong on 2017/11/28.
 */
public class BaseRoleFeignFallbackFactory implements FallbackFactory<BaseRoleFeign> {
    @Autowired
    private Tracer tracer;
    @Override
    public BaseRoleFeign create(Throwable e) {
        return new BaseRoleFeign() {
            @Override
            public Envelop create(@RequestBody String jsonData) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("创建角色失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("jsonData:"+jsonData);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop update(@RequestBody String jsonData) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("更新角色失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("jsonData:"+jsonData);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop delete(@PathVariable String id) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("删除角色失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("id:"+id);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop findById(String id) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找单个角色失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("id:"+id);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getList(String fields, String filterStr, String sorts, int size, int page) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("分页查找角色失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("fields:" + fields);
                tracer.getCurrentSpan().logEvent("filters:" + filterStr);
                tracer.getCurrentSpan().logEvent("sorts:" + sorts);
                tracer.getCurrentSpan().logEvent("size:" + size);
                tracer.getCurrentSpan().logEvent("page:" + page);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getListNoPage(String fields, String filters, String sorts) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找角色列表失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("fields:" + fields);
                tracer.getCurrentSpan().logEvent("filters:" + filters);
                tracer.getCurrentSpan().logEvent("sorts:" + sorts);
                throw new JiWeiException(e);
            }
        };
    }
}

+ 62 - 4
web-gateway/src/main/java/com/yihu/jw/feign/fallbackfactory/base/user/EmployeeFeignFallbackFactory.java

@ -1,14 +1,72 @@
package com.yihu.jw.feign.fallbackfactory.base.user;
import com.yihu.jw.feign.base.user.EmployeeFeign;
import com.yihu.jw.exception.business.JiWeiException;
import com.yihu.jw.feign.base.user.EmployFeign;
import com.yihu.jw.restmodel.common.Envelop;
import feign.hystrix.FallbackFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
/**
 * Created by chenweida on 2017/11/29.
 */
public class EmployeeFeignFallbackFactory  implements FallbackFactory<EmployeeFeign> {
public class EmployeeFeignFallbackFactory  implements FallbackFactory<EmployFeign> {
    @Autowired
    private Tracer tracer;
    @Override
    public EmployeeFeign create(Throwable cause) {
        return null;
    public EmployFeign create(Throwable e) {
        return new EmployFeign() {
            @Override
            public Envelop create(@RequestBody String jsonData) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("创建角色失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("jsonData:"+jsonData);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop update(@RequestBody String jsonData) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("更新角色失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("jsonData:"+jsonData);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop delete(@PathVariable String id) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("删除角色失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("id:"+id);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop findById(String id) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找单个角色失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("id:"+id);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getList(String fields, String filterStr, String sorts, int size, int page) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("分页查找角色失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("fields:" + fields);
                tracer.getCurrentSpan().logEvent("filters:" + filterStr);
                tracer.getCurrentSpan().logEvent("sorts:" + sorts);
                tracer.getCurrentSpan().logEvent("size:" + size);
                tracer.getCurrentSpan().logEvent("page:" + page);
                throw new JiWeiException(e);
            }
            @Override
            public Envelop getListNoPage(String fields, String filters, String sorts) throws JiWeiException {
                tracer.getCurrentSpan().logEvent("查找角色列表失败:原因:"+e.getMessage());
                tracer.getCurrentSpan().logEvent("fields:" + fields);
                tracer.getCurrentSpan().logEvent("filters:" + filters);
                tracer.getCurrentSpan().logEvent("sorts:" + sorts);
                throw new JiWeiException(e);
            }
        };
    }
}