Browse Source

Merge branch 'ijkdev' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into dev

# Conflicts:
#	app/app-iot-server/pom.xml
#	app/app-iot-server/src/main/java/com/yihu/ehr/iot/AppIotServer.java
#	app/app-iot-server/src/main/java/com/yihu/iot/controller/common/LoginController.java
#	app/app-iot-server/src/main/java/com/yihu/iot/security/config/EhrWebHttpSessionConfiguration.java
#	app/app-iot-server/src/main/java/com/yihu/iot/security/config/EhrWebSecurityConfiguration.java
#	app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAccessDecisionManager.java
#	app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAuthenticationFailureHandler.java
#	app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAuthenticationToken.java
#	app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUserDetails.java
#	app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUserDetailsService.java
#	app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUsernamePasswordAuthenticationFilter.java
#	app/app-iot-server/src/main/java/com/yihu/iot/security/entryPoint/LoginEntryPoint.java
#	app/app-iot-server/src/main/resources/application.yml
#	app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebAuthenticationProvider.java
#	app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebAuthenticationSuccessHandler.java
#	app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebContextLogoutHandler.java
#	app/public-health-server/src/main/java/com/yihu/health/util/CurrentRequest.java
#	svr/svr-base/src/main/resources/application.yml
#	web-gateway/src/main/java/com/yihu/jw/controller/base/login/LoginContorller.java
#	web-gateway/src/main/resources/application.yml
wangzhinan 6 years ago
parent
commit
d8407ed29a
35 changed files with 2672 additions and 264 deletions
  1. 84 1
      app/app-iot-server/pom.xml
  2. 32 0
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/AppIotServer.java
  3. 157 0
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/config/DataSourceConfig.java
  4. 27 0
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/config/HibernateProperties.java
  5. 59 0
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/config/WlyyJpa.java
  6. 41 0
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/dao/UserDao.java
  7. 43 0
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/model/IdEntity.java
  8. 457 0
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/model/User.java
  9. 18 12
      app/app-iot-server/src/main/java/com/yihu/iot/controller/common/LoginController.java
  10. 22 0
      app/app-iot-server/src/main/java/com/yihu/iot/security/config/EhrWebHttpSessionConfiguration.java
  11. 138 0
      app/app-iot-server/src/main/java/com/yihu/iot/security/config/EhrWebSecurityConfiguration.java
  12. 98 0
      app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAccessDecisionManager.java
  13. 43 0
      app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAuthenticationFailureHandler.java
  14. 57 0
      app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAuthenticationToken.java
  15. 50 0
      app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUserDetails.java
  16. 88 0
      app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUserDetailsService.java
  17. 180 0
      app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUsernamePasswordAuthenticationFilter.java
  18. 39 0
      app/app-iot-server/src/main/java/com/yihu/iot/security/entryPoint/LoginEntryPoint.java
  19. 20 22
      app/app-iot-server/src/main/java/com/yihu/iot/service/common/BaseService.java
  20. 238 171
      app/app-iot-server/src/main/java/com/yihu/iot/service/common/LoginService.java
  21. 48 0
      app/app-iot-server/src/main/resources/application-jwdev.yml
  22. 45 0
      app/app-iot-server/src/main/resources/application-jwprod.yml
  23. 44 0
      app/app-iot-server/src/main/resources/application-jwtest.yml
  24. 28 30
      app/app-iot-server/src/main/resources/application.yml
  25. 13 12
      app/app-iot-server/src/main/webapp/front/js/scripts/login.js
  26. 159 0
      app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebAuthenticationProvider.java
  27. 68 0
      app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebAuthenticationSuccessHandler.java
  28. 58 0
      app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebContextLogoutHandler.java
  29. 51 0
      app/public-health-server/src/main/java/com/yihu/health/util/CurrentRequest.java
  30. 4 4
      server/svr-admin-server/pom.xml
  31. 1 1
      server/svr-admin-server/src/main/resources/application.yml
  32. 11 11
      server/svr-admin-server/src/main/resources/bootstrap.yml
  33. 36 0
      svr/svr-base/src/main/resources/application.yml
  34. 105 0
      web-gateway/src/main/java/com/yihu/jw/controller/base/login/LoginContorller.java
  35. 110 0
      web-gateway/src/main/resources/application.yml

+ 84 - 1
app/app-iot-server/pom.xml

@ -9,10 +9,17 @@
        <relativePath>../../wlyy-parent-pom/pom.xml</relativePath>
    </parent>
<<<<<<< HEAD
    <groupId>com.yihu.ehr.iot</groupId>
    <artifactId>app-iot-server</artifactId>
    <packaging>war</packaging>
    <version>${parent.version}</version>
=======
    <properties>
        <version.hibernate-annotations>4.0.5.Final</version.hibernate-annotations>
        <version.hibernate-jpa-api>1.0.0.Final</version.hibernate-jpa-api>
    </properties>
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756
    <!-- 依赖包 -->
    <dependencies>
@ -54,6 +61,40 @@
            <artifactId>jstl</artifactId>
            <scope>compile</scope>
        </dependency>
<<<<<<< HEAD
=======
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>-->
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-security</artifactId>-->
        <!--</dependency>-->
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756
        <dependency>
            <groupId>org.apache.tiles</groupId>
@ -75,6 +116,13 @@
            <artifactId>jest</artifactId>
            <version>2.4.0</version>
        </dependency>
<<<<<<< HEAD
=======
        <!--<dependency>-->
        <!--<groupId>org.springframework.session</groupId>-->
        <!--<artifactId>spring-session-data-redis</artifactId>-->
        <!--</dependency>-->
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756
        <dependency>
            <groupId>net.lingala.zip4j</groupId>
            <artifactId>zip4j</artifactId>
@ -157,6 +205,41 @@
            <artifactId>mime-util</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!--演示用 后面可以删除 start-->
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>common-data-mysql-starter</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.15</version>
        </dependency>
        <!--Hibernate framework-->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>${version.hibernate-jpa-api}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.12.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.12.Final</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
        <!--Miscellaneous-->
        <!--演示用 后面可以删除 end-->
    </dependencies>
    <build>
@ -164,7 +247,7 @@
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin </artifactId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>

+ 32 - 0
app/app-iot-server/src/main/java/com/yihu/ehr/iot/AppIotServer.java

@ -0,0 +1,32 @@
package com.yihu.ehr.iot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableAutoConfiguration(exclude = {
        SecurityAutoConfiguration.class,
        ManagementWebSecurityAutoConfiguration.class})
@ComponentScan(basePackages={"com.yihu.base","com.yihu.ehr.iot"})
//@EnableRedisHttpSession
public class AppIotServer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(AppIotServer.class);
    }
	public static void main(String[] args) {
        SpringApplication app = new SpringApplication(AppIotServer.class);
        app.run(args);
	}
}

+ 157 - 0
app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/config/DataSourceConfig.java

@ -0,0 +1,157 @@
package com.yihu.ehr.iot.yanshi.config;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
 * Created by Administrator on 2016.10.20.
 * 多数据源配置
 */
@Configuration
public class DataSourceConfig {
    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;
    @Value("${spring.datasource.initialSize}")
    private Integer initialSize;
    @Value("${spring.datasource.minIdle}")
    private Integer minIdle;
    @Value("${spring.datasource.maxActive}")
    private Integer maxActive;
    @Value("${spring.datasource.maxWait}")
    private Integer maxWait;
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private Integer timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private Integer minEvictableIdleTimeMillis;
    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;
    @Value("${spring.datasource.testWhileIdle}")
    private Boolean testWhileIdle;
    @Value("${spring.datasource.testOnBorrow}")
    private Boolean testOnBorrow;
    @Value("${spring.datasource.testOnReturn}")
    private Boolean testOnReturn;
    @Value("${spring.datasource.poolPreparedStatements}")
    private Boolean poolPreparedStatements;
    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private Integer maxPoolPreparedStatementPerConnectionSize;
    @Value("${spring.datasource.removeAbandoned}")
    private Boolean removeAbandoned;
    @Value("${spring.datasource.removeAbandonedTimeout}")
    private Integer removeAbandonedTimeout;
    @Value("${spring.datasource.logAbandoned}")
    private Boolean logAbandoned;
    @Value("${spring.datasource.filters")
    private String filters;
    @Value("${spring.datasource.wlyy.url}")
    private String wlyyUrl;
    @Value("${spring.datasource.wlyy.username}")
    private String wlyyUsername;
    @Value("${spring.datasource.wlyy.password}")
    private String wlyyPassword;
    /**
     * 主数据源
     *
     * @return
     */
    @Bean(name = "wlyy")
    @Primary//主库 默认不写名字用这个
    public DataSource wlyyDataSource(StatFilter statFilter) throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(wlyyUrl);
        datasource.setUsername(wlyyUsername);
        datasource.setPassword(wlyyPassword);
        datasource.setDriverClassName(driverClassName);
        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        datasource.setRemoveAbandoned(removeAbandoned);
        datasource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        datasource.setLogAbandoned(logAbandoned);
        datasource.setFilters(filters);
        datasource.setConnectProperties(properties());//;# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        datasource.setUseGlobalDataSourceStat(true);// 合并多个DruidDataSource的监控数据
        List proxyFilters = new ArrayList<>();
        proxyFilters.add(statFilter);
        datasource.setProxyFilters(proxyFilters);
        return datasource;
    }
    private Properties properties() {
        Properties properties = new Properties();
        properties.put("druid.stat.mergeSql", "true");
        properties.put("slowSqlMillis", "1000");
        return properties;
    }
    //------------------------------------druid 监控----------------------------------------------
    @Bean
    public ServletRegistrationBean statViewServlet() {
        //创建servlet注册实体
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //设置ip白名单
        //servletRegistrationBean.addInitParameter("allow","127.0.0.1");
        //设置ip黑名单,如果allow与deny共同存在时,deny优先于allow
        // servletRegistrationBean.addInitParameter("deny","192.168.0.19");
        //设置控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "jkzl");
        servletRegistrationBean.addInitParameter("loginPassword", "jkzlehr");
        //是否可以重置数据
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }
    @Bean
    public FilterRegistrationBean filterRegistrationBean(WebStatFilter webStatFilter) {
        //创建过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(webStatFilter);
        //设置过滤器过滤路径
        filterRegistrationBean.addUrlPatterns("/*");
        //忽略过滤的形式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
    @Bean
    public StatFilter statFilter() {
        return new StatFilter();
    }
    @Bean
    public WebStatFilter webStatFilter() {
        return new WebStatFilter();
    }
    //------------------------------------druid 监控----------------------------------------------
}

+ 27 - 0
app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/config/HibernateProperties.java

@ -0,0 +1,27 @@
package com.yihu.ehr.iot.yanshi.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Properties;
/**
 * Created by chenweida on 2017/4/6.
 */
@Component
public class HibernateProperties {
    @Value("${hibernate.dialect}")
    private String dialect;
    @Value("${hibernate.show_sql}")
    private String show_sql;
    @Value("${hibernate.ejb.naming_strategy}")
    private String naming_strategy;
    public  Properties hibProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect",dialect);
        properties.put("hibernate.show_sql", show_sql);
        properties.put("hibernate.ejb.naming_strategy", naming_strategy);
        return properties;
    }
}

+ 59 - 0
app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/config/WlyyJpa.java

@ -0,0 +1,59 @@
package com.yihu.ehr.iot.yanshi.config;
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.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
/**
 * Created by chenweida on 2017/4/6.
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "wlyyEntityManagerFactory",
        transactionManagerRef = "wlyyTransactionManager",
        basePackages = {"com.yihu.ehr.iot.yanshi.dao"})   //设置Repository所在位置
public class WlyyJpa {
    @Autowired
    private HibernateProperties hibernateProperties;
    @Bean(name = "wlyyEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(dataSource);
        emfb.setPackagesToScan("com.yihu.ehr.iot.yanshi.model");
        emfb.setPersistenceUnitName("wlyy");
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        emfb.setJpaVendorAdapter(vendorAdapter);
        Properties properties = new Properties();
        properties.putAll(hibernateProperties.hibProperties());
        properties.put("hibernate.ejb.naming_strategy","org.hibernate.cfg.DefaultNamingStrategy");
        emfb.setJpaProperties(properties);
        return emfb;
    }
    @Bean(name = "wlyyTransactionManager")
    @Primary
    JpaTransactionManager transactionManagerSecondary(
            @Qualifier("wlyyEntityManagerFactory") EntityManagerFactory builder) {
        return new JpaTransactionManager(builder);
    }
}

+ 41 - 0
app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/dao/UserDao.java

@ -0,0 +1,41 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.ehr.iot.yanshi.dao;
import com.yihu.ehr.iot.yanshi.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface UserDao extends PagingAndSortingRepository<User, Long>, JpaSpecificationExecutor<User> {
	@Query("from User a where a.mobile = ?1")
	User findByMobile(String mobile);
	
	User findByCode(String code);
	
	@Query("select a from User a where a.organizationId = ?1")
	List<User> findByOrgid(long orgId);
	@Query("from User a where a.mobile = ?1")
	List<User> findByPhone(String mobile);
	@Query("from User a where a.mobile = ?1 and a.id!=?2")
	List<User> findByPhoneWithOutId(String mobile, Long id);
    @Query("from User a where a.name like ?1 order by code")
    Page<User> searchUsersByName(String name, Pageable pageRequest);
	List<User> findBySeat(String seat);
	User findByJobNo(String jobNo);
}

+ 43 - 0
app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/model/IdEntity.java

@ -0,0 +1,43 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.ehr.iot.yanshi.model;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
/**
 * 统一定义id的entity基类.
 * 
 * 基类统一定义id的属性名称、数据类型、列名映射及生成策略.
 * Oracle需要每个Entity独立定义id的SEQUCENCE时,不继承于本类而改为实现一个Idable的接口。
 * 
 * @author calvin
 */
// JPA 基类的标识
@MappedSuperclass
public abstract class IdEntity implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3673803562328635206L;
	
	// 非业务主键
	protected Long id;
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	
}

+ 457 - 0
app/app-iot-server/src/main/java/com/yihu/ehr/iot/yanshi/model/User.java

@ -0,0 +1,457 @@
package com.yihu.ehr.iot.yanshi.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
import java.util.List;
/**
 * 用户表
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_user")
public class User extends IdEntity {
    private static final long serialVersionUID = 5397123441067268436L;
	// 用户标识
	private String code;
    // 姓名
    private String name;
    // 手机号
    private String mobile;
    // 登录密码
    private String password;
    // 密码加密密钥
    private String salt;
    // 用户类型:1超级管理员,2医生   3客服管理员   4普通客服
    private int type;
    //用户类型名称
    private String typeName;
    //用户拥有的权限标识,以逗号分隔
    private String roles;
    // 用户找拥有的权限以逗号分隔
    private String roleName;
	// 添加日期
	private Date czrq;
	// 所属机构
	private long organizationId;
    // 所属机构名称
    private String organizationName;
    //客服工号
    private String jobNo;
    //客服坐席号
    private String seat;
    //客服电话
    private String phone;
    //是否在线 0不在线   1离开  2在线
    private String online;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getSalt() {
        return salt;
    }
    public void setSalt(String salt) {
        this.salt = salt;
    }
    public int getType() {
        return type;
    }
    public void setType(int type) {
        this.type = type;
    }
    @Transient
    public String getTypeName() {
        return typeName;
    }
    public void setTypeName(String typeName) {
        this.typeName = typeName;
    }
    public String getRoles() {
        return roles;
    }
    public void setRoles(String roles) {
        this.roles = roles;
    }
    @Transient
    @JsonIgnore
    public String getRoleName() {
        return roleName;
    }
    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    @Column(name = "organization_id")
    public long getOrganizationId() {
        return organizationId;
    }
    public void setOrganizationId(long organizationId) {
        this.organizationId = organizationId;
    }
    @Transient
    public String getOrganizationName() {
        return organizationName;
    }
    public void setOrganizationName(String organizationName) {
        this.organizationName = organizationName;
    }
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
    @Transient
    @JsonIgnore
    public List<String> getRoleList() {
        // 角色列表在数据库中实际以逗号分隔字符串存储,因此返回不能修改的List.
        return ImmutableList.copyOf(StringUtils.split("", ","));
    }
    @Column(name = "job_no")
    public String getJobNo() {
        return jobNo;
    }
    public void setJobNo(String jobNo) {
        this.jobNo = jobNo;
    }
    public String getSeat() {
        return seat;
    }
    public void setSeat(String seat) {
        this.seat = seat;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getOnline() {
        return online;
    }
    public void setOnline(String online) {
        this.online = online;
    }
    /**
	 * 
	 */
//	private static final long serialVersionUID = 5397123441067268436L;
//
//	// 用户标识
//	private String code;
//	// 添加日期
//	private Date czrq;
//	//科室code
//	private String hospitalDept;
//	//是否签约 1是 0否
//	private String isSign;
//	//职务code
//	private String mbjob;
//	// 手机号
//	private String mobile;
//	// 姓名
//	private String name;
//	//部门code
//	private String organizationDept;
//	// 所属机构
//	private long organizationId;
//	// 登录密码
//	private String password;
//	//简介
//	private String  remark;
//	// 密码加密密钥
//	private String salt;
//	//性别
//	private String  sex;
//	//专场
//	private String speciality;
//	// 用户类型:1超级管理员,2医生
//	private int type;
//
//	// 用户找拥有的权限以逗号分隔
//	private String roles;
//	// 用户找拥有的权限以逗号分隔
//	private String roleName;
//	private String photo;
//	//职务code
//	private String mbjobName;;
//	//科室code
//	private String hospitalDeptName;
//
//	private String organizationDeptName;
//
//	public String getCode() {
//		return code;
//	}
//
//	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
//	public Date getCzrq() {
//		return czrq;
//	}
//
//	@Column(name = "hospital_dept")
//	public String getHospitalDept() {
//		return hospitalDept;
//	}
//
//	@Column(name = "is_sign")
//	public String getIsSign() {
//		return isSign;
//	}
//
//	@Column(name = "mbjob")
//	public String getMbjob() {
//		return mbjob;
//	}
//
//	public String getMobile() {
//		return mobile;
//	}
//
//	public String getName() {
//		return name;
//	}
//
//	@Column(name = "organization_dept")
//	public String getOrganizationDept() {
//		return organizationDept;
//	}
//
//	@Column(name = "organization_id")
//	public long getOrganizationId() {
//		return organizationId;
//	}
//
//	public String getPassword() {
//		return password;
//	}
//
//	@Column(name = "remark")
//	public String getRemark() {
//		return remark;
//	}
//
//	@Transient
//	@JsonIgnore
//	public List<String> getRoleList() {
//		// 角色列表在数据库中实际以逗号分隔字符串存储,因此返回不能修改的List.
//		return ImmutableList.copyOf(StringUtils.split("", ","));
//	}
//
//	public String getRoles() {
//		return roles;
//	}
//
//	public String getSalt() {
//		return salt;
//	}
//
//	public String getSex() {
//		return sex;
//	}
//
//
//
//	public String getPhoto() {
//		return photo;
//	}
//
//	public void setPhoto(String photo) {
//		this.photo = photo;
//	}
//
//	@Column(name = "speciality")
//	public String getSpeciality() {
//		return speciality;
//	}
//
//	public int getType() {
//		return type;
//	}
//
//	public void setCode(String code) {
//		this.code = code;
//	}
//
//	public void setCzrq(Date czrq) {
//		this.czrq = czrq;
//	}
//
//	public void setHospitalDept(String hospitalDept) {
//		this.hospitalDept = hospitalDept;
//	}
//
//	public void setIsSign(String isSign) {
//		this.isSign = isSign;
//	}
//
//	public void setMbjob(String mbjob) {
//		this.mbjob = mbjob;
//	}
//
//	public void setMobile(String mobile) {
//		this.mobile = mobile;
//	}
//
//	public void setName(String name) {
//		this.name = name;
//	}
//
//	public void setOrganizationDept(String organizationDept) {
//		this.organizationDept = organizationDept;
//	}
//
//	public void setOrganizationId(long organizationId) {
//		this.organizationId = organizationId;
//	}
//
//	public void setPassword(String password) {
//		this.password = password;
//	}
//
//	public void setRemark(String remark) {
//		this.remark = remark;
//	}
//
//	public void setRoles(String roles) {
//		this.roles = roles;
//	}
//
//	public void setSalt(String salt) {
//		this.salt = salt;
//	}
//
//	public void setSex(String sex) {
//		this.sex = sex;
//	}
//
//	public void setSpeciality(String speciality) {
//		this.speciality = speciality;
//	}
//
//	public void setType(int type) {
//		this.type = type;
//	}
//
//	@Override
//	public String toString() {
//		return ToStringBuilder.reflectionToString(this);
//	}
//
//	@Transient
//	public String getRoleName() {
//		return roleName;
//	}
//
//	public void setRoleName(String roleName) {
//		this.roleName = roleName;
//	}
//
//	@Transient
//	public String getMbjobName() {
//		return mbjobName;
//	}
//
//	public void setMbjobName(String mbjobName) {
//		this.mbjobName = mbjobName;
//	}
//
//	@Transient
//	public String getHospitalDeptName() {
//		return hospitalDeptName;
//	}
//
//	public void setHospitalDeptName(String hospitalDeptName) {
//		this.hospitalDeptName = hospitalDeptName;
//	}
//
//	@Transient
//	public String getOrganizationDeptName() {
//		return organizationDeptName;
//	}
//
//	public void setOrganizationDeptName(String organizationDeptName) {
//		this.organizationDeptName = organizationDeptName;
//	}
	
}

+ 18 - 12
app/app-iot-server/src/main/java/com/yihu/iot/controller/common/LoginController.java

@ -47,15 +47,21 @@ public class LoginController extends BaseController{
     * @param password
     * @return
     */
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "登录验证")
    public Result login(HttpServletRequest request,
<<<<<<< HEAD:app/app-iot-server/src/main/java/com/yihu/iot/controller/common/LoginController.java
                        @ApiParam(name = "userName", value = "登录账号")
            @RequestParam(value = "userName") String userName,
                        @ApiParam(name = "password", value = "密码")
=======
            @ApiParam(name = "username", value = "登录账号")
            @RequestParam(value = "username") String userName,
            @ApiParam(name = "password", value = "密码")
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/controller/common/LoginController.java
            @RequestParam(value = "password") String password) {
            return loginService.login(request, userName, password);
            return loginService.loginyanshi(request, userName, password);
    }
    /**
@ -89,14 +95,14 @@ public class LoginController extends BaseController{
        response.sendRedirect(contextPath + "/front/views/signin.html?clientId=" + clientId);
    }
    /*
     * 自动登录
     */
    @RequestMapping(value = "/autoLogin", method = RequestMethod.POST)
    @ResponseBody
    public Envelop autoLogin(HttpServletRequest request, Model model,
                             @ApiParam(name = "token", value = "TOKEN")
                             @RequestParam(value = "token") String token) throws Exception {
        return loginService.autoLogin(request, model, token);
    }
//    /*
//     * 自动登录
//     */
//    @RequestMapping(value = "/autoLogin", method = RequestMethod.POST)
//    @ResponseBody
//    public Envelop autoLogin(HttpServletRequest request, Model model,
//                             @ApiParam(name = "token", value = "TOKEN")
//                             @RequestParam(value = "token") String token) throws Exception {
//        return loginService.autoLogin(request, model, token);
//    }
}

+ 22 - 0
app/app-iot-server/src/main/java/com/yihu/iot/security/config/EhrWebHttpSessionConfiguration.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/app-iot-server/src/main/java/com/yihu/iot/security/config/EhrWebHttpSessionConfiguration.java
package com.yihu.iot.security.config;
import org.springframework.context.annotation.Bean;
@ -17,3 +18,24 @@ public class EhrWebHttpSessionConfiguration {
        return new SessionRegistryImpl();
    }
}
=======
//package com.yihu.ehr.iot.security.config;
//
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.security.core.session.SessionRegistryImpl;
//
///**
// * Created by progr1mmer on 2018/1/27.
// */
//@Configuration
////@EnableRedisHttpSession
//public class EhrWebHttpSessionConfiguration {
//
//    @Bean
//    SessionRegistry sessionRegistry(){
//        return new SessionRegistryImpl();
//    }
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/config/EhrWebHttpSessionConfiguration.java

+ 138 - 0
app/app-iot-server/src/main/java/com/yihu/iot/security/config/EhrWebSecurityConfiguration.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/app-iot-server/src/main/java/com/yihu/iot/security/config/EhrWebSecurityConfiguration.java
package com.yihu.iot.security.config;
import com.yihu.iot.security.entryPoint.LoginEntryPoint;
@ -129,3 +130,140 @@ public class EhrWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    */
}
=======
//package com.yihu.ehr.iot.security.config;
//
//import com.yihu.ehr.iot.security.core.*;
//import com.yihu.ehr.iot.security.entryPoint.LoginEntryPoint;
//import com.yihu.ehr.iot.service.common.LoginService;
//import com.yihu.ehr.iot.yanshi.dao.UserDao;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
//import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.builders.WebSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
//import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//@Configuration
//@EnableWebSecurity
//public class EhrWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
//
//    @Value("${app.oauth2InnerUrl}")
//    protected String oauth2InnerUrl;
//    @Value("${service-gateway.profileInnerUrl}")
//    protected String profileInnerUrl;
//
//    @Autowired
//    private EhrWebAuthenticationProvider ehrWebAuthenticationProvider;
//    @Autowired
//    private EhrWebAuthenticationSuccessHandler ehrWebAuthenticationSuccessHandler;
//    @Autowired
//    private EhrWebAuthenticationFailureHandler ehrWebAuthenticationFailureHandler;
//    //@Autowired
//    //private EhrWebAccessDecisionManager ehrWebAccessDecisionManager;
//    @Autowired
//    private SessionRegistry sessionRegistry;
//    @Autowired
//    private LoginEntryPoint loginEntryPoint;
//    @Autowired
//    private EhrWebContextLogoutHandler ehrWebContextLogoutHandler;
//
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        //web.ignoring().antMatchers("/ambulance/search"); //忽略授权地址
//    }
//
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        // ---------- 自定义Filter Start ----------
//        EhrWebUsernamePasswordAuthenticationFilter ehrWebUsernamePasswordAuthenticationFilter = new EhrWebUsernamePasswordAuthenticationFilter(oauth2InnerUrl, profileInnerUrl);
//        ehrWebUsernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(ehrWebAuthenticationSuccessHandler);
//        ehrWebUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(ehrWebAuthenticationFailureHandler);
//        ehrWebUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
//        ehrWebUsernamePasswordAuthenticationFilter.setSessionAuthenticationStrategy(new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry));
//        http.addFilterBefore(ehrWebUsernamePasswordAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
//        // ---------- 自定义Filter End ----------
//        //http.sessionManagement().maximumSessions(3).expiredUrl("/login?expired").sessionRegistry(sessionRegistry);
//        //http.addFilter(ehrWebUsernamePasswordAuthenticationFilter);
//        http.authorizeRequests()
//                //.accessDecisionManager(ehrWebAccessDecisionManager)
//                //.antMatchers("/front/views/*.html").hasRole("USER") //拦截html
//                //.antMatchers("/user").hasRole("USER")
//                //.antMatchers("/ambulance/**").hasRole("USER")
//                //.antMatchers("/admin/**").hasRole("ADMIN")
//                .antMatchers("/front/css/**").permitAll()
//                .antMatchers("/front/fonts/**").permitAll()
//                .antMatchers("/front/images/**").permitAll()
//                .antMatchers("/front/js/**").permitAll()
//                .antMatchers("/front/views/signin.html").permitAll()
//                .antMatchers("/login/**").permitAll()
//                .antMatchers("/svr-iot/wlyy/**").permitAll()//健康监测平台没有做登录(这里添加免登录验证)
//                .antMatchers("/svr-iot/fileUpload/commonUpload").permitAll()//公共的文件上传(这里添加免登录验证)
//                .antMatchers("/front/views/**").hasRole("USER")
//                .antMatchers("/**").hasRole("USER")
//                .and().formLogin().loginPage("/login")
//                .and().exceptionHandling().authenticationEntryPoint(loginEntryPoint)
//                .and().logout().addLogoutHandler(ehrWebContextLogoutHandler).logoutUrl("/logout").logoutSuccessUrl("/login")
//                .and().headers().frameOptions().disable()
//                .and().csrf().disable();
//    }
//
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.authenticationProvider(ehrWebAuthenticationProvider); //自定义认证提供者
//    }
//
//    @Autowired
//    private UserDao userDao;
//    @Bean
//    EhrWebUserDetailsService ehrWebUserDetailsService(){
//        return new EhrWebUserDetailsService(profileInnerUrl,userDao);
//    }
//
//    @Bean
//    EhrWebAuthenticationProvider ehrWebAuthenticationProvider(UserDetailsService userDetailsService) {
//        EhrWebAuthenticationProvider ehrWebAuthenticationProvider = new EhrWebAuthenticationProvider(userDetailsService);
//        ehrWebAuthenticationProvider.setPasswordEncoder(new Md5PasswordEncoder());
//        return ehrWebAuthenticationProvider;
//    }
//
//    @Bean
//    EhrWebAuthenticationSuccessHandler ehrWebAuthenticationSuccessHandler(){
//        return new EhrWebAuthenticationSuccessHandler();
//    }
//
//    @Bean
//    EhrWebAuthenticationFailureHandler ehrWebAuthenticationFailureHandler(){
//        return new EhrWebAuthenticationFailureHandler();
//    }
//
//    @Bean
//    EhrWebContextLogoutHandler ehrWebContextLogoutHandler(){
//        return new EhrWebContextLogoutHandler();
//    }
//
//    @Bean
//    LoginEntryPoint loginEntryPoint(){
//        return new LoginEntryPoint("/login");
//    }
//
//    /**
//    @Bean
//    EhrWebAccessDecisionManager ehrWebAccessDecisionManager() {
//        return new EhrWebAccessDecisionManager(null);
//    }
//    */
//
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/config/EhrWebSecurityConfiguration.java

+ 98 - 0
app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAccessDecisionManager.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAccessDecisionManager.java
package com.yihu.iot.security.core;
import org.apache.commons.logging.Log;
@ -93,3 +94,100 @@ public class EhrWebAccessDecisionManager extends AbstractAccessDecisionManager {
        return false;
    }
}
=======
//package com.yihu.ehr.iot.security.core;
//
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.context.MessageSource;
//import org.springframework.context.support.MessageSourceAccessor;
//import org.springframework.security.access.AccessDecisionManager;
//import org.springframework.security.access.AccessDecisionVoter;
//import org.springframework.security.access.AccessDeniedException;
//import org.springframework.security.access.ConfigAttribute;
//import org.springframework.security.access.vote.AbstractAccessDecisionManager;
//import org.springframework.security.authentication.InsufficientAuthenticationException;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.SpringSecurityMessageSource;
//import org.springframework.util.Assert;
//
//import java.util.Collection;
//import java.util.Iterator;
//import java.util.List;
//
///**
// * Final AccessDecisionManager
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebAccessDecisionManager extends AbstractAccessDecisionManager {
//
//    private final Log logger = LogFactory.getLog(this.getClass());
//    private List<AccessDecisionVoter<? extends Object>> decisionVoters;
//    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
//    private boolean allowIfAllAbstainDecisions = false;
//
//    public EhrWebAccessDecisionManager(List<AccessDecisionVoter<? extends Object>> decisionVoters) {
//        super(decisionVoters);
//        Assert.notEmpty(decisionVoters, "A list of AccessDecisionVoters is required");
//        this.decisionVoters = decisionVoters;
//    }
//
//    @Override
//    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
//
//    }
//
//    public void afterPropertiesSet() throws Exception {
//        Assert.notEmpty(this.decisionVoters, "A list of AccessDecisionVoters is required");
//        Assert.notNull(this.messages, "A message source must be set");
//    }
//
//    public List<AccessDecisionVoter<? extends Object>> getDecisionVoters() {
//        return this.decisionVoters;
//    }
//
//    public boolean isAllowIfAllAbstainDecisions() {
//        return this.allowIfAllAbstainDecisions;
//    }
//
//    public void setAllowIfAllAbstainDecisions(boolean allowIfAllAbstainDecisions) {
//        this.allowIfAllAbstainDecisions = allowIfAllAbstainDecisions;
//    }
//
//    public void setMessageSource(MessageSource messageSource) {
//        this.messages = new MessageSourceAccessor(messageSource);
//    }
//
//    public boolean supports(ConfigAttribute attribute) {
//        Iterator var2 = this.decisionVoters.iterator();
//
//        AccessDecisionVoter voter;
//        do {
//            if(!var2.hasNext()) {
//                return false;
//            }
//
//            voter = (AccessDecisionVoter)var2.next();
//        } while(!voter.supports(attribute));
//
//        return true;
//    }
//
//    public boolean supports(Class<?> clazz) {
//        Iterator var2 = this.decisionVoters.iterator();
//
//        AccessDecisionVoter voter;
//        do {
//            if(!var2.hasNext()) {
//                return true;
//            }
//
//            voter = (AccessDecisionVoter)var2.next();
//        } while(voter.supports(clazz));
//
//        return false;
//    }
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAccessDecisionManager.java

+ 43 - 0
app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAuthenticationFailureHandler.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAuthenticationFailureHandler.java
package com.yihu.iot.security.core;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -38,3 +39,45 @@ public class EhrWebAuthenticationFailureHandler implements AuthenticationFailure
        httpServletResponse.getWriter().print(objectMapper.writeValueAsString(envelop));
    }
}
=======
//package com.yihu.ehr.iot.security.core;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.util.rest.Envelop;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.security.core.AuthenticationException;
//import org.springframework.security.web.authentication.AuthenticationFailureHandler;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebAuthenticationFailureHandler implements AuthenticationFailureHandler {
//
//    @Autowired
//    private ObjectMapper objectMapper;
//
//    /**
//     * Step 4
//     * @param httpServletRequest
//     * @param httpServletResponse
//     * @param authException
//     * @throws IOException
//     * @throws ServletException
//     */
//    @Override
//    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException authException) throws IOException, ServletException {
//        Envelop envelop = new Envelop();
//        envelop.setSuccessFlg(false);
//        envelop.setErrorMsg("invalid account or password !");
//        envelop.setErrorCode(-1);
//        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//        httpServletResponse.getWriter().print(objectMapper.writeValueAsString(envelop));
//    }
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationFailureHandler.java

+ 57 - 0
app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAuthenticationToken.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebAuthenticationToken.java
package com.yihu.iot.security.core;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -52,3 +53,59 @@ public class EhrWebAuthenticationToken extends UsernamePasswordAuthenticationTok
        return credentials;
    }
}
=======
//package com.yihu.ehr.iot.security.core;
//
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.SpringSecurityCoreVersion;
//
//import java.util.Collection;
//
///**
// * Sso integrated
// * Created by progr1mmer on 2018/1/27.
// */
//public class EhrWebAuthenticationToken extends UsernamePasswordAuthenticationToken {
//
//    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
//
//    // ~ Instance fields
//    // ================================================================================================
//
//    private final Object principal;
//    private Object credentials;
//    private boolean isSso;
//
//    // ~ 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 EhrWebAuthenticationToken(Object principal, Object credentials, boolean isSso) {
//        super(principal, credentials);
//        this.principal = principal;
//        this.credentials = credentials;
//        this.isSso = isSso;
//        setAuthenticated(false);
//    }
//
//    public boolean isSso() {
//        return this.isSso;
//    }
//
//    @Override
//    public Object getPrincipal() {
//        return principal;
//    }
//
//    @Override
//    public Object getCredentials() {
//        return credentials;
//    }
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationToken.java

+ 50 - 0
app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUserDetails.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUserDetails.java
package com.yihu.iot.security.core;
import org.springframework.security.core.GrantedAuthority;
@ -45,3 +46,52 @@ public class EhrWebUserDetails implements UserDetails {
        return false;
    }
}
=======
//package com.yihu.ehr.iot.security.core;
//
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.userdetails.UserDetails;
//
//import java.util.Collection;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebUserDetails implements UserDetails {
//
//    @Override
//    public Collection<? extends GrantedAuthority> getAuthorities() {
//        return null;
//    }
//
//    @Override
//    public boolean isEnabled() {
//        return false;
//    }
//
//    @Override
//    public boolean isCredentialsNonExpired() {
//        return false;
//    }
//
//    @Override
//    public String getPassword() {
//        return null;
//    }
//
//    @Override
//    public String getUsername() {
//        return null;
//    }
//
//    @Override
//    public boolean isAccountNonExpired() {
//        return false;
//    }
//
//    @Override
//    public boolean isAccountNonLocked() {
//        return false;
//    }
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebUserDetails.java

+ 88 - 0
app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUserDetailsService.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUserDetailsService.java
package com.yihu.iot.security.core;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -82,3 +83,90 @@ public class EhrWebUserDetailsService implements UserDetailsService {
    }
}
=======
//package com.yihu.ehr.iot.security.core;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.agModel.user.UserDetailModel;
//import com.yihu.ehr.iot.util.http.HttpHelper;
//import com.yihu.ehr.iot.util.http.HttpResponse;
//import com.yihu.ehr.iot.yanshi.dao.UserDao;
//import com.yihu.ehr.util.rest.Envelop;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.authority.SimpleGrantedAuthority;
//import org.springframework.security.core.session.SessionRegistry;
//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.session.FindByIndexNameSessionRepository;
//import org.springframework.util.Assert;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//
//import javax.servlet.http.HttpServletRequest;
//import java.util.ArrayList;
//import java.util.Collection;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebUserDetailsService implements UserDetailsService {
//
//    private final Logger logger = LoggerFactory.getLogger(this.getClass());
//
//    private final ObjectMapper objectMapper = new ObjectMapper();
//
//    private final String profileInnerUrl;
//    private UserDao userDao;
//
//    public EhrWebUserDetailsService(String profileInnerUrl, UserDao userDao) {
//        Assert.hasText(profileInnerUrl, "ProfileInnerUrl must not be empty or null");
//        this.profileInnerUrl = profileInnerUrl;
//        this.userDao = userDao;
//    }
//
//    /**
//     * Step 2
//     *
//     * @param username
//     * @return
//     * @throws UsernameNotFoundException
//     */
//    @Override
//    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        try {
//            Map<String, Object> params = new HashMap<>();
//            params.put("login_code", username);
//            com.yihu.ehr.iot.yanshi.model.User userObj = userDao.findByMobile(username);
//            if(userObj==null){
//                throw  new UsernameNotFoundException("用户不存在");
//            }
//            String password = userObj.getPassword();
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            //登陆成功后需要的属性
//            request.setAttribute("id", userObj.getCode());
//            request.setAttribute("username", userObj.getMobile());
//            request.setAttribute("realName", userObj.getName());
//            request.setAttribute("user", userObj);
//            return new User(username, password, getGrantedAuthorities(username));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        throw new UsernameNotFoundException(username);
//    }
//
//    private Collection<GrantedAuthority> getGrantedAuthorities(String username) {
//        Collection<GrantedAuthority> authorities = new ArrayList<>(1);
//        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
//        return authorities;
//    }
//
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebUserDetailsService.java

+ 180 - 0
app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUsernamePasswordAuthenticationFilter.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/app-iot-server/src/main/java/com/yihu/iot/security/core/EhrWebUsernamePasswordAuthenticationFilter.java
package com.yihu.iot.security.core;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -175,3 +176,182 @@ public class EhrWebUsernamePasswordAuthenticationFilter extends AbstractAuthenti
    }
}
=======
//package com.yihu.ehr.iot.security.core;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.agModel.user.UserDetailModel;
//import com.yihu.ehr.iot.util.http.HttpHelper;
//import com.yihu.ehr.iot.util.http.HttpResponse;
//import com.yihu.ehr.util.rest.Envelop;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.security.authentication.AuthenticationServiceException;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//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;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * Sso integrated
// * Created by progr1mmer on 2018/1/27.
// */
//public class EhrWebUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
//
//    private static Logger logger = LoggerFactory.getLogger(EhrWebUsernamePasswordAuthenticationFilter.class);
//
//    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
//    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
//    private ObjectMapper objectMapper = new ObjectMapper();
//    private String usernameParameter = "username";
//    private String passwordParameter = "password";
//    private String clientIdParameter = "clientId";
//    private String accessTokenParameter = "accessToken";
//    private boolean postOnly = true;
//
//    private final String oauth2InnerUrl;
//    private final String profileInnerUrl;
//
//    public EhrWebUsernamePasswordAuthenticationFilter(String oauth2InnerUrl, String profileInnerUrl) {
//        super(new AntPathRequestMatcher("/login", "POST"));
//        Assert.hasText(oauth2InnerUrl, "Oauth2InnerUrl must not be empty or null");
//        Assert.hasText(profileInnerUrl, "ProfileInnerUrl must not be empty or null");
//        this.oauth2InnerUrl = oauth2InnerUrl;
//        this.profileInnerUrl = profileInnerUrl;
//    }
//
//    /**
//     * Step 1
//     * @param request
//     * @param response
//     * @return
//     * @throws AuthenticationException
//     */
//    @Override
//    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
//        if(this.postOnly && !request.getMethod().equals("POST")) {
//            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
//        } else {
//            String username = null;
//            String password = null;
//            if(isSso(request)) {
//                Map<String, Object> params = new HashMap<>();
//                params.put("clientId", this.obtainClientId(request));
//                params.put("accessToken", this.obtainAccessToken(request));
//                try {
//                    HttpResponse httpResponse = HttpHelper.post(oauth2InnerUrl + "/oauth/validToken", params);
//                    if(httpResponse.getStatusCode() == 200) {
//                        Map<String, Object> map = objectMapper.readValue(httpResponse.getBody(), Map.class);
//                        String loginName = (String) map.get("user");
//                        //验证通过。赋值session中的用户信息
//                        params.clear();
//                        params.put("login_code", loginName);
//                        httpResponse = HttpHelper.get(profileInnerUrl + "/users/" + loginName, params);
//                        Envelop envelop = this.objectMapper.readValue(httpResponse.getBody(), Envelop.class);
//                        String user = this.objectMapper.writeValueAsString(envelop.getObj());
//                        UserDetailModel userDetailModel = this.objectMapper.readValue(user, UserDetailModel.class);
//                        username = userDetailModel.getLoginCode();
//                        password = userDetailModel.getPassword();
//                    }else {
//                        logger.error(httpResponse.getBody());
//                    }
//                }catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }else {
//                username = this.obtainUsername(request);
//                password = this.obtainPassword(request);
//            }
//
//            if(username == null) {
//                username = "";
//            }
//            if(password == null) {
//                password = "";
//            }
//
//            username = username.trim();
//            UsernamePasswordAuthenticationToken authRequest = new EhrWebAuthenticationToken(username, password, isSso(request)); //单点登陆集成
//
//            this.setDetails(request, authRequest);
//            return this.getAuthenticationManager().authenticate(authRequest);
//        }
//    }
//
//    //单点登陆集成 ------------ Start -------------
//    protected String obtainClientId(HttpServletRequest request) {
//        return request.getParameter(this.clientIdParameter);
//    }
//
//    protected String obtainAccessToken(HttpServletRequest request) {
//        return request.getParameter(this.accessTokenParameter);
//    }
//    //单点登陆集成 ------------ End -------------
//
//    protected String obtainPassword(HttpServletRequest request) {
//        return request.getParameter(this.passwordParameter);
//    }
//
//    protected String obtainUsername(HttpServletRequest request) {
//        return request.getParameter(this.usernameParameter);
//    }
//
//    public void setPostOnly(boolean postOnly) {
//        this.postOnly = postOnly;
//    }
//
//    protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
//        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
//    }
//
//    //单点登陆集成 ------------ Start -------------
//    public void setClientIdParameter(String clientIdParameter) {
//        Assert.hasText(clientIdParameter, "ClientId parameter must not be empty or null");
//        this.clientIdParameter = clientIdParameter;
//    }
//
//    public void setAccessTokenParameter(String accessTokenParameter) {
//        Assert.hasText(accessTokenParameter, "AccessTokenParameter parameter must not be empty or null");
//        this.accessTokenParameter = accessTokenParameter;
//    }
//    //单点登陆集成 ------------ End -------------
//
//    public void setUsernameParameter(String usernameParameter) {
//        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
//        this.usernameParameter = usernameParameter;
//    }
//
//    public void setPasswordParameter(String passwordParameter) {
//        Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
//        this.passwordParameter = passwordParameter;
//    }
//
//    public final String getClientIdParameter() {
//        return this.clientIdParameter;
//    }
//
//    public final String getAccessTokenParameter() {
//        return this.accessTokenParameter;
//    }
//
//    public final String getUsernameParameter() {
//        return this.usernameParameter;
//    }
//
//    public final String getPasswordParameter() {
//        return this.passwordParameter;
//    }
//
//    private boolean isSso(HttpServletRequest request){
//        return null != request.getParameter(accessTokenParameter);
//    }
//
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebUsernamePasswordAuthenticationFilter.java

+ 39 - 0
app/app-iot-server/src/main/java/com/yihu/iot/security/entryPoint/LoginEntryPoint.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/app-iot-server/src/main/java/com/yihu/iot/security/entryPoint/LoginEntryPoint.java
package com.yihu.iot.security.entryPoint;
import com.alibaba.fastjson.JSONObject;
@ -34,3 +35,41 @@ public class LoginEntryPoint extends LoginUrlAuthenticationEntryPoint {
}
=======
//package com.yihu.ehr.iot.security.entryPoint;
//
//import com.alibaba.fastjson.JSONObject;
//import org.springframework.security.core.AuthenticationException;
//import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//
///**
// * @author yeshijie on 2018/3/9.
// */
//public class LoginEntryPoint extends LoginUrlAuthenticationEntryPoint {
//
//
//    public LoginEntryPoint(String loginFormUrl) {
//        super(loginFormUrl);
//    }
//
//    @Override
//    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//        JSONObject json = new JSONObject();
//        json.put("status",998);
//        json.put("errorMsg","未登录或,登录超时");
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json");
//        response.getWriter().println(json.toString());
//        response.getWriter().flush();
//
////        super.commence(request, response, authException);
//    }
//
//
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/entryPoint/LoginEntryPoint.java

+ 20 - 22
app/app-iot-server/src/main/java/com/yihu/iot/service/common/BaseService.java

@ -17,8 +17,6 @@ import com.yihu.ehr.util.rest.Envelop;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@ -57,8 +55,8 @@ public class BaseService {
    protected String oauth2InnerUrl;
    @Value("${app.oauth2OuterUrl}")
    protected String oauth2OuterUrl;
    @Autowired
    protected SessionRegistry sessionRegistry;
//    @Autowired
//    protected SessionRegistry sessionRegistry;
    @Autowired
    protected HttpServletRequest request;
@ -66,29 +64,29 @@ public class BaseService {
     * 获取当前登录用户,当前已登录的用户都缓存在session中
     * @return
     */
    public JSONObject getCurrentUser(){
        JSONObject json = new JSONObject();
        String sessionId = request.getSession().getId();
        UserDetailModel user = null;
        SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId);
        if(null != sessionInformation.getPrincipal()){
            user = (UserDetailModel)sessionInformation.getPrincipal();
            json.put("id",user.getId());
            json.put("code",user.getLoginCode());
            json.put("name",user.getRealName());
        }
        return json;
    }
//    public JSONObject getCurrentUser(){
//        JSONObject json = new JSONObject();
//        String sessionId = request.getSession().getId();
//        UserDetailModel user = null;
//        SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId);
//        if(null != sessionInformation.getPrincipal()){
//            user = (UserDetailModel)sessionInformation.getPrincipal();
//            json.put("id",user.getId());
//            json.put("code",user.getLoginCode());
//            json.put("name",user.getRealName());
//        }
//        return json;
//    }
    /**
     * 获取登录信息
     * @return
     */
    public Map<String,Object> getLoginHeader(){
        Map<String, Object> header = new HashMap<>();
        header.put("User-Agent",getCurrentUser());
        return header;
    }
//    public Map<String,Object> getLoginHeader(){
//        Map<String, Object> header = new HashMap<>();
//        header.put("User-Agent",getCurrentUser());
//        return header;
//    }
    public String readFile(String filePath, String charSet) {

+ 238 - 171
app/app-iot-server/src/main/java/com/yihu/iot/service/common/LoginService.java

@ -1,9 +1,11 @@
package com.yihu.iot.service.common;
import com.alibaba.fastjson.JSONObject;
import com.yihu.ehr.agModel.user.RoleOrgModel;
import com.yihu.ehr.agModel.user.UserDetailModel;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.ehr.constants.SessionAttributeKeys;
import com.yihu.ehr.iot.yanshi.dao.UserDao;
import com.yihu.ehr.iot.yanshi.model.User;
import com.yihu.ehr.model.geography.MGeographyDict;
import com.yihu.ehr.model.org.MOrganization;
import com.yihu.ehr.model.resource.MRsRolesResource;
@ -16,15 +18,10 @@ import com.yihu.iot.model.ObjectResult;
import com.yihu.iot.model.Result;
import com.yihu.ehr.util.log.LogService;
import com.yihu.ehr.util.rest.Envelop;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import com.yihu.jw.util.security.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@ -32,6 +29,7 @@ import java.util.*;
/**
 * Service - 登陆
 *
 * @author Progr1mmer
 */
@Service
@ -64,26 +62,26 @@ public class LoginService extends BaseService {
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if(ip != null) {
            if("0:0:0:0:0:0:0:1".equals(ip)) {
        if (ip != null) {
            if ("0:0:0:0:0:0:0:1".equals(ip)) {
                request.getSession().setAttribute("isInnerIp", true);
            }else {
                if("127.0.0.1".equals(ip) || isInnerIP(ip)) {
            } else {
                if ("127.0.0.1".equals(ip) || isInnerIP(ip)) {
                    request.getSession().setAttribute("isInnerIp", true);
                }else {
                } else {
                    request.getSession().setAttribute("isInnerIp", false);
                }
            }
        }
    }
    public boolean isInnerIP(String ip){
    public boolean isInnerIP(String ip) {
        long n = getIpNum(ip);
        return (n >= a1 && n <= a2) || (n >= b1 && n <= b2) || (n >= c1 && n <= c2) || (n >= d1 && n <= d2);
    }
    public long getIpNum(String ipAddress) {
        String [] ip = ipAddress.split("\\.");
        String[] ip = ipAddress.split("\\.");
        long a = Integer.parseInt(ip[0]);
        long b = Integer.parseInt(ip[1]);
        long c = Integer.parseInt(ip[2]);
@ -93,8 +91,74 @@ public class LoginService extends BaseService {
    //------------------------ 初始化内外网IP end ------------------------
    //==============================演示用 以后删除 start============================
    @Autowired
    private UserDao userDao;
    public Result loginyanshi(HttpServletRequest request, String userName, String password) {
        try {
            ObjectResult result = new ObjectResult();
//            Map<String, Object> params = new HashMap<>();
//            params.put("userName", userName);
//            params.put("password", password);
//            params.put("clientId", clientId);
//            HttpResponse response = HttpHelper.get(portalInnerUrl + "/oauth/login", params);
            User user = userDao.findByMobile(userName);
            if (user == null) {
                return Result.error("用户名不存在");
            }
            String dbPassword = MD5.GetMD5Code(password + user.getSalt());
            if (!dbPassword.equals(user.getPassword())) {
                return Result.error("密码错误");
            }
            Map userMap = new HashMap<>();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", user.getCode());
            jsonObject.put("username", user.getMobile());
            jsonObject.put("realname", user.getName());
            userMap.put("user", jsonObject);
            result.setData(userMap);
            String userId = user.getCode();
            //获取token
            initUrlInfo(request);
            AccessToken token = new AccessToken();
            token.setAccessToken(UUID.randomUUID().toString().replace("-", ""));
            token.setExpiresIn(999999999);
            token.setRefreshToken(UUID.randomUUID().toString().replace("-", ""));
            JSONObject obj = new JSONObject();
            obj.put("id", user.getCode());
            obj.put("token",token.getAccessToken());
            result.setObj(obj);
            request.getSession().setAttribute("isLogin", true);
            request.getSession().setAttribute("token", token);
            request.getSession().setAttribute("loginName", userName);
            request.getSession().setAttribute("userId", userId);
            result.setSuccessFlg(true);
            result.setMessage("登录成功");
            result.setCode(200);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    //==============================演示用 以后删除 end============================
    /**
     * 用户名密码登录
     *
     * @param request
     * @param userName
     * @param password
@ -110,9 +174,9 @@ public class LoginService extends BaseService {
            HttpResponse response = HttpHelper.get(portalInnerUrl + "/oauth/login", params);
            if (response != null && response.getStatusCode() == 200) {
                ObjectResult re = toModel(response.getBody(), ObjectResult.class);
                if (re.isSuccessFlg()){
                if (re.isSuccessFlg()) {
                    Map userMap = new HashMap<>();
                    userMap.put("user",re.getData());
                    userMap.put("user", re.getData());
                    result.setData(userMap);
                    String userId = ((LinkedHashMap) re.getData()).get("id").toString();
                    //获取token
@ -120,7 +184,7 @@ public class LoginService extends BaseService {
                    if (tokenResponse.isSuccessFlg()) {
                        initUrlInfo(request);
                        String data = objectMapper.writeValueAsString(((ObjectResult) tokenResponse).getData());
                        AccessToken token = objectMapper.readValue(data,AccessToken.class);
                        AccessToken token = objectMapper.readValue(data, AccessToken.class);
                        request.getSession().setAttribute("isLogin", true);
                        request.getSession().setAttribute("token", token);
                        request.getSession().setAttribute("loginName", userName);
@ -129,12 +193,10 @@ public class LoginService extends BaseService {
                        result.setMessage("登录成功");
                        result.setCode(200);
                        return result;
                    }
                    else{
                    } else {
                        return tokenResponse;
                    }
                }
                else {
                } else {
                    return re;
                }
            } else {
@ -146,72 +208,74 @@ public class LoginService extends BaseService {
        }
    }
    /**
     * 自动登录
     * @param request
     * @param model
     * @param token
     * @return
     * @throws Exception
     */
    public Envelop autoLogin(HttpServletRequest request, Model model, @RequestParam String token) throws Exception {
        try {
            String clientId = request.getParameter("clientId").toString();
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", clientId);
            params.put("accessToken", token);
            HttpResponse response = HttpHelper.post(oauth2InnerUrl + "/oauth/validToken", params);
            Map<String, Object> map = objectMapper.readValue(response.getBody(), Map.class);
            if ((Boolean) map.get("successFlg")) {
                AccessToken accessToken = objectMapper.readValue(objectMapper.writeValueAsString(map.get("data")), AccessToken.class);
                String loginName = accessToken.getUser();
                //验证通过。赋值session中的用户信息
                response = HttpHelper.get(profileInnerUrl + "/users/" + loginName, params);
                Envelop envelop = (Envelop) this.objectMapper.readValue(response.getBody(), Envelop.class);
                String ex = this.objectMapper.writeValueAsString(envelop.getObj());
                UserDetailModel userDetailModel = this.objectMapper.readValue(ex, UserDetailModel.class);
                //获取用户的角色,机构,视图 等权限
                getUserRolePermissions(userDetailModel, loginName, request);
                // 注:SessionAttributeKeys.CurrentUser 是用 @SessionAttributes 来最终赋值,换成用 session.setAttribute() 赋值后将会被覆盖。
                model.addAttribute(SessionAttributeKeys.CurrentUser, userDetailModel);
                HttpSession session = request.getSession();
                //增加超级管理员信息
                if(loginName.equals(permissionsInfo)) {
                    session.setAttribute(AuthorityKey.IsAccessAll, true);
                }else {
                    session.setAttribute(AuthorityKey.IsAccessAll, false);
                }
                session.setAttribute("isLogin", true);
                session.setAttribute("token", accessToken);
                session.setAttribute("loginName", loginName);
                session.setAttribute("userId", userDetailModel.getId());
                session.setAttribute("clientId", clientId);
                //获取用户角色信息
                List<Map<String, Object>> features = getUserFeatures(userDetailModel.getId());
                Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                if (features != null) {
                    for (Map<String, Object> temp : features) {
                        if (temp.get("url") != null && !StringUtils.isEmpty(temp.get("url").toString())){
                            grantedAuthorities.add(new SimpleGrantedAuthority(temp.get("url").toString()));
                        }
                    }
                }
                //生成认证token
                Authentication AuthenticationToken = new UsernamePasswordAuthenticationToken(loginName, "", grantedAuthorities);
                //将信息存放到SecurityContext
                SecurityContextHolder.getContext().setAuthentication(AuthenticationToken);
                return success(userDetailModel);
            } else {
                String msg = String.valueOf(map.get("message"));
                return failed(msg);
            }
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
//    /**
//     * 自动登录
//     *
//     * @param request
//     * @param model
//     * @param token
//     * @return
//     * @throws Exception
//     */
//    public Envelop autoLogin(HttpServletRequest request, Model model, @RequestParam String token) throws Exception {
//        try {
//            String clientId = request.getParameter("clientId").toString();
//            Map<String, Object> params = new HashMap<>();
//            params.put("clientId", clientId);
//            params.put("accessToken", token);
//            HttpResponse response = HttpHelper.post(oauth2InnerUrl + "/oauth/validToken", params);
//            Map<String, Object> map = objectMapper.readValue(response.getBody(), Map.class);
//            if ((Boolean) map.get("successFlg")) {
//                AccessToken accessToken = objectMapper.readValue(objectMapper.writeValueAsString(map.get("data")), AccessToken.class);
//                String loginName = accessToken.getUser();
//                //验证通过。赋值session中的用户信息
//                response = HttpHelper.get(profileInnerUrl + "/users/" + loginName, params);
//                Envelop envelop = (Envelop) this.objectMapper.readValue(response.getBody(), Envelop.class);
//                String ex = this.objectMapper.writeValueAsString(envelop.getObj());
//                UserDetailModel userDetailModel = this.objectMapper.readValue(ex, UserDetailModel.class);
//                //获取用户的角色,机构,视图 等权限
//                getUserRolePermissions(userDetailModel, loginName, request);
//                // 注:SessionAttributeKeys.CurrentUser 是用 @SessionAttributes 来最终赋值,换成用 session.setAttribute() 赋值后将会被覆盖。
//                model.addAttribute(SessionAttributeKeys.CurrentUser, userDetailModel);
//                HttpSession session = request.getSession();
//                //增加超级管理员信息
//                if (loginName.equals(permissionsInfo)) {
//                    session.setAttribute(AuthorityKey.IsAccessAll, true);
//                } else {
//                    session.setAttribute(AuthorityKey.IsAccessAll, false);
//                }
//                session.setAttribute("isLogin", true);
//                session.setAttribute("token", accessToken);
//                session.setAttribute("loginName", loginName);
//                session.setAttribute("userId", userDetailModel.getId());
//                session.setAttribute("clientId", clientId);
//                //获取用户角色信息
//                List<Map<String, Object>> features = getUserFeatures(userDetailModel.getId());
//                Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//                if (features != null) {
//                    for (Map<String, Object> temp : features) {
//                        if (temp.get("url") != null && !StringUtils.isEmpty(temp.get("url").toString())) {
//                            grantedAuthorities.add(new SimpleGrantedAuthority(temp.get("url").toString()));
//                        }
//                    }
//                }
//                //生成认证token
//                Authentication AuthenticationToken = new UsernamePasswordAuthenticationToken(loginName, "", grantedAuthorities);
//                //将信息存放到SecurityContext
//                SecurityContextHolder.getContext().setAuthentication(AuthenticationToken);
//                return success(userDetailModel);
//            } else {
//                String msg = String.valueOf(map.get("message"));
//                return failed(msg);
//            }
//        } catch (Exception e) {
//            return failed(e.getMessage());
//        }
//    }
    /**
     * 通过用户名密码获取token
     *
     * @param userName
     * @param password
     * @param clientId
@ -225,10 +289,9 @@ public class LoginService extends BaseService {
            params.put("clientId", clientId);
            HttpResponse response = HttpHelper.post(oauth2InnerUrl + "oauth/accessToken", params);
            if (response != null && response.getStatusCode() == 200) {
                return toModel(response.getBody(),ObjectResult.class);
            }
            else {
                return Result.error(response.getStatusCode(),response.getBody());
                return toModel(response.getBody(), ObjectResult.class);
            } else {
                return Result.error(response.getStatusCode(), response.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
@ -238,6 +301,7 @@ public class LoginService extends BaseService {
    /**
     * 刷新token
     *
     * @param refreshToken
     * @param clientId
     * @return
@ -248,11 +312,10 @@ public class LoginService extends BaseService {
            params.put("refreshToken", refreshToken);
            params.put("clientId", clientId);
            HttpResponse response = HttpHelper.post(oauth2InnerUrl + "oauth/refreshToken", params);
            if (response!=null && response.getStatusCode() == 200) {
                return toModel(response.getBody(),ObjectResult.class);
            }
            else {
                return Result.error(response.getStatusCode(),response.getBody());
            if (response != null && response.getStatusCode() == 200) {
                return toModel(response.getBody(), ObjectResult.class);
            } else {
                return Result.error(response.getStatusCode(), response.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
@ -262,6 +325,7 @@ public class LoginService extends BaseService {
    /**
     * 校验token
     *
     * @param clientId
     * @param accessToken
     * @return
@ -273,10 +337,9 @@ public class LoginService extends BaseService {
            params.put("accessToken", accessToken);
            HttpResponse response = HttpHelper.post(oauth2InnerUrl + "oauth/validToken", params);
            if (response != null && response.getStatusCode() == 200) {
                return toModel(response.getBody(),ObjectResult.class);
            }
            else {
                return Result.error(response.getStatusCode(),response.getBody());
                return toModel(response.getBody(), ObjectResult.class);
            } else {
                return Result.error(response.getStatusCode(), response.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
@ -287,53 +350,54 @@ public class LoginService extends BaseService {
    /**
     * 获取用户的角色,机构,视图 等权限
     *
     * @param userDetailModel
     * @param request
     * @throws Exception
     */
    public void getUserRolePermissions(UserDetailModel userDetailModel, String loginCode, HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        if(loginCode.equals(permissionsInfo)){
        if (loginCode.equals(permissionsInfo)) {
            session.setAttribute(AuthorityKey.UserRoles, null);
            session.setAttribute(AuthorityKey.UserResource, null);
            session.setAttribute(AuthorityKey.UserAreaSaas, null);
            session.setAttribute(AuthorityKey.UserOrgSaas, null);
        }else{
        } else {
            //获取用户角色
            String roleStr = "";
            List<String> roleList = new ArrayList<>();
            roleStr =  gerUserRoles(userDetailModel.getId());
            if( !StringUtils.isEmpty(roleStr)){
                roleList =  Arrays.asList(roleStr.split(","));
            roleStr = gerUserRoles(userDetailModel.getId());
            if (!StringUtils.isEmpty(roleStr)) {
                roleList = Arrays.asList(roleStr.split(","));
                session.setAttribute(AuthorityKey.UserRoles, roleList);
                //获取角色机构
                List<RoleOrgModel> roleOrgModels = new ArrayList<>();
                gerRolesOrgs(roleList,roleOrgModels);
                if(roleOrgModels !=null && roleOrgModels.size() >0){
                gerRolesOrgs(roleList, roleOrgModels);
                if (roleOrgModels != null && roleOrgModels.size() > 0) {
                    List<String> roleOrgCodes = new ArrayList<>();
                    for(RoleOrgModel roleOrgModel : roleOrgModels){
                    for (RoleOrgModel roleOrgModel : roleOrgModels) {
                        roleOrgCodes.add(roleOrgModel.getOrgCode());
                    }
                    getUserSaasOrgAndArea(roleOrgCodes, request);
                }else{
                } else {
                    List<String> userOrgList = new ArrayList<>();
                    userOrgList.add("-NoneOrg");
                    session.setAttribute(AuthorityKey.UserOrgSaas, userOrgList);
                }
                //获取角色视图
                List<String> rolesResourceIdList =  new ArrayList<>();
                List<String> rolesResourceIdList = new ArrayList<>();
                List<MRsRolesResource> rolesResourceList = new ArrayList<>();
                gerRolesResource(roleList, rolesResourceList);
                if(rolesResourceList !=null && rolesResourceList.size() >0){
                    for(MRsRolesResource rsRolesResource : rolesResourceList){
                if (rolesResourceList != null && rolesResourceList.size() > 0) {
                    for (MRsRolesResource rsRolesResource : rolesResourceList) {
                        rolesResourceIdList.add(rsRolesResource.getResourceId());
                    }
                    session.setAttribute(AuthorityKey.UserResource, rolesResourceIdList);
                }else{
                } else {
                    rolesResourceIdList.add("-NoneResource");
                    session.setAttribute(AuthorityKey.UserResource, rolesResourceIdList);
                }
            }else{
            } else {
                roleList.add("-NoneRole");
                session.setAttribute(AuthorityKey.UserRoles, roleList);
            }
@ -342,43 +406,45 @@ public class LoginService extends BaseService {
    /**
     * 获取用户角色
     *
     * @param userId
     * @return
     */
    public String gerUserRoles(String userId){
    public String gerUserRoles(String userId) {
        //获取用户所属角色
        String roleStr = "";
        try {
            String url = "/roles/role_user/userRolesIds";
            Map<String,Object> params = new HashMap<>();
            params.put("user_id",userId);
            HttpResponse response = HttpHelper.get(profileInnerUrl + url,params);
            Envelop envelop = objectMapper.readValue(response.getBody(),Envelop.class);
            Map<String, Object> params = new HashMap<>();
            params.put("user_id", userId);
            HttpResponse response = HttpHelper.get(profileInnerUrl + url, params);
            Envelop envelop = objectMapper.readValue(response.getBody(), Envelop.class);
            if (envelop.isSuccessFlg() && null != envelop.getObj() && !"".equals(envelop.getObj())) {
                roleStr = envelop.getObj().toString();
            }
        } catch (Exception ex) {
            LogService.getLogger(LoginService.class).error(ex.getMessage());
        }
        return  roleStr;
        return roleStr;
    }
    /**
     * 获取角色机构
     *
     * @param roleList 角色组列表
     * @return
     */
    public List<RoleOrgModel> gerRolesOrgs(List<String> roleList,List<RoleOrgModel> roleOrgs){
        for(String roleId : roleList){
    public List<RoleOrgModel> gerRolesOrgs(List<String> roleList, List<RoleOrgModel> roleOrgs) {
        for (String roleId : roleList) {
            try {
                Map<String,Object> params = new HashMap<>();
                String roleUrl = "/roles/role/"+roleId;
                params.put("id",Long.valueOf(roleId));
                HttpResponse response = HttpHelper.get(profileInnerUrl + roleUrl,params);
                Envelop envelopRole = objectMapper.readValue(response.getBody(),Envelop.class);
                if(envelopRole.getObj() != null){
                Map<String, Object> params = new HashMap<>();
                String roleUrl = "/roles/role/" + roleId;
                params.put("id", Long.valueOf(roleId));
                HttpResponse response = HttpHelper.get(profileInnerUrl + roleUrl, params);
                Envelop envelopRole = objectMapper.readValue(response.getBody(), Envelop.class);
                if (envelopRole.getObj() != null) {
                    MRoles mRoles = objectMapper.convertValue(envelopRole.getObj(), MRoles.class);
                    if ( ! StringUtils.isEmpty( mRoles.getOrgCode() )){
                    if (!StringUtils.isEmpty(mRoles.getOrgCode())) {
                        RoleOrgModel roleOrgModel = new RoleOrgModel();
                        roleOrgModel.setOrgCode(mRoles.getOrgCode());
                        roleOrgModel.setRoleId(mRoles.getId());
@ -387,14 +453,14 @@ public class LoginService extends BaseService {
                }
                String url = ServiceApi.Roles.RoleOrgsNoPage;
                params.clear();
                params.put("filters","roleId=" + roleId);
                response = HttpHelper.get(profileInnerUrl + url,params);
                Envelop envelop = objectMapper.readValue(response.getBody(),Envelop.class);
                if (envelop.isSuccessFlg() && null != envelop.getDetailModelList() &&  envelop.getDetailModelList().size()>0) {
                params.put("filters", "roleId=" + roleId);
                response = HttpHelper.get(profileInnerUrl + url, params);
                Envelop envelop = objectMapper.readValue(response.getBody(), Envelop.class);
                if (envelop.isSuccessFlg() && null != envelop.getDetailModelList() && envelop.getDetailModelList().size() > 0) {
                    List<RoleOrgModel> roleOrgModels = envelop.getDetailModelList();
                    if(roleOrgModels != null && roleOrgModels.size() > 0){
                        for(int i = 0; i < roleOrgModels.size() ;i++){
                            RoleOrgModel orgModel = objectMapper.convertValue(roleOrgModels.get(i), RoleOrgModel.class) ;
                    if (roleOrgModels != null && roleOrgModels.size() > 0) {
                        for (int i = 0; i < roleOrgModels.size(); i++) {
                            RoleOrgModel orgModel = objectMapper.convertValue(roleOrgModels.get(i), RoleOrgModel.class);
                            roleOrgs.add(orgModel);
                        }
                    }
@ -403,7 +469,7 @@ public class LoginService extends BaseService {
                LogService.getLogger(LoginService.class).error(ex.getMessage());
            }
        }
        return  roleOrgs;
        return roleOrgs;
    }
    /**
@ -412,53 +478,53 @@ public class LoginService extends BaseService {
    public void getUserSaasOrgAndArea(List<String> roleOrgCodes, HttpServletRequest request) throws Exception {
        Envelop envelop = new Envelop();
        List<String> userOrgList = new ArrayList<>();
        for(String code : roleOrgCodes){
        for (String code : roleOrgCodes) {
            userOrgList.add(code);
        }
        //使用orgCode获取saas化的机构或者区域。
        String urlUOrg = "/org/getUserOrgSaasByUserOrgCode/";
        Map<String, Object> uParams = new HashMap<>();
        uParams.put("orgCodeStr",org.apache.commons.lang.StringUtils.join(roleOrgCodes,',') );
        uParams.put("orgCodeStr", org.apache.commons.lang.StringUtils.join(roleOrgCodes, ','));
        HttpResponse response = HttpHelper.get(profileInnerUrl + urlUOrg, uParams);
        envelop = objectMapper.readValue(response.getBody(),Envelop.class);
        envelop = objectMapper.readValue(response.getBody(), Envelop.class);
        HttpSession session = request.getSession();
        session.setAttribute("userAreaSaas", envelop.getObj());
        session.setAttribute("userOrgSaas", envelop.getDetailModelList());
        userOrgList = envelop.getDetailModelList();
        List<String> districtList = (List<String>) envelop.getObj();
        String geographyUrl = "/geography_entries/";
        if(districtList != null && districtList.size() > 0){
            for(String code : districtList){
        if (districtList != null && districtList.size() > 0) {
            for (String code : districtList) {
                uParams.clear();
                response = HttpHelper.get(profileInnerUrl + geographyUrl + code, uParams);
                envelop = objectMapper.readValue(response.getBody(),Envelop.class);
                envelop = objectMapper.readValue(response.getBody(), Envelop.class);
                MGeographyDict mGeographyDict = null;
                String objJsonData = objectMapper.writeValueAsString(envelop.getObj());
                mGeographyDict = objectMapper.readValue(objJsonData, MGeographyDict.class);
                if(mGeographyDict != null){
                if (mGeographyDict != null) {
                    String province = "";
                    String city = "";
                    String district = "";
                    if(mGeographyDict.getLevel() == 1){
                        province =  mGeographyDict.getName();
                    }else if(mGeographyDict.getLevel() == 2){
                        city =  mGeographyDict.getName();
                    }else if(mGeographyDict.getLevel() == 3){
                        district =  mGeographyDict.getName();
                    if (mGeographyDict.getLevel() == 1) {
                        province = mGeographyDict.getName();
                    } else if (mGeographyDict.getLevel() == 2) {
                        city = mGeographyDict.getName();
                    } else if (mGeographyDict.getLevel() == 3) {
                        district = mGeographyDict.getName();
                    }
                    String  orgGeographyStr = "/organizations/geography";
                    String orgGeographyStr = "/organizations/geography";
                    uParams.clear();
                    uParams.put("province",province);
                    uParams.put("city",city);
                    uParams.put("district",district);
                    response = HttpHelper.get(profileInnerUrl + orgGeographyStr , uParams);
                    envelop = objectMapper.readValue(response.getBody(),Envelop.class);
                    if(envelop !=null && envelop.getDetailModelList() != null ){
                        List<MOrganization> organizations = (List<MOrganization>)getEnvelopList(envelop.getDetailModelList(),new ArrayList<MOrganization>(),MOrganization.class);
                        if(organizations !=null ){
                    uParams.put("province", province);
                    uParams.put("city", city);
                    uParams.put("district", district);
                    response = HttpHelper.get(profileInnerUrl + orgGeographyStr, uParams);
                    envelop = objectMapper.readValue(response.getBody(), Envelop.class);
                    if (envelop != null && envelop.getDetailModelList() != null) {
                        List<MOrganization> organizations = (List<MOrganization>) getEnvelopList(envelop.getDetailModelList(), new ArrayList<MOrganization>(), MOrganization.class);
                        if (organizations != null) {
                            java.util.Iterator it = organizations.iterator();
                            while(it.hasNext()){
                                MOrganization mOrganization = (MOrganization)it.next();
                            while (it.hasNext()) {
                                MOrganization mOrganization = (MOrganization) it.next();
                                userOrgList.add(mOrganization.getCode());
                            }
                        }
@ -473,23 +539,24 @@ public class LoginService extends BaseService {
    /**
     * 获取角色视图列表
     *
     * @param roleList
     * @param rolesResourceList
     * @return
     */
    public List<MRsRolesResource> gerRolesResource(List<String> roleList,List<MRsRolesResource> rolesResourceList){
        for(String roleId : roleList){
    public List<MRsRolesResource> gerRolesResource(List<String> roleList, List<MRsRolesResource> rolesResourceList) {
        for (String roleId : roleList) {
            try {
                String url = ServiceApi.Resources.GetRolesGrantResources;
                Map<String,Object> params = new HashMap<>();
                params.put("rolesId",roleId);
                HttpResponse response = HttpHelper.get(profileInnerUrl + url,params);
                Envelop envelop = objectMapper.readValue(response.getBody(),Envelop.class);
                if (envelop.isSuccessFlg() && null != envelop.getDetailModelList() && envelop.getDetailModelList().size() > 0 ) {
                Map<String, Object> params = new HashMap<>();
                params.put("rolesId", roleId);
                HttpResponse response = HttpHelper.get(profileInnerUrl + url, params);
                Envelop envelop = objectMapper.readValue(response.getBody(), Envelop.class);
                if (envelop.isSuccessFlg() && null != envelop.getDetailModelList() && envelop.getDetailModelList().size() > 0) {
                    List<MRsRolesResource> roleResourceModels = envelop.getDetailModelList();
                    if(roleResourceModels != null && roleResourceModels.size() > 0){
                        for(int i = 0; i < roleResourceModels.size() ;i++){
                            MRsRolesResource rolesResource = objectMapper.convertValue(roleResourceModels.get(i),MRsRolesResource.class) ;
                    if (roleResourceModels != null && roleResourceModels.size() > 0) {
                        for (int i = 0; i < roleResourceModels.size(); i++) {
                            MRsRolesResource rolesResource = objectMapper.convertValue(roleResourceModels.get(i), MRsRolesResource.class);
                            rolesResourceList.add(rolesResource);
                        }
                    }
@ -498,14 +565,14 @@ public class LoginService extends BaseService {
                LogService.getLogger(LoginService.class).error(ex.getMessage());
            }
        }
        return  rolesResourceList;
        return rolesResourceList;
    }
    private List<Map<String, Object>> getUserFeatures(String userId) throws Exception {
        Map params = new HashMap<>();
        params.put("user_id", userId);
        HttpResponse response = HttpHelper.get(profileInnerUrl + "/roles/user/features", params);
        Envelop envelop =  objectMapper.readValue(response.getBody(), Envelop.class);
        Envelop envelop = objectMapper.readValue(response.getBody(), Envelop.class);
        if (envelop.isSuccessFlg()) {
            return envelop.getDetailModelList();
        } else {

+ 48 - 0
app/app-iot-server/src/main/resources/application-jwdev.yml

@ -0,0 +1,48 @@
spring:
  profiles: jwdev
  loginVaild: true
  redis:
    host: 172.19.103.47 # Redis server host.
    port: 6379
    password: redis!@456
  datasource:
    wlyy:
      url: jdbc:mysql://172.19.103.77/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
      username: root
      password: 123456
app:
#  oauth2InnerUrl: http://172.19.103.44:10260/  # 物联网环境
  oauth2InnerUrl: http://172.19.103.73:10260/   # 认证中心,获取token ehr环境
  oauth2OuterUrl: http://27.154.233.186:10260/  # 上饶-授权外网映射
service-gateway:
  iotUrl: http://192.168.131.24:8088/svr-iot/
  profileInnerUrl: http://172.19.103.73:10000/api/v1.0/admin
  profileOuterUrl: http://27.154.233.186:10000/api/v1.0/admin
  portalInnerUrl: http://172.19.103.73:10280/api/v1.0/portal
  portalOuterUrl: http://27.154.233.186:10280/api/v1.0/portal
third:
  wlyy:
    url: http://172.19.103.88:9092/wlyy/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee61
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee57
ehr:
  user:
    roleId: 10268
  metadata:
    version: 59083976eebd
    reference: 000000065a965615966b3a40c86ceba7
fast-dfs:
  tracker-server: 172.19.103.54:22122
  public-server: http://172.19.103.54:80/
logging:
  path: /data/logger
  file: app-iot-server
##如果是外网项目就是flase 内网是true
neiwang:
  enable: true
  wlyy: http://localhost:9099/iot/

+ 45 - 0
app/app-iot-server/src/main/resources/application-jwprod.yml

@ -0,0 +1,45 @@
spring:
  profiles: jwprod
  loginVaild: true
  redis:
    host: 172.19.103.47 # Redis server host.
    port: 6379
    password: redis!@456
  datasource:
    wlyy:
      url: jdbc:mysql://59.61.92.90:9069/wlyy?useUnicode=true&characterEncoding=utf-8&amp;autoReconnect=true
      username: wlyy
      password: jkzlehr@123
app:
  oauth2InnerUrl: http://172.19.103.73:10260/
  oauth2OuterUrl: http://27.154.233.186:10260/
service-gateway:
  profileInnerUrl: http://172.19.103.73:10000/api/v1.0/admin
  profileOuterUrl: http://27.154.233.186:10000/api/v1.0/admin
  portalInnerUrl: http://172.19.103.73:10280/api/v1.0/portal
  portalOuterUrl: http://27.154.233.186:10280/api/v1.0/portal
third:
  wlyy:
    url: http://www.yihu.com/wlyy/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee61
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee57
ehr:
  user:
    roleId: 10268
  metadata:
    version: 59083976eebd
    reference: 000000065a965615966b3a40c86ceba7
fast-dfs:
  tracker-server: 11.1.2.9:22122
  accessUrl: http://11.1.2.9
logging:
  path: /data/logger
  file: app-iot-server
##如果是外网项目就是flase 内网是true
neiwang:
  enable: false
  wlyy: http://59.61.92.90:9099/iot/
#单点登录
#GET http://172.19.103.73:10260/oauth/sso?response_type=token&client_id=uzs5G0HgTp&state=sxy&scope=read&redirect_uri=http://192.168.1.221:8010/ehr/browser/common/login/signin?idCardNo=362321200108017313&user=admin

+ 44 - 0
app/app-iot-server/src/main/resources/application-jwtest.yml

@ -0,0 +1,44 @@
spring:
  profiles: jwtest
  loginVaild: true
  redis:
    host: 172.19.103.47 # Redis server host.
    port: 6379
    password: redis!@456
  datasource:
    wlyy:
      url: jdbc:mysql://172.19.103.85/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
      username: linzhou
      password: linzhou
app:
  oauth2InnerUrl: http://172.19.103.73:10260/
  oauth2OuterUrl: http://27.154.233.186:10260/
service-gateway:
  iotUrl: http://172.19.103.33:8088/svr-iot/
  profileInnerUrl: http://172.19.103.73:10000/api/v1.0/admin
  profileOuterUrl: http://27.154.233.186:10000/api/v1.0/admin
  portalInnerUrl: http://172.19.103.73:10280/api/v1.0/portal
  portalOuterUrl: http://27.154.233.186:10280/api/v1.0/portal
third:
  wlyy:
    url: http://172.19.103.88:9092/wlyy/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee61
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee57
ehr:
  user:
    roleId: 10268
  metadata:
    version: 59083976eebd
    reference: 000000065a965615966b3a40c86ceba7
fast-dfs:
  tracker-server: 172.19.103.54:22122
  public-server: http://172.19.103.54:80/
logging:
  path: /data/logger
  file: app-iot-server
##如果是外网项目就是flase,false会调用内网http接口项目提交  内网是true直接上传fastDfs
neiwang:
  enable: true
  wlyy: http://172.19.103.88:9099/iot/

+ 28 - 30
app/app-iot-server/src/main/resources/application.yml

@ -23,7 +23,27 @@ spring:
  resources:
    static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/front/,classpath:/
#    cache-period: 0
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    initialSize: 50
    maxActive: 50
    minIdle: 50 #最大空闲连接
    maxWait: 50
    validationQuery: SELECT 1 #SQL 查询, 用来验证从连接池取出的连接, 在将连接返回给调用者之前。 如果指定, 则查询必须是一个SQL SELECT 并且必须返回至少一行记录
    testOnBorrow: true #指明是否在从池中取出连接前进行检验, 如果检验失败, 则从池中去除连接并尝试取出另一个。注意: 设置为true 后如果要生效,validationQuery 参数必须设置为非空字符串
    testOnReturn: true #指明是否在归还到池中前进行检验 注意: 设置为true 后如果要生效validationQuery 参数必须设置为非空字符串
    testWhileIdle: true #指明连接是否被空闲连接回收器(如果有)进行检验,如果检测失败,则连接将被从池中去除
    minEvictableIdleTimeMillis: 3600000 #连接池中连接,在时间段内一直空闲,被逐出连接池的时间(1000*60*60),以毫秒为单位
    timeBetweenEvictionRunsMillis: 300000 #在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位,一般比minEvictableIdleTimeMillis小
    poolPreparedStatements: true # 打开PSCache,并且指定每个连接上PSCache的大小
    maxPoolPreparedStatementPerConnectionSize: 50
    removeAbandoned: false #超过时间限制是否回收
    removeAbandonedTimeout: 7200 #超时时间;单位为秒。180秒=3分钟
    logAbandoned: false #关闭abanded连接时输出错误日志
    filters: stat,wall,logback #配置监控统计拦截的filters,去掉后监控界面sql将无法统计,'wall'用于防火墙
      ##  演示用 后面可以删除 start
      ##  演示用 后面可以删除 end
permissions:
  info: admin
@ -44,37 +64,8 @@ fast-dfs:
    max-size: 20
    wait-time: 500
---
spring:
  profiles: jwdev
  loginVaild: true
  redis:
    host: 172.19.103.47 # Redis server host.
    port: 6379
    password: redis!@456
app:
#  oauth2InnerUrl: http://172.19.103.44:10260/  # 物联网环境
  oauth2InnerUrl: http://172.19.103.73:10260/   # 认证中心,获取token ehr环境
  oauth2OuterUrl: http://27.154.233.186:10260/  # 上饶-授权外网映射
service-gateway:
  iotUrl: http://192.168.131.24:8088/svr-iot/
  profileInnerUrl: http://172.19.103.73:10000/api/v1.0/admin
  profileOuterUrl: http://27.154.233.186:10000/api/v1.0/admin
  portalInnerUrl: http://172.19.103.73:10280/api/v1.0/portal
  portalOuterUrl: http://27.154.233.186:10280/api/v1.0/portal
third:
  wlyy:
    url: http://172.19.103.88:9092/wlyy/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee61
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee57
ehr:
  user:
    roleId: 10268
  metadata:
    version: 59083976eebd
    reference: 000000065a965615966b3a40c86ceba7
<<<<<<< HEAD
fast-dfs:
  tracker-server: 172.19.103.54:22122
  public-server: http://172.19.103.54:80/
@ -163,3 +154,10 @@ neiwang:
  wlyy: http://59.61.92.90:9099/iot/
#单点登录
#GET http://172.19.103.73:10260/oauth/sso?response_type=token&client_id=uzs5G0HgTp&state=sxy&scope=read&redirect_uri=http://192.168.1.221:8010/ehr/browser/common/login/signin?idCardNo=362321200108017313&user=admin
=======
hibernate:
  dialect: org.hibernate.dialect.MySQL5Dialect
  show_sql: false
  ejb:
    naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756

+ 13 - 12
app/app-iot-server/src/main/webapp/front/js/scripts/login.js

@ -3,7 +3,7 @@
 */
var loginRelyOn = ['jquery', 'layer', 'vue', 'jsHelper', 'apiServer', 'promise', 'bootstrap', 'validate'];
require(loginRelyOn, function ($, layer, vue, jsHelper, apiServer, Promise) {
   jsHelper.setLayerCon();
    jsHelper.setLayerCon();
    var load = null;
    var loginApp = new vue({
        el: '#loginApp',
@ -13,40 +13,41 @@ require(loginRelyOn, function ($, layer, vue, jsHelper, apiServer, Promise) {
        },
        methods: {
            setLoad: function () {
                load =layer.load(1, {
                    shade: [0.5,'#000']
                load = layer.load(1, {
                    shade: [0.5, '#000']
                });
            },
            sendFun: function () {
                if (this.userID == '') {
                    this.tips('请输入账号', '#lUAn');
                    return ;
                    return;
                }
                if (this.password == '') {
                    this.tips('请输入密码', '#lUPwd');
                    return ;
                    return;
                }
                this.setLoad();
                apiServer.login({
                    data:{
                    data: {
                        "username": this.userID,
                        "password": this.password
                    }
                }).then(function (res) {
                    layer.close(load);
                    if (res.successFlg) {
                        debugger
                        sessionStorage.setItem("ZF_UID",res.obj.id);
                        sessionStorage.setItem("ZF_UN",res.obj.realName);
                        sessionStorage.setItem("ZF_U",res.obj);
                        location.href = apiServer.indexPage();
                        sessionStorage.setItem("ZF_UID", res.obj.id);
                        sessionStorage.setItem("ZF_UN", res.obj.realName);
                        sessionStorage.setItem("ZF_U", res.obj);
                        var indexurl = apiServer.indexPage();
                        console.info(indexurl)
                        location.href = indexurl;
                    } else {
                        layer.msg(res.message);
                    }
                });
            },
            tips: function (msg, id) {
                layer.tips(msg, id,{
                layer.tips(msg, id, {
                    tips: [2, '#ff5722'],
                    time: 1000
                });

+ 159 - 0
app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebAuthenticationProvider.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebAuthenticationProvider.java
package com.yihu.health.security.core;
import org.springframework.security.authentication.BadCredentialsException;
@ -150,3 +151,161 @@ public class EhrWebAuthenticationProvider extends AbstractUserDetailsAuthenticat
        return this.userDetailsService;
    }
}
=======
//package com.yihu.ehr.iot.security.core;
//
//import org.springframework.security.authentication.BadCredentialsException;
//import org.springframework.security.authentication.InternalAuthenticationServiceException;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
//import org.springframework.security.authentication.dao.SaltSource;
//import org.springframework.security.authentication.encoding.PasswordEncoder;
//import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder;
//import org.springframework.security.core.AuthenticationException;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.core.userdetails.UsernameNotFoundException;
//import org.springframework.util.Assert;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//
//import javax.servlet.http.HttpServletRequest;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
//
//    private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
//    private PasswordEncoder passwordEncoder;
//    private String userNotFoundEncodedPassword;
//    private SaltSource saltSource;
//    private UserDetailsService userDetailsService;
//    private SessionRegistry sessionRegistry;
//
//    public EhrWebAuthenticationProvider() {
//        this.setPasswordEncoder((PasswordEncoder)(new PlaintextPasswordEncoder()));
//    }
//
//    public EhrWebAuthenticationProvider(UserDetailsService userDetailsService) {
//        this.userDetailsService = userDetailsService;
//        this.setPasswordEncoder((PasswordEncoder)(new PlaintextPasswordEncoder()));
//    }
//
//    /**
//    public EhrWebAuthenticationProvider(UserDetailsService userDetailsService, SessionRegistry sessionRegistry) {
//        this.userDetailsService = userDetailsService;
//        this.sessionRegistry = sessionRegistry;
//        this.setPasswordEncoder((PasswordEncoder)(new PlaintextPasswordEncoder()));
//    }
//     */
//
//    /**
//     * Step 3
//     * @param userDetails
//     * @param authentication
//     * @throws AuthenticationException
//     */
//    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
//        Object salt = null;
//        if(this.saltSource != null) {
//            salt = this.saltSource.getSalt(userDetails);
//        }
//
//        if(authentication.getCredentials() == null) {
//            this.logger.debug("Authentication failed: no credentials provided");
//            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
//        } else {
//            EhrWebAuthenticationToken ehrWebAuthenticationToken = (EhrWebAuthenticationToken) authentication;
//            if(!ehrWebAuthenticationToken.isSso()) {
//                String presentedPassword = authentication.getCredentials().toString();
//                if (!this.passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
//                    this.logger.debug("Authentication failed: password does not match stored value");
//                    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
//                }
//            }
//            //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            //sessionRegistry.registerNewSession(request.getSession().getId(), userDetails);
//        }
//    }
//
//    protected void doAfterPropertiesSet() throws Exception {
//        Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
//    }
//
//    protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
//        UserDetails loadedUser;
//        try {
//            loadedUser = this.getUserDetailsService().loadUserByUsername(username);
//        } catch (UsernameNotFoundException var6) {
//            if(authentication.getCredentials() != null) {
//                String presentedPassword = authentication.getCredentials().toString();
//                this.passwordEncoder.isPasswordValid(this.userNotFoundEncodedPassword, presentedPassword, (Object)null);
//            }
//
//            throw var6;
//        } catch (Exception var7) {
//            throw new InternalAuthenticationServiceException(var7.getMessage(), var7);
//        }
//
//        if(loadedUser == null) {
//            throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
//        } else {
//            return loadedUser;
//        }
//    }
//
//    public void setPasswordEncoder(Object passwordEncoder) {
//        Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
//        if(passwordEncoder instanceof PasswordEncoder) {
//            this.setPasswordEncoder((PasswordEncoder)passwordEncoder);
//        } else if(passwordEncoder instanceof org.springframework.security.crypto.password.PasswordEncoder) {
//            final org.springframework.security.crypto.password.PasswordEncoder delegate = (org.springframework.security.crypto.password.PasswordEncoder)passwordEncoder;
//            this.setPasswordEncoder(new PasswordEncoder() {
//                public String encodePassword(String rawPass, Object salt) {
//                    this.checkSalt(salt);
//                    return delegate.encode(rawPass);
//                }
//
//                public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
//                    this.checkSalt(salt);
//                    return delegate.matches(rawPass, encPass);
//                }
//
//                private void checkSalt(Object salt) {
//                    Assert.isNull(salt, "Salt value must be null when used with crypto module PasswordEncoder");
//                }
//            });
//        } else {
//            throw new IllegalArgumentException("passwordEncoder must be a PasswordEncoder instance");
//        }
//    }
//
//    private void setPasswordEncoder(PasswordEncoder passwordEncoder) {
//        Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
//        this.userNotFoundEncodedPassword = passwordEncoder.encodePassword("userNotFoundPassword", (Object)null);
//        this.passwordEncoder = passwordEncoder;
//    }
//
//    protected PasswordEncoder getPasswordEncoder() {
//        return this.passwordEncoder;
//    }
//
//    public void setSaltSource(SaltSource saltSource) {
//        this.saltSource = saltSource;
//    }
//
//    protected SaltSource getSaltSource() {
//        return this.saltSource;
//    }
//
//    public void setUserDetailsService(UserDetailsService userDetailsService) {
//        this.userDetailsService = userDetailsService;
//    }
//
//    protected UserDetailsService getUserDetailsService() {
//        return this.userDetailsService;
//    }
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationProvider.java

+ 68 - 0
app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebAuthenticationSuccessHandler.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebAuthenticationSuccessHandler.java
package com.yihu.health.security.core;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -61,3 +62,70 @@ public class EhrWebAuthenticationSuccessHandler implements AuthenticationSuccess
        sessionRegistry.registerNewSession(httpServletRequest.getSession().getId(),userDetailModel);
    }
}
=======
//package com.yihu.ehr.iot.security.core;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.agModel.user.UserDetailModel;
//import com.yihu.ehr.iot.util.CurrentRequest;
//import com.yihu.ehr.util.rest.Envelop;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//
//    @Autowired
//    private ObjectMapper objectMapper;
//
//    @Autowired
//    SessionRegistry sessionRegistry;
//
//    /**
//     * Step 4
//     * @param httpServletRequest
//     * @param httpServletResponse
//     * @param authentication
//     * @throws IOException
//     * @throws ServletException
//     */
//    @Override
//    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//        Envelop envelop = new Envelop();
//        envelop.setSuccessFlg(true);
//        Map userMap = new HashMap();
//        String id = (String) httpServletRequest.getAttribute("id");
//        String username = (String) httpServletRequest.getAttribute("username");
//        String realName = (String) httpServletRequest.getAttribute("realName");
//        userMap.put("id", id);
//        userMap.put("username", username);
//        userMap.put("realName", realName);
//        envelop.setObj(userMap);
//
//        List modelList = new ArrayList<>();
//        UserDetailModel userDetailModel = (UserDetailModel)httpServletRequest.getAttribute("user");
//        modelList.add(userDetailModel);
//        envelop.setDetailModelList(modelList);
//
//        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//        httpServletResponse.getWriter().print(objectMapper.writeValueAsString(envelop));
//
//        sessionRegistry.registerNewSession(httpServletRequest.getSession().getId(),userDetailModel);
//    }
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationSuccessHandler.java

+ 58 - 0
app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebContextLogoutHandler.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/public-health-server/src/main/java/com/yihu/health/security/core/EhrWebContextLogoutHandler.java
package com.yihu.health.security.core;
import org.apache.commons.logging.Log;
@ -38,3 +39,60 @@ public class EhrWebContextLogoutHandler extends SecurityContextLogoutHandler {
            }
    }
}
=======
//package com.yihu.ehr.iot.security.core;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.agModel.user.UserDetailModel;
//import com.yihu.ehr.iot.util.CurrentRequest;
//import com.yihu.ehr.util.rest.Envelop;
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.context.SecurityContext;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
//import org.springframework.security.web.authentication.logout.LogoutHandler;
//import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
//import org.springframework.util.Assert;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.HttpSession;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebContextLogoutHandler extends SecurityContextLogoutHandler {
//
//    protected final Log logger = LogFactory.getLog(this.getClass());
//
//    @Autowired
//    SessionRegistry sessionRegistry;
//
//    /**
//     * Step 5
//     * @param httpServletRequest
//     * @param httpServletResponse
//     * @param authentication
//     */
//    @Override
//    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
//        Assert.notNull(httpServletRequest, "HttpServletRequest required");
//            HttpSession session = httpServletRequest.getSession(false);
//            if (session != null) {
//                this.logger.debug("removeSessionInformation, session: " + session.getId());
//                sessionRegistry.removeSessionInformation(session.getId());
//            }
//    }
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebContextLogoutHandler.java

+ 51 - 0
app/public-health-server/src/main/java/com/yihu/health/util/CurrentRequest.java

@ -1,3 +1,4 @@
<<<<<<< HEAD:app/public-health-server/src/main/java/com/yihu/health/util/CurrentRequest.java
package com.yihu.health.util;
import com.yihu.ehr.agModel.user.UserDetailModel;
@ -33,3 +34,53 @@ public class CurrentRequest {
        return user;
    }
}
=======
//package com.yihu.ehr.iot.util;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.agModel.user.UserDetailModel;
//import com.yihu.ehr.iot.util.http.HttpHelper;
//import com.yihu.ehr.iot.util.http.HttpResponse;
//import com.yihu.ehr.iot.util.spring.SpringContextHolder;
//import com.yihu.ehr.util.rest.Envelop;
//import org.apache.commons.lang.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.core.session.SessionInformation;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import javax.servlet.http.HttpServletRequest;
//import java.io.IOException;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//
///**
// * @author lith
// * @created 2018/02/06
// */
//@Component
//public class CurrentRequest {
//
//    @Autowired
//    SessionRegistry sessionRegistry;
//
//    /**
//     * 获取当前登录用户,当前已登录的用户都缓存在session中
//     * @param request
//     * @return
//     */
//    public  UserDetailModel getCurrentUser(HttpServletRequest request){
//        String sessionId = request.getSession().getId();
//        UserDetailModel user = null;
//        SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId);
//        if(null != sessionInformation.getPrincipal()){
//            user = (UserDetailModel)sessionInformation.getPrincipal();
//        }
//        return user;
//    }
//}
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756:app/app-iot-server/src/main/java/com/yihu/ehr/iot/util/CurrentRequest.java

+ 4 - 4
server/svr-admin-server/pom.xml

@ -52,10 +52,10 @@
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>org.springframework.cloud</groupId>-->
            <!--<artifactId>spring-cloud-starter-config</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>

+ 1 - 1
server/svr-admin-server/src/main/resources/application.yml

@ -1,5 +1,5 @@
server:
  port: 8082
  port: 8084
spring:
  application:

+ 11 - 11
server/svr-admin-server/src/main/resources/bootstrap.yml

@ -1,15 +1,15 @@
##优先读取 boostarap配置 然后在读取application。yml的配置
spring:
  #从发现服务里面取配置服务的信息
  cloud:
    config:
      username: jw
      password: jkzl
      failFast: true ##启动快速失败 即链接不到配置服务就启动失败
      discovery:
        enabled: true ##使用发现服务
        service-id: svr-configurations ##配置服务的名字
#spring:
#  #从发现服务里面取配置服务的信息
#  cloud:
#    config:
#      username: jw
#      password: jkzl
#      failFast: true ##启动快速失败 即链接不到配置服务就启动失败
#      discovery:
#        enabled: true ##使用发现服务
#        service-id: svr-configurations ##配置服务的名字
#
##发现服务的地址

+ 36 - 0
svr/svr-base/src/main/resources/application.yml

@ -1,6 +1,42 @@
<<<<<<< HEAD
#通用的配置不用区分环境变量
server:
  port: ${server.svr-base-port}
=======
##如果有配置服务的话,远程服务器和本地服务器配置不一致的情况下,优先远程的为主  git上 svr-base ->  git application ->本地 appliction ->本地 bootstarp
spring:
  application:
    name: svr-base  #注册到发现服务的id 如果id一样 eurika会自动做负载
#  jmx:
#    default-domain: svr-base
  jmx:
    enabled: true
#  data:
#    elasticsearch:
#      cluster-name: jkzl #es集群的名字
#      cluster-nodes: 172.19.103.68:9300  #多个逗号分割
#      cluster-nodes-jest: http://172.19.103.68:9200  #多个逗号分割
#      repositories:
#        enabled: true
#      properties:
#        client:
#          transport:
#            sniff: false #开启嗅探集群  用nginx代理一层过后会出现ip解析失败问题
management:
  security:
    enabled: false #关闭 refresh的权限认证
health:
  config:
    enabled: true
endpoints:
  info:
    enabled: true
>>>>>>> eb49bc9a23d809112535a9bde36737ef12f77756
spring:
  datasource:

+ 105 - 0
web-gateway/src/main/java/com/yihu/jw/controller/base/login/LoginContorller.java

@ -0,0 +1,105 @@
package com.yihu.jw.controller.base.login;
import com.yihu.base.security.properties.SecurityProperties;
import com.yihu.base.security.sms.mobile.MobileCheck;
import com.yihu.base.security.sms.process.SmsValidateCodeProcessor;
import com.yihu.jw.common.base.base.BaseContants;
import com.yihu.jw.fegin.base.base.FunctionFeign;
import com.yihu.jw.fegin.base.login.LoginFeign;
import com.yihu.jw.restmodel.common.Envelop;
import com.yihu.jw.restmodel.common.base.BaseEnvelop;
import com.yihu.jw.rm.base.BaseLoginRequestMapping;
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.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.ServletWebRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by 刘文彬 on 2018/4/20.
 */
@RestController
@RequestMapping(BaseLoginRequestMapping.api_gateway_common)
@Api(value = "登录模块", description = "登录模块")
public class LoginContorller {
    @Autowired
    private LoginFeign loginFeign;
    @Autowired
    private MobileCheck mobileCheck;
    @Autowired
    private SmsValidateCodeProcessor smsValidateCodeProcessor;
    @PostMapping(value = BaseLoginRequestMapping.BaseLoginAccount.api_checkoutInfo, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "注册校验信息", notes = "注册校验姓名、身份证、医保卡号信息")
    public BaseEnvelop checkoutInfo(@ApiParam(name = "ssc", value = "医保卡号", required = true) @RequestParam(value = "ssc", required = true) String ssc,
                                @ApiParam(name = "idcard", value = "身份证", required = true) @RequestParam(value = "idcard", required = true) String idcard){
        return loginFeign.checkoutInfo(ssc,idcard);
    }
    @PostMapping(value = BaseLoginRequestMapping.BaseLoginAccount.api_accountSub, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "注册账号", notes = "注册校验姓名、身份证、医保卡号信息")
    public Envelop register(
            @ApiParam(name = "mobilePhone", value = "电话号码(账号)", required = true) @RequestParam(value = "mobilePhone", required = true) String mobilePhone,
            @ApiParam(name = "saasId", value = "saasID", required = true) @RequestParam(value = "saasId", required = true) String saasId,
            @ApiParam(name = "type", value = "1微信端注册,2微信端找回密码,3医生端找回密码,4患者登录,5医生登录", required = true) @RequestParam(value = "type", required = true) int type,
            @ApiParam(name = "captcha", value = "短信验证码", required = true) @RequestParam(value = "captcha", required = true) String captcha,
            @ApiParam(name = "name", value = "姓名", required = true) @RequestParam(value = "name", required = true) String name,
            @ApiParam(name = "password", value = "账户密码", required = true) @RequestParam(value = "password", required = true) String password,
            @ApiParam(name = "idcard", value = "身份证", required = true) @RequestParam(value = "idcard", required = true) String idcard,
            @ApiParam(name = "ssc", value = "医保卡号", required = true) @RequestParam(value = "ssc", required = true) String ssc) {
        return loginFeign.register(mobilePhone,saasId,type,captcha,name,password,idcard,ssc);
    }
    @PostMapping(BaseLoginRequestMapping.BaseLoginAccount.mobileSendSms)
    @ApiOperation(value = "发送短信登录的验证码", notes = "不走校验框架")
    public BaseEnvelop createCode(@ApiParam(name = "mobile", value = "手机号", required = true) @RequestParam(value = "mobile", required = true) String mobile,
                                  HttpServletRequest request, HttpServletResponse response) throws Exception{
        //验证手机号是否正确
        String[] mobileSaas = mobile.split(",");
        if (!mobileCheck.checkMobile(mobileSaas[0])) {
            return BaseEnvelop.getError("手机格式错误!");
        } else {
            //发送短信验证码并且保存到redis中
            smsValidateCodeProcessor.create(new ServletWebRequest(request, response));
            return BaseEnvelop.getSuccess("发送成功!");
        }
    }
    @PostMapping(BaseLoginRequestMapping.BaseLoginAccount.api_login)
    public Envelop login(@ApiParam(name = "mobilePhone", value = "电话号码(账号)", required = false) @RequestParam(value = "mobilePhone", required = false) String mobilePhone,
                       @ApiParam(name = "password", value = "password", required = false) @RequestParam(value = "password", required = false) String password,
                       @ApiParam(name = "saasId", value = "saasID", required = true) @RequestParam(value = "saasId", required = true) String saasId,
                       @ApiParam(name = "captcha", value = "短信验证码", required = false) @RequestParam(value = "captcha", required = false) String captcha){
        //1 框架登录
        //2 base取用户信息
        return loginFeign.login(mobilePhone,password,saasId,captcha);
    }
//    @PostMapping("/logout")
//    public Envelop logout(){
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Accept", "*/*");
//        headers.add("Cache-Control", "no-cache");
//        RestTemplate restTemplate = new RestTemplate();
//        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
//        //设置http请求实体
//        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
//        restTemplate.postForObject("http://localhost:8088/logout", requestEntity, String.class);
//        return new Envelop();
//    }
}

+ 110 - 0
web-gateway/src/main/resources/application.yml

@ -0,0 +1,110 @@
##如果有配置服务的话,远程服务器和本地服务器配置不一致的情况下,优先远程的为主
server:
  port: 8088
spring:
  application:
    name:  web-gateway #注册到发现服务的id 如果id一样 eurika会自动做负载
  jmx:
    default-domain: web-gateway
  http:
    multipart:
      enabled: true
      max-file-size: 500MB
      max-request-size: 500MB
#  data:
#    elasticsearch: #ElasticsearchProperties
#      cluster-name: jkzl #默认即为elasticsearch  集群名
#      cluster-nodes: 172.19.103.45:9300,172.19.103.68:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
#      local: false #是否本地连接
#      properties: # Additional properties used to configure the client.
#        enable: true
#    # JEST (Elasticsearch HTTP client) (JestProperties)
#  elasticsearch:
#    jest:
#      uris: http://172.19.103.45:9200,http://172.19.103.68:9200
##      uris: http://172.19.103.68:9200
#      connection-timeout: 60000 # Connection timeout in milliseconds.
#      multi-threaded: true
  redis:
    host: 172.19.103.88 # Redis server host.
    port: 6379 # Redis server port.
    database: 0
##开启feign断路器
feign:
  hystrix:
    enabled: true
management:
  security:
    enabled: false  #关闭 refresh的权限认证
hystrix:
  threadpool:
    default:
      coreSize: 500  #并发执行的最大线程数,默认10
  command:
    paas-file:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3600000
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 308000  #命令执行超时时间,默认1000ms
ribbon:
  ReadTimeout: 300000
  ConnectTimeout: 5000
#zuul 默认会代理所有的微服务  路径 /{appliction.name}/**
#zuul:
#  ignored-services: '*'  ##忽略全部的代理  忽略单个微服务   ignored-services: svr-base 多个逗号分割
#  routes:
#    svr-base: /v1/base/**  ##svr-base方向代理到/base下多层级的路径
#    svr-wlyy: /v1/wlyy/**
#    api-esb-url:
#      path: /job/**
#      url: http://192.168.131.131:10030/
#      stripPrefix: false ##如果是物理服务器要设置成false
#    svr-base:    这种方式和  svr-base: /base/**  一样  svr-base可以随便写 唯一即可
#      path: /base/**  path是代理后的路径
#      serviceId: svr-base  serviceId是微服务name
#   svr-base: 这种方式和 上面一样 就是serviceId改成具体的url 但是这种配置方法不能利用eurika的负载均衡
#     path: /base/**
#     url: http://localhost:10020/
#svr-base: 这边是微服务ID  配置负载均衡
#  ribbon:
#    listOfService: http://localhost:10020/,http://localhost:10021/
---
spring:
  profiles: jwdev
#  cloud:
#    stream:
#      kafka:
#        binder:
#          brokers: 172.17.110.201
#          defaultBrokerPort: 9092
#          zkNodes: 172.17.110.201
#          defaultZkPort: 2181
#          replicationFactor: 1
---
spring:
  profiles: jwtest
---
spring:
  profiles: jwprod