Commit 65324010 authored by Java-刘 彧阳's avatar Java-刘 彧阳

Merge branch 'master' into log_without_phone

Conflicts:
	src/main/java/cn/quantgroup/xyqb/controller/external/user/WeChatController.java
	src/test/java/user/TestUserLogin.java
parents 3cc775b3 0c126d5d
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
...@@ -40,6 +40,12 @@ ...@@ -40,6 +40,12 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId> <artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
...@@ -207,6 +213,78 @@ ...@@ -207,6 +213,78 @@
<artifactId>quantgroup-config-sdk</artifactId> <artifactId>quantgroup-config-sdk</artifactId>
<version>1.0.3-SNAPSHOT</version> <version>1.0.3-SNAPSHOT</version>
</dependency> </dependency>
<!-- motan -->
<dependency>
<groupId>com.weibo</groupId>
<artifactId>motan-core</artifactId>
<version>0.2.2</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.quantgroup</groupId>
<artifactId>hession-bugfix</artifactId>
<version>4.0.38</version>
</dependency>
<dependency>
<groupId>com.weibo</groupId>
<artifactId>motan-transport-netty</artifactId>
<version>0.2.2</version>
</dependency>
<!-- only needed for spring-based features -->
<dependency>
<groupId>com.weibo</groupId>
<artifactId>motan-springsupport</artifactId>
<version>0.2.2</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.quantgroup</groupId>
<artifactId>xyqb-user-rpc-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.weibo</groupId>
<artifactId>motan-registry-zookeeper</artifactId>
<version>0.2.1</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- spring security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.7.RELEASE</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package cn.quantgroup.xyqb; package cn.quantgroup.xyqb;
import com.weibo.api.motan.common.MotanConstants;
import com.weibo.api.motan.util.MotanSwitcherUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableAsync;
@ComponentScan(basePackages = {"cn.quantgroup.xyqb", "cn.quantgroup.cloudconfig"}) @ComponentScan(basePackages = {"cn.quantgroup.xyqb", "cn.quantgroup.cloudconfig"})
...@@ -18,9 +23,20 @@ import org.springframework.scheduling.annotation.EnableAsync; ...@@ -18,9 +23,20 @@ import org.springframework.scheduling.annotation.EnableAsync;
@Configuration @Configuration
@EnableAspectJAutoProxy @EnableAspectJAutoProxy
@EnableAsync @EnableAsync
@Slf4j
public class Bootstrap { public class Bootstrap {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args); SpringApplication springApplication = new SpringApplication(Bootstrap.class);
springApplication.addListeners(new ApplicationListener<ContextRefreshedEvent>() {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
log.info("注册zookeeper成功");
}
});
springApplication.setRegisterShutdownHook(true);
springApplication.run(args);
log.info("server start...");
} }
} }
package cn.quantgroup.xyqb; package cn.quantgroup.xyqb;
/** /**
* Created by Miraculous on 15/7/5. * Created by Miraculous on 15/7/5.
*/ */
...@@ -47,7 +46,7 @@ public interface Constants { ...@@ -47,7 +46,7 @@ public interface Constants {
long WECHAT = 198L; long WECHAT = 198L;
} }
interface Session{ interface Session {
String USER_SESSION_CACHE = "user:session:"; String USER_SESSION_CACHE = "user:session:";
String USER_SESSION_ID_CACHE = "userid-sessionvalue:cache:"; String USER_SESSION_ID_CACHE = "userid-sessionvalue:cache:";
Long ONE_DAY = 24 * 60 * 60L; Long ONE_DAY = 24 * 60 * 60L;
......
package cn.quantgroup.xyqb.aspect.captcha; package cn.quantgroup.xyqb.aspect.captcha;
import java.lang.annotation.Documented; import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* 类名称:CaptchaValidate * 类名称:CaptchaValidate
......
package cn.quantgroup.xyqb.aspect.fplock; package cn.quantgroup.xyqb.aspect.fplock;
import java.lang.annotation.Documented; import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* Created by Miraculous on 15/11/10. * Created by Miraculous on 15/11/10.
...@@ -15,5 +11,6 @@ import java.lang.annotation.Target; ...@@ -15,5 +11,6 @@ import java.lang.annotation.Target;
public @interface FPLock { public @interface FPLock {
String uniqueName(); String uniqueName();
FPRestriction[] restrictions() default {}; FPRestriction[] restrictions() default {};
} }
package cn.quantgroup.xyqb.aspect.fplock; package cn.quantgroup.xyqb.aspect.fplock;
import java.lang.annotation.Documented; import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
...@@ -16,10 +12,13 @@ import java.util.concurrent.TimeUnit; ...@@ -16,10 +12,13 @@ import java.util.concurrent.TimeUnit;
public @interface FPRestriction { public @interface FPRestriction {
// 持续时间 // 持续时间
int duration() default 1; int duration() default 1;
// 持续时间单位 // 持续时间单位
TimeUnit type() default TimeUnit.MINUTES; TimeUnit type() default TimeUnit.MINUTES;
// 限制值, -1表示不限制 // 限制值, -1表示不限制
int limit() default -1; int limit() default -1;
// 使用可覆盖 // 使用可覆盖
boolean override() default true; boolean override() default true;
} }
...@@ -35,11 +35,6 @@ import java.util.stream.Stream; ...@@ -35,11 +35,6 @@ import java.util.stream.Stream;
public class FirstParamLockAspect { public class FirstParamLockAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(FirstParamLockAspect.class); private static final Logger LOGGER = LoggerFactory.getLogger(FirstParamLockAspect.class);
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate;
private static final HashMap<String, FPRestrictionWraper> LOCK_PARAM; private static final HashMap<String, FPRestrictionWraper> LOCK_PARAM;
private static final Long MAX_COUNTER = 1L; private static final Long MAX_COUNTER = 1L;
private static final Long MAX_TO_LIVE = 10L; private static final Long MAX_TO_LIVE = 10L;
...@@ -50,6 +45,9 @@ public class FirstParamLockAspect { ...@@ -50,6 +45,9 @@ public class FirstParamLockAspect {
LOCK_PARAM = fastHashMap; LOCK_PARAM = fastHashMap;
} }
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate;
/* 自定义限制策略 (FPRestriction) 的情况下, 可配置的限制数值 */ /* 自定义限制策略 (FPRestriction) 的情况下, 可配置的限制数值 */
@Value("${xyqb.fplock.limit.byhour:3}") @Value("${xyqb.fplock.limit.byhour:3}")
private Integer limitByHour; // 每小时限制值 private Integer limitByHour; // 每小时限制值
...@@ -129,8 +127,8 @@ public class FirstParamLockAspect { ...@@ -129,8 +127,8 @@ public class FirstParamLockAspect {
public void setLimitation(String key, Integer duration, Integer limit) { public void setLimitation(String key, Integer duration, Integer limit) {
FPRestrictionWraper restriction = LOCK_PARAM.get(key); FPRestrictionWraper restriction = LOCK_PARAM.get(key);
if (restriction != null) { if (restriction != null) {
if(duration != null) restriction.duration(duration); if (duration != null) restriction.duration(duration);
if(limit != null) restriction.limit(limit); if (limit != null) restriction.limit(limit);
} }
} }
...@@ -213,6 +211,28 @@ public class FirstParamLockAspect { ...@@ -213,6 +211,28 @@ public class FirstParamLockAspect {
return true; return true;
} }
/**
* 根据时间单位获取Redis锁名
*
* @return
*/
private String getLockKeyByTimeUnit(TimeUnit timeUnit) {
Calendar calendar = Calendar.getInstance();
String unit = timeUnit.toString();
switch (timeUnit) {
case DAYS:
return unit + DateFormatUtils.format(calendar, "yyyyMMdd");
case HOURS:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHH");
case MINUTES:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHHmm");
case SECONDS:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHHmmss");
default:
return unit;
}
}
/** /**
* 注解包装类 * 注解包装类
*/ */
...@@ -284,26 +304,4 @@ public class FirstParamLockAspect { ...@@ -284,26 +304,4 @@ public class FirstParamLockAspect {
return "timeUnit:" + timeUnit + ", duration:" + this.duration + ", limit:" + limit; return "timeUnit:" + timeUnit + ", duration:" + this.duration + ", limit:" + limit;
} }
} }
/**
* 根据时间单位获取Redis锁名
*
* @return
*/
private String getLockKeyByTimeUnit(TimeUnit timeUnit) {
Calendar calendar = Calendar.getInstance();
String unit = timeUnit.toString();
switch (timeUnit) {
case DAYS:
return unit + DateFormatUtils.format(calendar, "yyyyMMdd");
case HOURS:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHH");
case MINUTES:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHHmm");
case SECONDS:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHHmmss");
default:
return unit;
}
}
} }
...@@ -49,7 +49,7 @@ public class CustomJCaptchaEngine extends ListImageCaptchaEngine { ...@@ -49,7 +49,7 @@ public class CustomJCaptchaEngine extends ListImageCaptchaEngine {
SingleColorGenerator colorGenerator = new SingleColorGenerator(Color.WHITE); SingleColorGenerator colorGenerator = new SingleColorGenerator(Color.WHITE);
//文字干扰器--- 可以创建多个 //文字干扰器--- 可以创建多个
BaffleTextDecorator baffleTextDecorator = new BaffleTextDecorator(1,colorGenerator, 1);//气泡干扰 BaffleTextDecorator baffleTextDecorator = new BaffleTextDecorator(1, colorGenerator, 1);//气泡干扰
// LineTextDecorator lineTextDecorator = new LineTextDecorator(1,colorGenerator, 1);//曲线干扰 // LineTextDecorator lineTextDecorator = new LineTextDecorator(1,colorGenerator, 1);//曲线干扰
// TextDecorator[] textDecorators = new TextDecorator[]{baffleTextDecorator, lineTextDecorator}; // TextDecorator[] textDecorators = new TextDecorator[]{baffleTextDecorator, lineTextDecorator};
TextDecorator[] textDecorators = new TextDecorator[]{baffleTextDecorator}; TextDecorator[] textDecorators = new TextDecorator[]{baffleTextDecorator};
......
...@@ -75,7 +75,7 @@ public class CustomJCaptchaService extends AbstractManageableImageCaptchaService ...@@ -75,7 +75,7 @@ public class CustomJCaptchaService extends AbstractManageableImageCaptchaService
} }
this.getTimes().remove(id); this.getTimes().remove(id);
if(valid) { if (valid) {
addNumberOfCorrectResponse(1); addNumberOfCorrectResponse(1);
} else { } else {
addNumberOfUncorrectResponse(1); addNumberOfUncorrectResponse(1);
......
...@@ -87,7 +87,6 @@ public class JpaConfig { ...@@ -87,7 +87,6 @@ public class JpaConfig {
} }
@Bean @Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager(); JpaTransactionManager transactionManager = new JpaTransactionManager();
......
...@@ -6,8 +6,6 @@ import org.springframework.beans.factory.annotation.Value; ...@@ -6,8 +6,6 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode; import org.springframework.data.redis.connection.RedisNode;
......
package cn.quantgroup.xyqb.config.http; package cn.quantgroup.xyqb.config.http;
import java.security.KeyManagementException; import com.fasterxml.jackson.annotation.JsonInclude;
import java.security.KeyStoreException; import com.fasterxml.jackson.databind.DeserializationFeature;
import java.security.NoSuchAlgorithmException; import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
import javax.net.ssl.SSLContext;
import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.CookieSpecs;
import org.apache.http.config.Registry; import org.apache.http.config.Registry;
...@@ -37,9 +33,11 @@ import org.springframework.core.convert.converter.ConverterRegistry; ...@@ -37,9 +33,11 @@ import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.filter.CharacterEncodingFilter;
import com.fasterxml.jackson.annotation.JsonInclude; import javax.net.ssl.SSLContext;
import com.fasterxml.jackson.databind.DeserializationFeature; import java.security.KeyManagementException;
import com.fasterxml.jackson.databind.SerializationFeature; import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
/** /**
* Created by Miraculous on 15/7/12. * Created by Miraculous on 15/7/12.
......
...@@ -12,9 +12,10 @@ import java.sql.Timestamp; ...@@ -12,9 +12,10 @@ import java.sql.Timestamp;
*/ */
public class Timestamp2LongConverter implements ObjectSerializer { public class Timestamp2LongConverter implements ObjectSerializer {
; ;
@Override @Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
Timestamp time = (Timestamp)object; Timestamp time = (Timestamp) object;
if (time == null) { if (time == null) {
serializer.write(String.valueOf(0L)); serializer.write(String.valueOf(0L));
} else { } else {
......
package cn.quantgroup.xyqb.config.motan;
import com.weibo.api.motan.config.springsupport.AnnotationBean;
import com.weibo.api.motan.config.springsupport.BasicServiceConfigBean;
import com.weibo.api.motan.config.springsupport.ProtocolConfigBean;
import com.weibo.api.motan.config.springsupport.RegistryConfigBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by 11 on 2017/2/27.
*/
@Configuration
public class MotanConfig {
@Bean
public AnnotationBean motanAnnotationBean() {
AnnotationBean motanAnnotationBean = new AnnotationBean();
motanAnnotationBean.setPackage("cn.quantgroup.xyqb.controller.external.motan");
return motanAnnotationBean;
}
@Bean(name = "userMotan")
public ProtocolConfigBean protocolConfig1(
@Value("${protocol.isDefault}") Boolean isDefault, @Value("${protocol.name}") String name,
@Value("${protocol.contentLength}") int contentLength) {
ProtocolConfigBean config = new ProtocolConfigBean();
config.setDefault(isDefault);
config.setName(name);
config.setMaxContentLength(contentLength);
config.setMaxServerConnection(1000);
return config;
}
@Bean(name = "registryConfig")
public RegistryConfigBean registryConfig(@Value("${registry.protocol}") String registryProtocol,
@Value("${registry.address}") String registryAddress
) {
RegistryConfigBean config = new RegistryConfigBean();
config.setRegProtocol(registryProtocol);
config.setAddress(registryAddress);
return config;
}
@Bean
public BasicServiceConfigBean baseServiceConfig(@Value("${motan.port}") int motanPort,
@Value("${motan.user.group}") String userGroup,
@Value("${motan.user.module}") String userModule,
@Value("${motan.application:xyqbUserMotan}") String applicationName) {
BasicServiceConfigBean config = new BasicServiceConfigBean();
config.setExport("userMotan:" + motanPort);
config.setGroup(userGroup);
config.setVersion("1.0");
config.setAccessLog(true);
config.setShareChannel(true);
config.setModule(userModule);
config.setApplication(applicationName);
config.setRegistry("registryConfig");
return config;
}
}
package cn.quantgroup.xyqb.config.web; package cn.quantgroup.xyqb.config.web;
import cn.quantgroup.xyqb.interceptors.ChannelIdInterceptor; import cn.quantgroup.xyqb.interceptors.ChannelIdInterceptor;
import cn.quantgroup.xyqb.interceptors.IPWhiteListInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
...@@ -11,7 +13,11 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter ...@@ -11,7 +13,11 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
@Configuration @Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter { public class InterceptorConfig extends WebMvcConfigurerAdapter {
@Value("${configserver.disable}")
private Integer isDebug;
public void addInterceptors(InterceptorRegistry registry) { public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new IPWhiteListInterceptor(isDebug)).addPathPatterns("/innerapi/**");
registry.addInterceptor(new ChannelIdInterceptor()).addPathPatterns("/**"); registry.addInterceptor(new ChannelIdInterceptor()).addPathPatterns("/**");
} }
......
...@@ -51,7 +51,6 @@ public class ExceptionHandlingController implements IBaseController { ...@@ -51,7 +51,6 @@ public class ExceptionHandlingController implements IBaseController {
} }
@ExceptionHandler(Exception.class) @ExceptionHandler(Exception.class)
public JsonResult exceptionOccurs(Exception e) { public JsonResult exceptionOccurs(Exception e) {
HttpServletRequest request = getRequest(); HttpServletRequest request = getRequest();
......
...@@ -7,8 +7,9 @@ import org.springframework.web.context.request.RequestContextHolder; ...@@ -7,8 +7,9 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.*;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.getXSession;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.getXSessionFromRedis;
/** /**
* Created by Miraculous on 15/7/5. * Created by Miraculous on 15/7/5.
*/ */
...@@ -26,6 +27,10 @@ public interface IBaseController { ...@@ -26,6 +27,10 @@ public interface IBaseController {
return getXSession(); return getXSession();
} }
default SessionStruct getCurrentSessionFromRedis(){
return getXSessionFromRedis();
}
default HttpServletRequest getRequest() { default HttpServletRequest getRequest() {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
......
...@@ -79,7 +79,9 @@ public class ImageCaptchaController implements IBaseController { ...@@ -79,7 +79,9 @@ public class ImageCaptchaController implements IBaseController {
} }
/** 图片验证码验证*/ /**
* 图片验证码验证
*/
@CaptchaValidator @CaptchaValidator
@RequestMapping("/verification_image_code") @RequestMapping("/verification_image_code")
public JsonResult verificationImageCode() { public JsonResult verificationImageCode() {
......
package cn.quantgroup.xyqb.controller.external.motan;
import cn.quantgroup.xyqb.model.JsonResult;
import com.weibo.api.motan.common.MotanConstants;
import com.weibo.api.motan.util.MotanSwitcherUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/motan")
public class MotanController {
@RequestMapping("/enable/{key}")
public JsonResult reload(@PathVariable String key) {
if (StringUtils.equals(key, "b5140fb2-2c85-4b5a-abcf-3e97528014db")) {
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
return JsonResult.buildSuccessResult("加载成功", null);
}
return JsonResult.buildErrorStateResult("无效", null);
}
@RequestMapping("/disable/{key}")
public JsonResult disable(@PathVariable String key) {
if (StringUtils.equals(key, "b5140fb2-2c85-4b5a-abcf-3e97528014db")) {
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, false);
return JsonResult.buildSuccessResult("加载成功", null);
}
return JsonResult.buildErrorStateResult("无效", null);
}
}
package cn.quantgroup.xyqb.controller.external.motan;
import cn.quantgroup.motan.bean.*;
import cn.quantgroup.motan.retbean.*;
import cn.quantgroup.motan.service.UserMotanService;
import cn.quantgroup.motan.vo.UserSysResult;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.entity.enumerate.*;
import cn.quantgroup.xyqb.model.IdCardInfo;
import cn.quantgroup.xyqb.model.IdType;
import cn.quantgroup.xyqb.model.LoginProperties;
import cn.quantgroup.xyqb.model.UserRet;
import cn.quantgroup.xyqb.model.session.LoginInfo;
import cn.quantgroup.xyqb.model.session.SessionStruct;
import cn.quantgroup.xyqb.repository.IUserRepository;
import cn.quantgroup.xyqb.service.auth.IIdCardService;
import cn.quantgroup.xyqb.service.merchant.IMerchantService;
import cn.quantgroup.xyqb.service.session.ISessionService;
import cn.quantgroup.xyqb.service.sms.ISmsService;
import cn.quantgroup.xyqb.service.user.*;
import cn.quantgroup.xyqb.service.user.vo.UserDetailVO;
import cn.quantgroup.xyqb.service.wechat.IWechatService;
import cn.quantgroup.xyqb.util.PasswordUtil;
import cn.quantgroup.xyqb.util.ValidationUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weibo.api.motan.config.springsupport.annotation.MotanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
/**
* Created by 11 on 2017/2/27.
*/
@Slf4j
@MotanService(basicService = "baseServiceConfig")
public class MotanUserServiceImpl implements UserMotanService {
private static final ObjectMapper MAPPER = new ObjectMapper();
private final static Random random = new Random();
static {
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Autowired
private IIdCardService idCardService;
@Autowired
private IUserService userService;
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IUserRepository userRepository;
@Autowired
private ISmsService smsService;
@Autowired
private ILkbUserService lkbUserService;
@Autowired
private IMerchantService merchantService;
@Autowired
private ISessionService sessionService;
@Autowired
private IContactService contactService;
@Autowired
private IAddressService addressService;
@Autowired
private IUserExtInfoService userExtInfoService;
@Autowired
private IWechatService wechatService;
@Autowired
private IUserSpouseService userSpouseService;
@Override
public UserSysResult<XUser> findUserByPhoneNo(String phoneNo) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return returnErrorValue("手机号格式不正确");
}
User user = userService.findByPhoneInDb(phoneNo);
return returnSuccessValue(fromUser(user));
}
@Override
public UserSysResult<XUser> findUserByUuid(String uuid) {
if (StringUtils.isBlank(uuid)) {
return returnErrorValue("参数不能为空");
}
User user = userService.findByUuidInDb(uuid);
return returnSuccessValue(fromUser(user));
}
@Override
public UserSysResult<XUser> saveUser(UserBean userBean) {
if (null == userBean || !ValidationUtil.validatePhoneNo(userBean.getPhoneNo())) {
return returnErrorValue(userBean == null ? "要保存的用户对象不能为null" : "手机号不正确");
}
Timestamp now = new Timestamp(System.currentTimeMillis());
User user = userService.findByPhoneWithCache(userBean.getPhoneNo());
if (user == null) {
user = new User();
user.setCreatedAt(now);
user.setPhoneNo(userBean.getPhoneNo());
user.setEnable(true);
String password = userBean.getPassword();
if (StringUtils.isBlank(password)) {
password = String.valueOf(random.nextInt(899999) + 100000);
}
user.setPassword(PasswordUtil.MD5(password + Constants.PASSWORD_SALT));
} else {
if (StringUtils.isNotBlank(user.getPassword())) {
user.setPassword(PasswordUtil.MD5(userBean.getPassword() + Constants.PASSWORD_SALT));
}
}
user.setUpdatedAt(now);
user.setUuid(userBean.getUuid());
user.setRegisteredFrom(null==userBean.getRegisteredFrom()?0L:userBean.getRegisteredFrom());
User saveUser = userService.saveUser(user);
return returnSuccessValue(fromUser(saveUser));
}
@Override
public UserSysResult<XUserDetail> findUserDetailByUserId(Long userId) {
if (userId == null || userId < 1) {
return returnErrorValue("参数必须是正整数");
}
UserDetail userDetail = userDetailService.findByUserId(userId);
XUserDetail xUserDetail = fromUserDetail(userDetail);
return returnSuccessValue(xUserDetail);
}
private XUserDetail fromUserDetail(UserDetail userDetail) {
return userDetail == null ? null : userDetail.toXUserDetail();
}
private XUserDetail fromUserDetailVO(UserDetailVO userDetail) {
return userDetail == null ? null : userDetail.toXUserDetail();
}
private XUser fromUser(User user) {
return user == null ? null : user.toXUser();
}
@Override
public UserSysResult<XUser> findUserByUserId(Long id) {
if (id == null || id < 1) {
return returnErrorValue("参数必须是正整数");
}
User user = userService.findById(id);
return returnSuccessValue(fromUser(user));
}
@Override
public UserSysResult<XUserDetail> findUserDetailByPhone(String phoneNo) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return returnErrorValue("手机号格式不正确");
}
UserDetail userDetail = userDetailService.findByPhoneNo(phoneNo);
return returnSuccessValue(fromUserDetail(userDetail));
}
@Override
public UserSysResult<XUserDetail> updateUserDetail(UserDetailUpdateBean userDetailUpdateBean) {
if (null == userDetailUpdateBean) {
return returnErrorValue("要保存的用户详情对象不能为null");
}
UserDetail userDetail = new UserDetail();
if (null != userDetailUpdateBean.getId() && userDetailUpdateBean.getId() > 0L) {
userDetail.setId(userDetailUpdateBean.getId());
}
userDetail.setUserId(userDetailUpdateBean.getUserId());
userDetail.setName(userDetailUpdateBean.getName());
userDetail.setPhoneNo(userDetailUpdateBean.getPhoneNo());
userDetail.setIdNo(userDetailUpdateBean.getIdNo());
Timestamp time = new Timestamp(System.currentTimeMillis());
userDetail.setCreatedAt(time);
userDetail.setUpdatedAt(time);
userDetail.setIdType(IdType.ID_CARD);
try {
userDetail.setGender(idCardService.getIdCardInfo(userDetailUpdateBean.getIdNo()).getGender());
} catch (ParseException e) {
log.error("根据身份证获取性别出错,userDetailUpdateBean:{}", JSON.toJSONString(userDetailUpdateBean), e);
return returnErrorValue("根据身份证获取性别出错.");
}
userDetail.setEmail(userDetailUpdateBean.getEmail());
userDetail = userDetailService.saveUserDetail(userDetail);
if (userDetail != null) {
XUserDetail xUserDetail = convertObject(JSON.toJSONString(userDetail), new TypeReference<XUserDetail>() {
});
return returnSuccessValue(xUserDetail);
}
return returnErrorValue("保存失败");
}
@Override
public UserSysResult<XUserDetail> saveUserDetail(UserDetailSaveBean userDetailSaveBean) {
if (userDetailSaveBean == null) {
return returnErrorValue("数据不能为空");
}
Long userId = userDetailSaveBean.getUserId();
if (userId == null || userId == 0L) {
return returnErrorValue("用户id为空");
}
if (StringUtils.isBlank(userDetailSaveBean.getPhoneNo())) {
return returnErrorValue("用户手机号为空");
}
if (StringUtils.isBlank(userDetailSaveBean.getName())) {
return returnErrorValue("用户名为空");
}
if (StringUtils.isBlank(userDetailSaveBean.getIdNo())) {
return returnErrorValue("用户身份证为空");
}
Timestamp time = new Timestamp(System.currentTimeMillis());
UserDetail userDetail = userDetailService.findByUserId(userId);
if (userDetail == null) {
userDetail = new UserDetail();
userDetail.setUserId(userId);
userDetail.setCreatedAt(time);
userDetail.setUpdatedAt(time);
} else {
userDetail.setUpdatedAt(time);
}
userDetail.setName(userDetail.getName());
userDetail.setPhoneNo(userDetail.getPhoneNo());
userDetail.setIdType(IdType.ID_CARD);
if (StringUtils.isNotBlank(userDetail.getIdNo())) {
try {
userDetail.setGender(idCardService.getIdCardInfo(userDetail.getIdNo()).getGender());
} catch (ParseException e) {
log.error("根据身份证获取性别出错,身份证号码:{}", userDetail.getIdNo(), e);
return returnErrorValue("身份证信息出错");
}
userDetail.setIdNo(userDetail.getIdNo());
}
userDetail.setEmail(userDetail.getEmail());
userDetail = userDetailService.saveUserDetail(userDetail);
if (userDetail != null) {
return returnSuccessValue(fromUserDetail(userDetail));
}
return returnErrorValue("操作失败");
}
@Override
public UserSysResult<XLoginInfo> appLoginAndFetchLoginInfo(AppLoginParam appLoginParam, String requestIp) {
if (!ValidationUtil.validatePhoneNo(appLoginParam.getPhoneNo())) {
return returnErrorValue("账户或者密码错误");
}
log.info("第三方用户登录, loginFrom:{}, requestIp:{}", appLoginParam.getRegisterFrom(), requestIp);
User user = userService.findByPhoneInDb(appLoginParam.getPhoneNo());
if (user == null) {
user = register(appLoginParam.getRegisterFrom(), appLoginParam.getPhoneNo(), appLoginParam.getIdNo(), appLoginParam.getName());
}
if (user == null) {
return returnErrorValue("账户或者密码错误");
}
Merchant merchant = merchantService.findMerchantByName(appLoginParam.getKey());
if (merchant == null) {
return returnErrorValue("无效的商户");
}
LoginProperties loginProperties = new LoginProperties();
loginProperties.setChannelId(appLoginParam.getChannelId());
loginProperties.setMerchantName(merchant.getName());
loginProperties.setCreatedFrom(appLoginParam.getRegisterFrom());
loginProperties.setAppChannel(appLoginParam.getAppChannel());
SessionStruct sessionStruct = sessionService.createSessionAndPersist(user, loginProperties);
LoginInfo loginInfo = new LoginInfo();
loginInfo.setUser(UserRet.getUserRet(user));
loginInfo.setToken(sessionStruct.getSid());
LoginInfo.LoginContext context = new LoginInfo.LoginContext();
context.setChannelId(sessionStruct.getValues().getLoginProperties().getChannelId());
context.setCreatedFrom(sessionStruct.getValues().getLoginProperties().getCreatedFrom());
context.setAppChannel(appLoginParam.getAppChannel());
loginInfo.setLoginContext(context);
log.info("第三方用户获取信息登录成功, loginFrom:{}, phoneNo:{},appChannel:{}", appLoginParam.getRegisterFrom(), appLoginParam.getPhoneNo(), appLoginParam.getAppChannel());
XLoginInfo xLoginInfo = convertObject(JSON.toJSONString(loginInfo), new TypeReference<XLoginInfo>() {
});
return returnSuccessValue(xLoginInfo);
}
private <T> T convertObject(String json, TypeReference typeReference) {
try {
if (StringUtils.isEmpty(json)) {
return null;
}
return MAPPER.readValue(json, typeReference);
} catch (Exception ex) {
log.error("用户信息转换出错,json:{}", json, ex);
return null;
}
}
@Override
public void updateUserQQ(String qq, Long userId) {
if (StringUtils.isEmpty(qq) || userId == null || userId == 0L) {
log.error("QQ或用户id非法,不允许修改:qq{}, userid:{}", qq, userId);
return;
}
userDetailService.updateUserQQ(userId, qq);
}
@Override
public UserSysResult<List<XContact>> findContactsByUserId(Long userId) {
List<Contact> contacts = contactService.findByUserId(userId);
List<XContact> xContacts = convertObject(JSON.toJSONString(contacts), new TypeReference<List<XContact>>() {
});
return returnSuccessValue(xContacts);
}
@Override
public UserSysResult<List<XContact>> saveContacts(Long userId, List<XContact> contacts) {
if (null == userId || userId == 0L) {
return returnErrorValue("保存联系人列表失败,用户id为空");
}
if (CollectionUtils.isEmpty(contacts)) {
return returnErrorValue("保存联系人列表失败,列表为空");
}
//做一次类型转换,
String jsonContacts = JSON.toJSONString(contacts);
List<Contact> contactList = null;
try {
contactList = MAPPER.readValue(jsonContacts, new TypeReference<List<Contact>>() {
});
} catch (Exception e) {
log.error("联系人列表转换错误", e);
return returnErrorValue("联系人转换错误");
}
Timestamp now = new Timestamp(System.currentTimeMillis());
for (Contact c : contactList) {
c.setId(null);
c.setUserId(userId);
c.setRelation(c.getRelation() == null ? Relation.OTHER : c.getRelation());
c.setCreatedAt(now);
c.setUpdateAt(now);
}
List<Contact> result = contactService.save(contactList);
List<XContact> xResult = convertObject(JSON.toJSONString(result), new TypeReference<List<XContact>>() {
});
return returnSuccessValue(xResult);
}
@Override
public UserSysResult<XAddress> findAddressByUserId(Long userId) {
UserSysResult<XAddress> userSysResult = returnErrorValue(null);
Address address = addressService.findByUserId(userId);
if (null == address) {
return userSysResult;
}
XAddress xAddress = convertObject(JSON.toJSONString(address), new TypeReference<XAddress>() {
});
return returnSuccessValue(xAddress);
}
@Override
public UserSysResult<XAddress> saveAddress(Long userId, Long provinceCode, String province, Long cityCode, String city,
Long districtCode, String district, String address) {
if (null == userId || null == provinceCode || null == cityCode) {
return returnErrorValue("参数不能为空");
}
Address addressObj = addressService.findByUserId(userId);
if (addressObj == null) {
addressObj = new Address();
Timestamp now = new Timestamp(System.currentTimeMillis());
addressObj.setCreatedAt(now);
addressObj.setUpdateAt(now);
}
addressObj.setUserId(userId);
addressObj.setProvinceCode(provinceCode);
addressObj.setCityCode(cityCode);
addressObj.setCity(city);
addressObj.setDistrictCode(districtCode);
addressObj.setDistrict(district);
addressObj.setAddress(address);
addressObj.setProvince(province);
addressObj = addressService.save(addressObj);
XAddress xAddress = convertObject(JSON.toJSONString(addressObj), new TypeReference<XAddress>() {
});
return returnSuccessValue(xAddress);
}
@Override
public UserSysResult<XUserExtInfo> updateUserExtInfo(
Long userId, cn.quantgroup.motan.enums.IncomeEnum incomeEnum, cn.quantgroup.motan.enums.IncomeRangeEnum incomeRangeEnum,
cn.quantgroup.motan.enums.OccupationEnum occupationEnum, cn.quantgroup.motan.enums.EducationEnum educationEnum, Boolean hasCar,
Boolean hasSocialSecurity, Boolean hasHouse, Boolean hasCreditCard, cn.quantgroup.motan.enums.MaritalStatus maritalStatus) {
UserSysResult<XUserExtInfo> userSysResult = returnValue(null, null);
if (null == userId || 0L == userId) {
return returnErrorValue("用户id为空");
}
UserExtInfo info = userExtInfoService.findByUserId(userId);
if (info == null) {
Timestamp now = new Timestamp(System.currentTimeMillis());
info = new UserExtInfo();
info.setUserId(userId);
info.setCreatedAt(now);
info.setUpdateAt(now);
}
if (incomeEnum != null) {
info.setIncomeEnum(IncomeEnum.valueOf(incomeEnum.name()));
}
if (incomeRangeEnum != null) {
info.setIncomeRangeEnum(IncomeRangeEnum.valueOf(incomeRangeEnum.name()));
}
if (occupationEnum != null) {
info.setOccupationEnum(OccupationEnum.valueOf(occupationEnum.name()));
}
if (educationEnum != null) {
info.setEducationEnum(EducationEnum.valueOf(educationEnum.name()));
}
if (hasCar != null) {
info.setHasCar(hasCar);
}
if (hasCreditCard != null) {
info.setHasCreditCard(hasCreditCard);
}
if (hasHouse != null) {
info.setHasHouse(hasHouse);
}
if (maritalStatus != null) {
info.setMarryStatus(MaritalStatus.valueOf(maritalStatus.name()));
}
info = userExtInfoService.save(info);
XUserExtInfo userExtInfo = convertObject(JSON.toJSONString(info), new TypeReference<XUserExtInfo>() {
});
return returnSuccessValue(userExtInfo);
}
@Override
public UserSysResult<String> queryOpenIdByXyqbUserId(Long userId) {
if (userId == null || userId < 1) {
return returnErrorValue("用户id不能为空");
}
WechatUserInfo wechatUserInfo = wechatService.queryOpenIdByUserId(userId);
if (wechatUserInfo == null) {
return returnErrorValue("wechat信息为空");
}
return returnValue(wechatUserInfo.getOpenId(), "success");
}
@Override
public UserSysResult<Boolean> disableUser(Long userId) {
return null;
}
@Override
public UserSysResult<String> queryOpenIdByPhoneNo(String phoneNo) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return returnErrorValue("手机号格式不正确");
}
WechatUserInfo wechatUserInfo = wechatService.findWechatUserInfoByPhoneNo(phoneNo);
String openId = null == wechatUserInfo ? null : wechatUserInfo.getOpenId();
return returnSuccessValue(openId);
}
@Override
public UserSysResult<UserRegisterTrace> findRegisterTraceByPhoneNo(String phoneNo) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return returnErrorValue("手机号格式不正确");
}
return null;
}
@Override
public UserSysResult<XUserSpouse> findUserSpouseByUserId(Long userId) {
if (userId == null || userId == 0) {
return returnErrorValue("用户不能为空");
}
UserSpouse userSpouse = userSpouseService.findByUserId(userId);
if (userSpouse == null) {
userSpouse = new UserSpouse(userId);
userSpouse.setStatus(MaritalStatus.UNKNOWN);
}
return returnSuccessValue(fromUserSpouse(userSpouse));
}
private XUserSpouse fromUserSpouse(UserSpouse userSpouse) {
if (userSpouse == null) {
return null;
}
XUserSpouse xUserSpouse = new XUserSpouse();
xUserSpouse.setUserId(userSpouse.getUserId());
xUserSpouse.setSpousePhone(userSpouse.getSpousePhone());
xUserSpouse.setSpouseName(userSpouse.getSpouseName());
xUserSpouse.setCreatedAt(userSpouse.getCreatedAt());
xUserSpouse.setUpdateAt(userSpouse.getUpdateAt());
xUserSpouse.setStatus(cn.quantgroup.motan.enums.MaritalStatus.valueOf(userSpouse.getStatus().name()));
return xUserSpouse;
}
@Override
public UserSysResult<XUserExtInfo> findUserExtInfoByUserId(Long userId) {
return null;
}
@Override
public UserSysResult<List<XUserDetail>> queryUserDetailBySpecification(String name, String phoneNo, String idNo) {
List<UserDetailVO> userDetails = userDetailService.searchUserDetailList(name, phoneNo, idNo);
if (CollectionUtils.isEmpty(userDetails)) {
return null;
}
List<XUserDetail> xUserDetails = userDetails.stream().map(user -> fromUserDetailVO(user)).collect(Collectors.toList());
return returnSuccessValue(xUserDetails);
}
@Override
public UserSysResult<String> loginWithUuid(String uuid) {
return null;
}
@Override
public UserSysResult<Boolean> userImportCheck(String phoneNo, String registerFrom) {
return null;
}
@Override
public UserSysResult<XUserSpouse> saveUserSpouse(XUserSpouse xUserSpouse) {
if (xUserSpouse.getUserId() == null || xUserSpouse.getUserId() == 0) {
return returnErrorValue("用户不能为空");
}
cn.quantgroup.motan.enums.MaritalStatus status = xUserSpouse.getStatus();
String spousePhone = xUserSpouse.getSpousePhone();
String spouseName = xUserSpouse.getSpouseName();
if (xUserSpouse.getStatus() == cn.quantgroup.motan.enums.MaritalStatus.MARRIED) {
if (!ValidationUtil.validatePhoneNo(spousePhone)) {
return returnErrorValue("手机号格式错误");
}
if (StringUtils.isBlank(spouseName)) {
return returnErrorValue("配偶姓名不能为空");
}
}
UserSpouse userSpouse = userSpouseService.findByUserId(xUserSpouse.getUserId());
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
if (userSpouse == null) {
userSpouse = new UserSpouse(xUserSpouse.getUserId());
userSpouse.setCreatedAt(timestamp);
}
userSpouse.setSpouseName(status == cn.quantgroup.motan.enums.MaritalStatus.MARRIED ? spouseName : "");
userSpouse.setSpousePhone(status == cn.quantgroup.motan.enums.MaritalStatus.MARRIED ? spousePhone : "");
userSpouse.setStatus(MaritalStatus.valueOf(status.name()));
userSpouse.setUpdateAt(timestamp);
userSpouse = userSpouseService.save(userSpouse);
return returnSuccessValue(fromUserSpouse(userSpouse));
}
@Override
public UserSysResult<AppLoginResultBean> appLogin(AppLoginParam param) {
return null;
}
/**
* 封装返回结果.
*
* @param t
* @param message
* @param <T>
* @return
*/
private <T> UserSysResult<T> returnValue(T t, String message) {
UserSysResult<T> userSysResult = new UserSysResult();
userSysResult.setMsg(message);
/**
* 无返回结果时,返回的code和BusinessCode均是0001
*/
if (null == t) {
userSysResult.setBusinessCode("0001");
userSysResult.setCode("0001");
} else {
userSysResult.setBusinessCode("0000");
userSysResult.setCode("0000");
}
userSysResult.setData(t);
return userSysResult;
}
private <T> UserSysResult<T> returnErrorValue(String message) {
return returnValue(null, message);
}
private <T> UserSysResult<T> returnSuccessValue(T t) {
return returnValue(t, "");
}
/**
* 注册新用户
*
* @return
*/
private User register(Long registerFrom, String phoneNo, String idNo, String name) {
String randomCode = String.valueOf(random.nextInt(899999) + 100000);
String uuid = lkbUserService.registerApp(phoneNo, randomCode);
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
log.info("第三方登录用户,保存 User");
User user = new User();
user.setRegisteredFrom(registerFrom);
user.setUuid(uuid);
user.setEnable(true);
user.setPhoneNo(phoneNo);
user.setPassword(PasswordUtil.MD5(randomCode + Constants.PASSWORD_SALT));
user.setUpdatedAt(currentTime);
user.setCreatedAt(currentTime);
userRepository.saveAndFlush(user);
if (registerFrom != 645L && registerFrom !=900L) {
smsService.sendAfterRegister(phoneNo);
log.info("第三方登录用户注册成功, registerFrom:{}, phoneNo:{},idNo:{},name:{} 并且已发送短信通知", registerFrom, phoneNo, idNo, name);
}else if(registerFrom ==900L){
smsService.sendAfterRegister(phoneNo,"123");
log.info("第三方(聚美)登录用户注册成功, registerFrom:{}, phoneNo:{},idNo:{},name:{} 并且已发送短信通知", registerFrom, phoneNo, idNo, name);
}
if (StringUtils.isNotEmpty(idNo) && StringUtils.isNotEmpty(name)) {
IdCardInfo cardInfo;
try {
cardInfo = idCardService.getIdCardInfoWithExceptions(idNo);
UserDetail userDetail = new UserDetail();
userDetail.setIdNo(cardInfo.getIdNo());
userDetail.setPhoneNo(phoneNo);
userDetail.setName(name);
userDetail.setIdType(IdType.ID_CARD);
userDetail.setCreatedAt(currentTime);
userDetail.setUpdatedAt(currentTime);
userDetail.setUserId(user.getId());
userDetail.setGender(cardInfo.getGender());
userDetailService.saveUserDetail(userDetail);
lkbUserService.userUpdate(user.getUuid(), name, idNo);
} catch (Exception e) {
log.error("保存 UserDetail 出现异常", e);
}
}
return user;
}
}
...@@ -42,7 +42,7 @@ import static cn.quantgroup.xyqb.constant.UserConstant.USER_ERROR_OR_PASSWORD_ER ...@@ -42,7 +42,7 @@ import static cn.quantgroup.xyqb.constant.UserConstant.USER_ERROR_OR_PASSWORD_ER
public class AppController implements IBaseController { public class AppController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(AppController.class); private static final Logger LOGGER = LoggerFactory.getLogger(AppController.class);
private final static Random random = new Random();
@Autowired @Autowired
private ISessionService sessionService; private ISessionService sessionService;
@Autowired @Autowired
...@@ -53,7 +53,6 @@ public class AppController implements IBaseController { ...@@ -53,7 +53,6 @@ public class AppController implements IBaseController {
private IUserRepository userRepository; private IUserRepository userRepository;
@Autowired @Autowired
private ISmsService smsService; private ISmsService smsService;
@Autowired @Autowired
private IUserDetailService userDetailService; private IUserDetailService userDetailService;
@Autowired @Autowired
...@@ -61,8 +60,6 @@ public class AppController implements IBaseController { ...@@ -61,8 +60,6 @@ public class AppController implements IBaseController {
@Autowired @Autowired
private IMerchantService merchantService; private IMerchantService merchantService;
private final static Random random = new Random();
/** /**
* 第三方用户登录 * 第三方用户登录
*/ */
...@@ -186,14 +183,16 @@ public class AppController implements IBaseController { ...@@ -186,14 +183,16 @@ public class AppController implements IBaseController {
user.setCreatedAt(currentTime); user.setCreatedAt(currentTime);
userRepository.saveAndFlush(user); userRepository.saveAndFlush(user);
if (registerFrom != 645L) { if (registerFrom != 645L && registerFrom != 900L) {
smsService.sendAfterRegister(phoneNo); smsService.sendAfterRegister(phoneNo);
LOGGER.info("第三方登录用户注册成功, registerFrom:{}, phoneNo:{}, 并且已发送短信通知", registerFrom, phoneNo); LOGGER.info("第三方登录用户注册成功, registerFrom:{}, phoneNo:{}, 并且已发送短信通知", registerFrom, phoneNo);
}else if(registerFrom == 900L){
smsService.sendAfterRegister(phoneNo,"123");
LOGGER.info("第三方(聚美)登录用户注册成功, registerFrom:{}, phoneNo:{},idNo:{},name:{} 并且已发送短信通知", registerFrom, phoneNo, idNo, name);
} }
if (StringUtils.isNotEmpty(idNo) && StringUtils.isNotEmpty(name)) { if (StringUtils.isNotEmpty(idNo) && StringUtils.isNotEmpty(name)) {
LOGGER.info("第三方登录用户,保存 UserDetail"); LOGGER.info("第三方登录用户,保存 UserDetail");
IdCardInfo cardInfo; IdCardInfo cardInfo;
try { try {
cardInfo = idCardService.getIdCardInfoWithExceptions(idNo); cardInfo = idCardService.getIdCardInfoWithExceptions(idNo);
......
package cn.quantgroup.xyqb.controller.external.user; package cn.quantgroup.xyqb.controller.external.user;
import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.entity.*; import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.entity.enumerate.*; import cn.quantgroup.xyqb.entity.enumerate.*;
import cn.quantgroup.xyqb.model.*; import cn.quantgroup.xyqb.model.*;
...@@ -15,6 +16,7 @@ import org.apache.commons.lang3.StringUtils; ...@@ -15,6 +16,7 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
...@@ -23,13 +25,14 @@ import java.sql.Timestamp; ...@@ -23,13 +25,14 @@ import java.sql.Timestamp;
import java.text.ParseException; import java.text.ParseException;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* Created by Miraculous on 2016/12/19. * Created by Miraculous on 2016/12/19.
*/ */
@RestController @RestController
@RequestMapping("/innerapi") @RequestMapping("/innerapi")
public class InnerController { public class InnerController implements IBaseController {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(InnerController.class); private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(InnerController.class);
...@@ -72,6 +75,22 @@ public class InnerController { ...@@ -72,6 +75,22 @@ public class InnerController {
return JsonResult.buildSuccessResult("", userRet); return JsonResult.buildSuccessResult("", userRet);
} }
@RequestMapping("/user/getPhoneByUserIds")
public JsonResult findByIds(@RequestParam(value = "userIds") String userIdsString) {
LOGGER.info("批量查询用户的手机号列表, userIdsString:" + userIdsString);
if (StringUtils.isEmpty(userIdsString)) {
return JsonResult.buildErrorStateResult(null, null);
}
List<Long> userIds = JSONObject.parseObject(userIdsString, new TypeReference<List<Long>>() {
});
if(!CollectionUtils.isEmpty(userIds) && userIds.size()<=500) {
Map<Long, String> userIdAndPhoneMap = userService.findPhoneByIdsInDb(userIds);
return JsonResult.buildSuccessResult("", userIdAndPhoneMap);
}else {
return JsonResult.buildErrorStateResult("批量查询每次最多进行500条用户信息的查询",null);
}
}
@RequestMapping("/user/save") @RequestMapping("/user/save")
public JsonResult saveUser( public JsonResult saveUser(
String phoneNo, Long registeredFrom, Long createdAt, Long updatedAt, String phoneNo, Long registeredFrom, Long createdAt, Long updatedAt,
...@@ -240,6 +259,12 @@ public class InnerController { ...@@ -240,6 +259,12 @@ public class InnerController {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
Timestamp now = new Timestamp(System.currentTimeMillis()); Timestamp now = new Timestamp(System.currentTimeMillis());
convertContactList(userId, contacts, now);
List<Contact> result = contactService.save(contacts);
return JsonResult.buildSuccessResult(null, ContactRet.contacts2ContactRets(result));
}
private void convertContactList(Long userId, List<Contact> contacts, Timestamp now) {
for (Contact c : contacts) { for (Contact c : contacts) {
c.setId(null); c.setId(null);
c.setUserId(userId); c.setUserId(userId);
...@@ -247,8 +272,6 @@ public class InnerController { ...@@ -247,8 +272,6 @@ public class InnerController {
c.setCreatedAt(now); c.setCreatedAt(now);
c.setUpdateAt(now); c.setUpdateAt(now);
} }
List<Contact> result = contactService.save(contacts);
return JsonResult.buildSuccessResult(null, ContactRet.contacts2ContactRets(result));
} }
@RequestMapping("/address/search/user_id") @RequestMapping("/address/search/user_id")
...@@ -300,13 +323,13 @@ public class InnerController { ...@@ -300,13 +323,13 @@ public class InnerController {
return JsonResult.buildErrorStateResult("用户ID不能为空", null); return JsonResult.buildErrorStateResult("用户ID不能为空", null);
} }
UserExtInfo info = userExtInfoService.findByUserId(userId); UserExtInfo info = userExtInfoService.findByUserId(userId);
if (info == null) {
Timestamp now = new Timestamp(System.currentTimeMillis()); Timestamp now = new Timestamp(System.currentTimeMillis());
if (info == null) {
info = new UserExtInfo(); info = new UserExtInfo();
info.setUserId(userId); info.setUserId(userId);
info.setCreatedAt(now); info.setCreatedAt(now);
info.setUpdateAt(now);
} }
info.setUpdateAt(now);
if (incomeEnum != null) { if (incomeEnum != null) {
info.setIncomeEnum(incomeEnum); info.setIncomeEnum(incomeEnum);
} }
...@@ -337,6 +360,8 @@ public class InnerController { ...@@ -337,6 +360,8 @@ public class InnerController {
@RequestMapping("/user_detail/search_list") @RequestMapping("/user_detail/search_list")
public JsonResult searchUserDetailList(String name, String phoneNo, String idNo) { public JsonResult searchUserDetailList(String name, String phoneNo, String idNo) {
LOGGER.info("searchUserDetailList ,param.name:{},phone:{},idNo:{},ip:{}",name,phoneNo,idNo,getIp());
if (StringUtils.isBlank(name) && StringUtils.isBlank(phoneNo) && StringUtils.isBlank(idNo)) { if (StringUtils.isBlank(name) && StringUtils.isBlank(phoneNo) && StringUtils.isBlank(idNo)) {
return JsonResult.buildErrorStateResult("至少必须满足一个条件不为空", null); return JsonResult.buildErrorStateResult("至少必须满足一个条件不为空", null);
} }
...@@ -353,7 +378,7 @@ public class InnerController { ...@@ -353,7 +378,7 @@ public class InnerController {
if (userExtInfo == null) { if (userExtInfo == null) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
return JsonResult.buildSuccessResult("success", UserExtInfoRet.getUserExtInfoRet(userExtInfo)); return JsonResult.buildSuccessResult(null, UserExtInfoRet.getUserExtInfoRet(userExtInfo));
} }
@RequestMapping("/user/query/openId") @RequestMapping("/user/query/openId")
...@@ -439,4 +464,29 @@ public class InnerController { ...@@ -439,4 +464,29 @@ public class InnerController {
return JsonResult.buildSuccessResult(null, UserSpouseRet.getUserSpouseRet(userSpouse)); return JsonResult.buildSuccessResult(null, UserSpouseRet.getUserSpouseRet(userSpouse));
} }
/**
* 重置密码接口,供内部人员使用(例如绝影)
* @param key
* @param phone
* @return
*/
@RequestMapping("/user/password/reset/{key}/{phone}")
public JsonResult resetPassword(@PathVariable("key")String key,@PathVariable("phone")String phone) {
LOGGER.info("密码重置请求,phone:[{}]",phone);
if(StringUtils.isBlank(key)){
return JsonResult.buildErrorStateResult("用户密码重置失败.", null);
}
if(!"ecf75c1f-2ccb-4661-8e4b-2874c0f45a2b".equalsIgnoreCase(key)){
LOGGER.error("密码重置失败,key错误!@!,phone:[{}]", phone);
return JsonResult.buildErrorStateResult("用户密码重置失败.", null);
}
try {
userService.resetPassword(phone, "123456"); //默认重置的密码是123456
return JsonResult.buildSuccessResult("用户密码已重置.", "null");
}catch (Exception e){
LOGGER.error("密码重置失败,phone[{}],err:[{}]",phone, e);
}
return JsonResult.buildErrorStateResult("用户密码重置失败.", null);
}
} }
\ No newline at end of file
...@@ -57,12 +57,14 @@ public class Jr58Controller implements ApplicationEventPublisherAware { ...@@ -57,12 +57,14 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
private static final Logger LOGGER = LoggerFactory.getLogger(Jr58Controller.class); private static final Logger LOGGER = LoggerFactory.getLogger(Jr58Controller.class);
private static final String ENTRY_POINT_URL_TEMPLATE = "%s/app-landing?registerFrom=175&channelId=1&token=%s"; private static final String ENTRY_POINT_URL_TEMPLATE = "%s/app-landing?registerFrom=175&channelId=1&token=%s";
private static List<String> authorizationTypeList= new ArrayList<>(); private static List<String> authorizationTypeList = new ArrayList<>();
static { static {
//授权类型 //授权类型
authorizationTypeList.add("1"); authorizationTypeList.add("1");
authorizationTypeList.add("2"); authorizationTypeList.add("2");
} }
@Value("${xyqb.url}") @Value("${xyqb.url}")
private String xyqbUrl; private String xyqbUrl;
...@@ -102,13 +104,13 @@ public class Jr58Controller implements ApplicationEventPublisherAware { ...@@ -102,13 +104,13 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
result.put("errorcode", Jr58.ERROR_PHONE_NUMBER); result.put("errorcode", Jr58.ERROR_PHONE_NUMBER);
return result; return result;
} }
if(StringUtils.isBlank(param.getAccount())){ if (StringUtils.isBlank(param.getAccount())) {
LOGGER.error("58金融授权账号-account={}",param.getAccount()); LOGGER.error("58金融授权账号-account={}", param.getAccount());
result.put("errorcode", Jr58.ERROR_ACCOUNT); result.put("errorcode", Jr58.ERROR_ACCOUNT);
return result; return result;
} }
if(StringUtils.isBlank(param.getAuthorizationType()) || !authorizationTypeList.contains(param.getAuthorizationType())){ if (StringUtils.isBlank(param.getAuthorizationType()) || !authorizationTypeList.contains(param.getAuthorizationType())) {
LOGGER.error("58金融授权类型-authorization={} ",param.getAuthorizationType()); LOGGER.error("58金融授权类型-authorization={} ", param.getAuthorizationType());
result.put("errorcode", Jr58.ERROR_AUTH_TYPE); result.put("errorcode", Jr58.ERROR_AUTH_TYPE);
return result; return result;
} }
...@@ -120,16 +122,16 @@ public class Jr58Controller implements ApplicationEventPublisherAware { ...@@ -120,16 +122,16 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
return result; return result;
} }
try { try {
if(StringUtils.isNotBlank(param.getWbUserName())){ if (StringUtils.isNotBlank(param.getWbUserName())) {
param.setWbUserName(URLDecoder.decode(param.getWbUserName(), "UTF-8")); param.setWbUserName(URLDecoder.decode(param.getWbUserName(), "UTF-8"));
} }
if(StringUtils.isNotBlank(param.getEmail())){ if (StringUtils.isNotBlank(param.getEmail())) {
param.setEmail(URLDecoder.decode(param.getEmail(), "UTF-8")); param.setEmail(URLDecoder.decode(param.getEmail(), "UTF-8"));
} }
if(StringUtils.isNotBlank(param.getName())){ if (StringUtils.isNotBlank(param.getName())) {
param.setName(URLDecoder.decode(param.getName(), "UTF-8")); param.setName(URLDecoder.decode(param.getName(), "UTF-8"));
} }
if(StringUtils.isNotBlank(param.getInfo())){ if (StringUtils.isNotBlank(param.getInfo())) {
param.setInfo(URLDecoder.decode(param.getInfo(), "UTF-8")); param.setInfo(URLDecoder.decode(param.getInfo(), "UTF-8"));
} }
...@@ -147,7 +149,7 @@ public class Jr58Controller implements ApplicationEventPublisherAware { ...@@ -147,7 +149,7 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("58金融运营商授权状态更新失败,异常信息如下所示:error={}", e.getMessage(), e); LOGGER.error("58金融运营商授权状态更新失败,异常信息如下所示:error={}", e.getMessage(), e);
} }
jr58Service.pushAuthorizationStatus(uuid,param.getAccount(),param.getAuthorizationType()); jr58Service.pushAuthorizationStatus(uuid, param.getAccount(), param.getAuthorizationType());
LOGGER.info("58金融运营商授权状态更新结束"); LOGGER.info("58金融运营商授权状态更新结束");
result.put("customerid", uuid); result.put("customerid", uuid);
result.put("success", true); result.put("success", true);
...@@ -190,9 +192,9 @@ public class Jr58Controller implements ApplicationEventPublisherAware { ...@@ -190,9 +192,9 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
UuidPhoneMapping phoneMapping = uuidPhoneMappingService.findByUuid(uuid); UuidPhoneMapping phoneMapping = uuidPhoneMappingService.findByUuid(uuid);
String phoneNo = null; String phoneNo = null;
if(phoneMapping != null){ if (phoneMapping != null) {
phoneNo = phoneMapping.getPhoneNo(); phoneNo = phoneMapping.getPhoneNo();
}else{ } else {
LOGGER.error("58金融运营商授权数据导入接口 - uuid对应的UuidPhoneMapping为空"); LOGGER.error("58金融运营商授权数据导入接口 - uuid对应的UuidPhoneMapping为空");
} }
// 手机号在新系统中存在,说明之前已经注册过 // 手机号在新系统中存在,说明之前已经注册过
...@@ -216,57 +218,58 @@ public class Jr58Controller implements ApplicationEventPublisherAware { ...@@ -216,57 +218,58 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
/** /**
* 58金融运营商授权数据导入接口 * 58金融运营商授权数据导入接口
*
* @param authorizationData 入参 * @param authorizationData 入参
* @return JsonResult * @return JsonResult
*/ */
@RequestMapping(value = "/import_authorization_data", method= RequestMethod.POST) @RequestMapping(value = "/import_authorization_data", method = RequestMethod.POST)
public JsonResult importAuthorizationData(@RequestBody Jr58Authorization authorizationData) { public JsonResult importAuthorizationData(@RequestBody Jr58Authorization authorizationData) {
String authorizationDataStr = null; String authorizationDataStr = null;
LOGGER.info("推送的运营商数据userId={}",authorizationData.getUserId()); LOGGER.info("推送的运营商数据userId={}", authorizationData.getUserId());
LOGGER.info("推送的运营商数据sourceFrom={}",authorizationData.getSourceFrom()); LOGGER.info("推送的运营商数据sourceFrom={}", authorizationData.getSourceFrom());
if(StringUtils.isEmpty(authorizationData.getAuthorizationData())){ if (StringUtils.isEmpty(authorizationData.getAuthorizationData())) {
LOGGER.error("58金融运营商授权数据导入接口 - authorizationData不能为空"); LOGGER.error("58金融运营商授权数据导入接口 - authorizationData不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - authorizationData不能为空",null); return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - authorizationData不能为空", null);
} }
//try { //try {
authorizationDataStr = JR58GzipUtil.bytesTogzip(Base64.decodeBase64(authorizationData.getAuthorizationData()), "utf-8"); authorizationDataStr = JR58GzipUtil.bytesTogzip(Base64.decodeBase64(authorizationData.getAuthorizationData()), "utf-8");
//authorizationDataStr = JR58GzipUtil.bytesTogzip(new BASE64Decoder().decodeBuffer(authorizationData.getAuthorizationData()), "utf-8"); //authorizationDataStr = JR58GzipUtil.bytesTogzip(new BASE64Decoder().decodeBuffer(authorizationData.getAuthorizationData()), "utf-8");
LOGGER.info("推送的运营商数据authorizationDataStr={}",authorizationDataStr); LOGGER.info("推送的运营商数据authorizationDataStr={}", authorizationDataStr);
/*} catch (IOException e) { /*} catch (IOException e) {
LOGGER.error("58金融生成借款申请失败,base64转换失败"); LOGGER.error("58金融生成借款申请失败,base64转换失败");
return JsonResult.buildErrorStateResult("58金融导入运营商授权数据失败",null); return JsonResult.buildErrorStateResult("58金融导入运营商授权数据失败",null);
}*/ }*/
//authorizationData.setOperator_data(new Gson().fromJson(authorizationDataStr, Jr58Authorization.OperatorData.class)); //authorizationData.setOperator_data(new Gson().fromJson(authorizationDataStr, Jr58Authorization.OperatorData.class));
authorizationData.setOperator_data(JSONObject.parseObject(authorizationDataStr, Jr58Authorization.OperatorData.class)); authorizationData.setOperator_data(JSONObject.parseObject(authorizationDataStr, Jr58Authorization.OperatorData.class));
if(authorizationData == null){ if (authorizationData == null) {
LOGGER.error("58金融运营商授权数据导入接口 - 入参不完整"); LOGGER.error("58金融运营商授权数据导入接口 - 入参不完整");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入 - 入参不完整",null); return JsonResult.buildErrorStateResult("58金融运营商授权数据导入 - 入参不完整", null);
} }
String userId = authorizationData.getUserId(); String userId = authorizationData.getUserId();
String phoneNo= null; String phoneNo = null;
if(authorizationData.getOperator_data() != null && authorizationData.getOperator_data().getOriginalData() != null){ if (authorizationData.getOperator_data() != null && authorizationData.getOperator_data().getOriginalData() != null) {
phoneNo= authorizationData.getOperator_data().getOriginalData().getPhone(); phoneNo = authorizationData.getOperator_data().getOriginalData().getPhone();
} }
if(phoneNo == null){ if (phoneNo == null) {
LOGGER.info("推送的运营商数据authorizationData={}",authorizationData.getAuthorizationData()); LOGGER.info("推送的运营商数据authorizationData={}", authorizationData.getAuthorizationData());
LOGGER.error("58金融运营商授权数据导入接口 - phoneNo不能为空"); LOGGER.error("58金融运营商授权数据导入接口 - phoneNo不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整",null); return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整", null);
} }
LOGGER.info("收到来自58金融运营商授权导入请求, userId:{}", userId); LOGGER.info("收到来自58金融运营商授权导入请求, userId:{}", userId);
if (StringUtils.isEmpty(authorizationData.getSourceFrom())) { if (StringUtils.isEmpty(authorizationData.getSourceFrom())) {
LOGGER.error("58金融运营商授权数据导入接口 - sourceFrom不能为空"); LOGGER.error("58金融运营商授权数据导入接口 - sourceFrom不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - sourceFrom不能为空",null); return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - sourceFrom不能为空", null);
} }
if (StringUtils.isEmpty(userId)) { if (StringUtils.isEmpty(userId)) {
LOGGER.error("58金融运营商授权数据导入接口 - userId不能为空"); LOGGER.error("58金融运营商授权数据导入接口 - userId不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - userId不能为空",null); return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - userId不能为空", null);
} }
if("1".equals(authorizationData.getSourceFrom()) && (null== authorizationData.getOperator_data() if ("1".equals(authorizationData.getSourceFrom()) && (null == authorizationData.getOperator_data()
|| null == authorizationData.getOperator_data().getOriginalData())){ || null == authorizationData.getOperator_data().getOriginalData())) {
LOGGER.error("58金融运营商授权数据导入接口 - 入参不完整, sourceFrom : {}, authorizationDataStr={}", authorizationData.getSourceFrom(),authorizationDataStr); LOGGER.error("58金融运营商授权数据导入接口 - 入参不完整, sourceFrom : {}, authorizationDataStr={}", authorizationData.getSourceFrom(), authorizationDataStr);
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整",null); return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整", null);
} }
String uuid = userId.toLowerCase(); String uuid = userId.toLowerCase();
...@@ -276,13 +279,13 @@ public class Jr58Controller implements ApplicationEventPublisherAware { ...@@ -276,13 +279,13 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
// 用户不存在 // 用户不存在
if (user == null) { if (user == null) {
LOGGER.error("58金融运营商授权数据导入接口 - 用户不存在,userId=[{}]", userId); LOGGER.error("58金融运营商授权数据导入接口 - 用户不存在,userId=[{}]", userId);
return JsonResult.buildErrorStateResult("用户不存在,userId="+userId,null); return JsonResult.buildErrorStateResult("用户不存在,userId=" + userId, null);
} }
// 推送授权to风控 // 推送授权to风控
jr58Service.pushAuthorizationData(authorizationData); jr58Service.pushAuthorizationData(authorizationData);
LOGGER.info("58金融运营商数据导入结束"); LOGGER.info("58金融运营商数据导入结束");
return JsonResult.buildSuccessResult("success",null); return JsonResult.buildSuccessResult("success", null);
} }
} }
...@@ -4,7 +4,6 @@ import cn.quantgroup.xyqb.entity.User; ...@@ -4,7 +4,6 @@ import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserDetail; import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.model.JsonResult; import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.UserModel; import cn.quantgroup.xyqb.model.UserModel;
import cn.quantgroup.xyqb.repository.IUserDetailRepository;
import cn.quantgroup.xyqb.service.user.IUserDetailService; import cn.quantgroup.xyqb.service.user.IUserDetailService;
import cn.quantgroup.xyqb.service.user.IUserService; import cn.quantgroup.xyqb.service.user.IUserService;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
......
...@@ -5,19 +5,15 @@ import cn.quantgroup.xyqb.controller.IBaseController; ...@@ -5,19 +5,15 @@ import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.entity.Merchant; import cn.quantgroup.xyqb.entity.Merchant;
import cn.quantgroup.xyqb.entity.User; import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WechatUserInfo; import cn.quantgroup.xyqb.entity.WechatUserInfo;
import cn.quantgroup.xyqb.event.UserinfoChangedEvent;
import cn.quantgroup.xyqb.model.AuthBean; import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.webchat.AccessTokenResponse; import cn.quantgroup.xyqb.model.webchat.AccessTokenResponse;
import cn.quantgroup.xyqb.service.merchant.IMerchantService; import cn.quantgroup.xyqb.service.merchant.IMerchantService;
import cn.quantgroup.xyqb.service.page.IPageService;
import cn.quantgroup.xyqb.service.session.ISessionService; import cn.quantgroup.xyqb.service.session.ISessionService;
import cn.quantgroup.xyqb.service.user.IUserService; import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.service.wechat.IWechatService; import cn.quantgroup.xyqb.service.wechat.IWechatService;
import cn.quantgroup.xyqb.util.EmojiUtil; import cn.quantgroup.xyqb.util.EmojiUtil;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.TypeReference;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
...@@ -34,6 +30,7 @@ import javax.servlet.http.HttpServletResponse; ...@@ -34,6 +30,7 @@ import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap;
/** /**
* Created by 11 on 2017/1/17. * Created by 11 on 2017/1/17.
...@@ -64,6 +61,8 @@ public class WeChatController implements IBaseController { ...@@ -64,6 +61,8 @@ public class WeChatController implements IBaseController {
@Value("${xyqb-user.ui}") @Value("${xyqb-user.ui}")
private String userUIAddr; private String userUIAddr;
@Value("${xyqb.user.domain}")
private String userDomainStr;
/** /**
* 开发者资质认证,有必要吗? * 开发者资质认证,有必要吗?
...@@ -315,6 +314,7 @@ public class WeChatController implements IBaseController { ...@@ -315,6 +314,7 @@ public class WeChatController implements IBaseController {
// 已经关联了用户 // 已经关联了用户
// create session, 登进去,该怎么玩怎么玩。 // create session, 登进去,该怎么玩怎么玩。
String redirectUrl = createUserSession(user, merchant, redirect, schema, registerFrom); String redirectUrl = createUserSession(user, merchant, redirect, schema, registerFrom);
LOGGER.info("Location:[{}]",redirectUrl);
response.setHeader("Location", redirectUrl); response.setHeader("Location", redirectUrl);
response.setStatus(301); response.setStatus(301);
} }
...@@ -322,12 +322,8 @@ public class WeChatController implements IBaseController { ...@@ -322,12 +322,8 @@ public class WeChatController implements IBaseController {
LOGGER.error("发生异常", ex); LOGGER.error("发生异常", ex);
throw ex; throw ex;
} }
} }
/** /**
* 通过redirect_url获取code * 通过redirect_url获取code
* *
...@@ -357,7 +353,7 @@ public class WeChatController implements IBaseController { ...@@ -357,7 +353,7 @@ public class WeChatController implements IBaseController {
// welcome 首次登录 // welcome 首次登录
if (userInfoInDb == null) { if (userInfoInDb == null) {
// 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面 // 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面
if(StringUtils.isNotBlank(userInfo.getNickName())) { if (StringUtils.isNotBlank(userInfo.getNickName())) {
String nickName = EmojiUtil.filter(userInfo.getNickName()); String nickName = EmojiUtil.filter(userInfo.getNickName());
userInfo.setNickName(nickName); userInfo.setNickName(nickName);
} }
...@@ -378,52 +374,55 @@ public class WeChatController implements IBaseController { ...@@ -378,52 +374,55 @@ public class WeChatController implements IBaseController {
// 已经关联了用户 // 已经关联了用户
// create session, 登进去,该怎么玩怎么玩。 // create session, 登进去,该怎么玩怎么玩。
String redirectUrl = createUserSession(user, merchant, "", schema, Constants.Channel.WECHAT); String redirectUrl = createUserSession(user, merchant, "", schema, Constants.Channel.WECHAT);
LOGGER.info("Location={}", redirectUrl); LOGGER.info("Location=[{}]", redirectUrl);
response.setHeader("Location", redirectUrl); response.setHeader("Location", redirectUrl);
response.setStatus(301); response.setStatus(301);
} }
private String createUserSession(User user, Merchant merchant, String redirect, String schema, Long registerFrom) { private String createUserSession(User user, Merchant merchant, String redirect, String schema, Long registerFrom) {
//TODO 临时紧急上线修改的.下次上线的时候修复一下,不能这样写. //String url = "http://passport.xyqb.com";
String url = "http://passport.xyqb.com"; String url = "http://"+userDomainStr;
if("https:".equals(schema)) { if ("https:".equals(schema)) {
url = "https://passport.xyqb.com"; url = "https://"+userDomainStr;
} }
if(StringUtils.isEmpty(redirect) || "redirect".equals(redirect)) { if (StringUtils.isEmpty(redirect) || "redirect".equals(redirect)) {
LOGGER.info("微信登录:redirect为null,走正常流程."); LOGGER.info("微信登录:redirect为null,走正常流程.");
if ("baitiao".equals(merchant.getName())) { if ("baitiao".equals(merchant.getName())) {
return loginInWechatWithSessionCreated(user, merchant, "cashTarget5", Constants.Channel.BAITIAO, url, Constants.Channel.WECHAT); return loginInWechatWithSessionCreated(user, merchant, "cashTarget5", Constants.Channel.BAITIAO, url, Constants.Channel.WECHAT);
} else if("wechat-pay".equals(merchant.getName())){ } else if ("wechat-pay".equals(merchant.getName())) {
AuthBean authBean = sessionService.createSession(Constants.Channel.WECHAT, registerFrom, "", user, merchant); AuthBean authBean = sessionService.createSession(Constants.Channel.WECHAT, registerFrom, "", user, merchant);
return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom+ "&channelId=" + Constants.Channel.WECHAT +"&key=" + merchant.getName() +"&target=cashTarget5" ; return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom + "&channelId=" + Constants.Channel.WECHAT + "&key=" + merchant.getName() + "&target=cashTarget5";
}else { } else {
return loginInWechatWithSessionCreated(user, merchant, "cashTarget4", 1L, url, registerFrom); return loginInWechatWithSessionCreated(user, merchant, "cashTarget4", 1L, url, registerFrom);
} }
} else if("local".equals(redirect)){ } else if ("local".equals(redirect)) {
LOGGER.info("微信登录:redirect不为null,创建session跳到指定前端页面."); LOGGER.info("微信登录:redirect不为null,创建session跳到指定前端页面.");
AuthBean authBean = sessionService.createSession(Constants.Channel.WECHAT, Constants.Channel.WECHAT, "", user, merchant); AuthBean authBean = sessionService.createSession(Constants.Channel.WECHAT, Constants.Channel.WECHAT, "", user, merchant);
LOGGER.info("微信登录:跳转地址{}", url + "/weixin/callback?phoneNo=" + user.getPhoneNo() + "&token=" + authBean.getToken()); LOGGER.info("微信登录:跳转地址{}", url + "/weixin/callback?phoneNo=" + user.getPhoneNo() + "&token=" + authBean.getToken());
Long channelId = "baitiao".equals(merchant.getName()) ? 222L : 1L; Long channelId = "baitiao".equals(merchant.getName()) ? 222L : 1L;
String target = "baitiao".equals(merchant.getName()) ? "cashTarget5" : "cashTarget4"; String target = "baitiao".equals(merchant.getName()) ? "cashTarget5" : "cashTarget4";
return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom+ return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom +
"&channelId=" + channelId +"&key=" + merchant.getName() +"&target=" + target + "&isWechat=true"; "&channelId=" + channelId + "&key=" + merchant.getName() + "&target=" + target + "&isWechat=true";
} }
return null; return null;
} }
private String loginInWechatWithSessionCreated(User user, Merchant merchant, String target, Long channelId, String url, Long registerFrom) { private String loginInWechatWithSessionCreated(User user, Merchant merchant, String target, Long channelId, String url, Long registerFrom) {
AuthBean authBean = sessionService.createSession(channelId, registerFrom, "", user, merchant); AuthBean authBean = sessionService.createSession(channelId, registerFrom, "", user, merchant);
return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom+ "&channelId=" + channelId +"&key=" + merchant.getName() +"&target=" + target; return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom + "&channelId=" + channelId + "&key=" + merchant.getName() + "&target=" + target;
} }
private void redirectWechatLoginUrlWithoutLogin(HttpServletResponse response, Merchant merchant, WechatUserInfo userInfo, Long registerFrom) { private void redirectWechatLoginUrlWithoutLogin(HttpServletResponse response, Merchant merchant, WechatUserInfo userInfo, Long registerFrom) {
String redirectUrl = assembleWechatRedirectUrl(merchant, userInfo, registerFrom); String redirectUrl = assembleWechatRedirectUrl(merchant, userInfo, registerFrom);
LOGGER.info("redirectWechatLoginUrlWithoutLogin redirectUrl:[{}]",redirectUrl);
response.setHeader("Location", redirectUrl); response.setHeader("Location", redirectUrl);
response.setStatus(301); response.setStatus(301);
} }
private void redirectNormalUrl(HttpServletResponse response, Merchant merchant, Long registerFrom) { private void redirectNormalUrl(HttpServletResponse response, Merchant merchant, Long registerFrom) {
String redirectUrl = assembleNormalRedirectUrl(merchant, registerFrom); String redirectUrl = assembleNormalRedirectUrl(merchant, registerFrom);
LOGGER.info("redirectNormalUrl redirectUrl:[{}]",redirectUrl);
response.setHeader("Location", redirectUrl); response.setHeader("Location", redirectUrl);
response.setStatus(301); response.setStatus(301);
} }
......
package cn.quantgroup.xyqb.controller.internal.login; package cn.quantgroup.xyqb.controller.internal.login;
import cn.quantgroup.xyqb.controller.IBaseController; import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.JsonResult; import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.UserRet; import cn.quantgroup.xyqb.model.UserRet;
import cn.quantgroup.xyqb.model.session.LoginInfo; import cn.quantgroup.xyqb.model.session.LoginInfo;
import cn.quantgroup.xyqb.model.session.SessionStruct; import cn.quantgroup.xyqb.model.session.SessionStruct;
import cn.quantgroup.xyqb.service.http.IHttpService;
import cn.quantgroup.xyqb.service.user.IUserService;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/** /**
* Created by Miraculous on 2016/12/30. * Created by Miraculous on 2016/12/30.
*/ */
@RestController @RestController
@RequestMapping("/auth") @RequestMapping("/auth")
@Slf4j
public class AuthInfoController implements IBaseController { public class AuthInfoController implements IBaseController {
@Value("${xyqb.auth.url}")
private String xyqbAuthUrl;
@Autowired
private IHttpService httpService;
@Autowired
private IUserService userService;
@RequestMapping("/info/login") @RequestMapping("/info/login")
public JsonResult loginInfo() { public JsonResult loginInfo() {
SessionStruct sessionStruct = getSessionStruct(); SessionStruct sessionStruct = getCurrentSessionFromRedis();
if(null != sessionStruct) {
log.info("从用户中心获取到了用户登录信息:phone:[{}]",sessionStruct.getValues().getUser().getPhoneNo());
LoginInfo loginInfo = new LoginInfo(); LoginInfo loginInfo = new LoginInfo();
loginInfo.setUser(UserRet.getUserRet(sessionStruct.getValues().getUser())); loginInfo.setUser(UserRet.getUserRet(sessionStruct.getValues().getUser()));
loginInfo.setToken(sessionStruct.getSid()); loginInfo.setToken(sessionStruct.getSid());
...@@ -26,7 +56,35 @@ public class AuthInfoController implements IBaseController { ...@@ -26,7 +56,35 @@ public class AuthInfoController implements IBaseController {
context.setCreatedFrom(sessionStruct.getValues().getLoginProperties().getCreatedFrom()); context.setCreatedFrom(sessionStruct.getValues().getLoginProperties().getCreatedFrom());
context.setAppChannel(sessionStruct.getValues().getLoginProperties().getAppChannel()); context.setAppChannel(sessionStruct.getValues().getLoginProperties().getAppChannel());
loginInfo.setLoginContext(context); loginInfo.setLoginContext(context);
return JsonResult.buildSuccessResult("", loginInfo); //有ThreadLocal不释放的问题,不可再使用原来方式了
}else {
// 函谷关去查token 返回值高仿
log.info("去向函谷关查询用户信息");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("x-auth-token");
if(StringUtils.isBlank(token) ||token.length() != 36){
return JsonResult.buildErrorStateResult("用户未登录",null);
}
String checkUrl = xyqbAuthUrl+"/innerapi/is_login";
ImmutableMap<String, String> headMap = ImmutableMap.of("x-auth-token", token);
String response = httpService.get(checkUrl, headMap, null);
log.info("去向函谷关查询用户信息,response:[{}]",response);
JsonResult result = JSONObject.parseObject(response, JsonResult.class);
if (result == null || !"0000".equals(result.getCode()) || !"0000".equals(result.getBusinessCode())) {
return JsonResult.buildErrorStateResult("用户未登录",null);
}
String phoneNo = ((Map<String, String>) result.getData()).get("phoneNo");
User user = userService.findByPhoneWithCache(phoneNo);
LoginInfo loginInfo = new LoginInfo();
loginInfo.setUser(UserRet.getUserRet(user));
loginInfo.setToken(token);
LoginInfo.LoginContext context = new LoginInfo.LoginContext();
context.setChannelId(null);
context.setCreatedFrom(user.getRegisteredFrom());
context.setAppChannel("");
loginInfo.setLoginContext(context);
return JsonResult.buildSuccessResult("", loginInfo); return JsonResult.buildSuccessResult("", loginInfo);
} }
}
} }
...@@ -38,7 +38,7 @@ public class PlatformAPIController implements IBaseController { ...@@ -38,7 +38,7 @@ public class PlatformAPIController implements IBaseController {
if (null == merchant) { if (null == merchant) {
return JsonResult.buildErrorStateResult("", null); return JsonResult.buildErrorStateResult("", null);
} }
MerchantConfig config= merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl"); MerchantConfig config = merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl");
if (null == config) { if (null == config) {
return JsonResult.buildSuccessResult("", null); return JsonResult.buildSuccessResult("", null);
} }
...@@ -72,5 +72,4 @@ public class PlatformAPIController implements IBaseController { ...@@ -72,5 +72,4 @@ public class PlatformAPIController implements IBaseController {
} }
} }
...@@ -27,20 +27,16 @@ import java.util.concurrent.TimeUnit; ...@@ -27,20 +27,16 @@ import java.util.concurrent.TimeUnit;
public class SmsController { public class SmsController {
private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class); private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class);
private static final Random random = new Random();
private static final long EXPIRE_MINUTES = 10;
@Autowired @Autowired
private ISmsService smsService; private ISmsService smsService;
@Autowired @Autowired
@Qualifier("stringRedisTemplate") @Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate; private RedisTemplate<String, String> redisTemplate;
@Value("${sms.is.debug}") @Value("${sms.is.debug}")
private boolean smsIsDebug; private boolean smsIsDebug;
private static final Random random = new Random();
private static final long EXPIRE_MINUTES = 10;
/** /**
* 短信验证码: for H5 * 短信验证码: for H5
* 使用 @FPLock 注解并加入自定义限制参数, 做针对手机号的发送次数限制 * 使用 @FPLock 注解并加入自定义限制参数, 做针对手机号的发送次数限制
......
...@@ -26,11 +26,11 @@ import java.text.ParseException; ...@@ -26,11 +26,11 @@ import java.text.ParseException;
@RequestMapping("/user_detail") @RequestMapping("/user_detail")
public class UserDetailController implements IBaseController { public class UserDetailController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailController.class);
@Autowired @Autowired
private IUserDetailService userDetailService; private IUserDetailService userDetailService;
@Autowired @Autowired
private IIdCardService idCardService; private IIdCardService idCardService;
private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailController.class);
@RequestMapping("/save") @RequestMapping("/save")
public JsonResult saveUserdetail(String idNo, String name) { public JsonResult saveUserdetail(String idNo, String name) {
......
...@@ -13,7 +13,7 @@ import java.sql.Timestamp; ...@@ -13,7 +13,7 @@ import java.sql.Timestamp;
@Data @Data
@Entity @Entity
@Table(name = "address", uniqueConstraints = @UniqueConstraint(columnNames = "user_id")) @Table(name = "address", uniqueConstraints = @UniqueConstraint(columnNames = "user_id"))
public class Address implements Serializable{ public class Address implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
......
...@@ -15,7 +15,7 @@ import java.sql.Timestamp; ...@@ -15,7 +15,7 @@ import java.sql.Timestamp;
@Data @Data
@Entity @Entity
@Table(name = "merchant") @Table(name = "merchant")
public class Merchant implements Serializable{ public class Merchant implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
......
package cn.quantgroup.xyqb.entity; package cn.quantgroup.xyqb.entity;
import cn.quantgroup.motan.retbean.XUser;
import cn.quantgroup.xyqb.config.http.Timestamp2LongConverter; import cn.quantgroup.xyqb.config.http.Timestamp2LongConverter;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.Getter;
import lombok.*; import lombok.Setter;
import lombok.ToString;
import javax.jws.soap.SOAPBinding;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Timestamp; import java.sql.Timestamp;
...@@ -57,4 +58,18 @@ public class User implements Serializable { ...@@ -57,4 +58,18 @@ public class User implements Serializable {
private Timestamp updatedAt; private Timestamp updatedAt;
public XUser toXUser() {
XUser xUser = new XUser();
xUser.setId(this.getId());
xUser.setPassword(this.getPassword());
xUser.setRegisteredFrom(this.getRegisteredFrom());
xUser.setUuid(this.getUuid());
xUser.setEnable(this.getEnable());
xUser.setPhoneNo(this.getPhoneNo());
xUser.setUpdatedAt(this.getUpdatedAt());
xUser.setCreatedAt(this.getCreatedAt());
return xUser;
}
} }
package cn.quantgroup.xyqb.entity; package cn.quantgroup.xyqb.entity;
import cn.quantgroup.motan.retbean.XUserDetail;
import cn.quantgroup.xyqb.model.Gender; import cn.quantgroup.xyqb.model.Gender;
import cn.quantgroup.xyqb.model.IdType; import cn.quantgroup.xyqb.model.IdType;
import lombok.*; import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable; import java.io.Serializable;
...@@ -64,5 +67,27 @@ public class UserDetail implements Serializable { ...@@ -64,5 +67,27 @@ public class UserDetail implements Serializable {
@Column(name = "updated_at") @Column(name = "updated_at")
private Timestamp updatedAt; private Timestamp updatedAt;
public XUserDetail toXUserDetail() {
XUserDetail xUserDetail = new XUserDetail();
xUserDetail.setId(this.getId());
xUserDetail.setUserId(this.getUserId());
xUserDetail.setPhoneNo(this.getPhoneNo());
xUserDetail.setName(this.getName());
xUserDetail.setIdNo(this.getIdNo());
if (this.getIdType() != null) {
xUserDetail.setIdType(cn.quantgroup.motan.enums.IdType.valueOf(this.getIdType().name()));
}
if (this.getGender() != null) {
xUserDetail.setGender(cn.quantgroup.motan.enums.Gender.valueOf(this.getGender().name()));
}
xUserDetail.setEmail(this.getEmail());
xUserDetail.setQq(this.getQq());
xUserDetail.setId(this.getId());
xUserDetail.setCreatedAt(this.getCreatedAt());
xUserDetail.setUpdatedAt(this.getUpdatedAt());
xUserDetail.setIsAuthenticated(this.getIsAuthenticated());
return xUserDetail;
}
} }
package cn.quantgroup.xyqb.entity; package cn.quantgroup.xyqb.entity;
import cn.quantgroup.xyqb.entity.enumerate.*; import cn.quantgroup.xyqb.entity.enumerate.*;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.Data; import lombok.Data;
import javax.persistence.*; import javax.persistence.*;
......
...@@ -24,10 +24,10 @@ public class UuidPhoneMapping implements Serializable { ...@@ -24,10 +24,10 @@ public class UuidPhoneMapping implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@Column (name = "uuid") @Column(name = "uuid")
private String uuid; private String uuid;
@Column (name = "phone_no") @Column(name = "phone_no")
private String phoneNo; private String phoneNo;
......
...@@ -13,7 +13,7 @@ import java.sql.Timestamp; ...@@ -13,7 +13,7 @@ import java.sql.Timestamp;
@Entity @Entity
@Table(name = "wechat_userinfo") @Table(name = "wechat_userinfo")
@Data @Data
public class WechatUserInfo implements Serializable{ public class WechatUserInfo implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
......
...@@ -21,14 +21,14 @@ public enum EducationEnum { ...@@ -21,14 +21,14 @@ public enum EducationEnum {
this.name = name; this.name = name;
} }
public void setName(String name) {
this.name = name;
}
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) {
this.name = name;
}
@Override @Override
public String toString() { public String toString() {
return name; return name;
......
...@@ -10,7 +10,7 @@ public enum IncomeEnum { ...@@ -10,7 +10,7 @@ public enum IncomeEnum {
CASH_AND_PAY_CARD("混合"); CASH_AND_PAY_CARD("混合");
private String desc; private String desc;
private IncomeEnum(String desc){ private IncomeEnum(String desc) {
this.desc = desc; this.desc = desc;
} }
} }
\ No newline at end of file
...@@ -16,7 +16,7 @@ public enum IncomeRangeEnum { ...@@ -16,7 +16,7 @@ public enum IncomeRangeEnum {
private String desc; private String desc;
private IncomeRangeEnum(String desc){ private IncomeRangeEnum(String desc) {
this.desc = desc; this.desc = desc;
} }
......
...@@ -23,14 +23,14 @@ public enum OccupationEnum { ...@@ -23,14 +23,14 @@ public enum OccupationEnum {
this.name = name; this.name = name;
} }
public void setName(String name) {
this.name = name;
}
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) {
this.name = name;
}
@Override @Override
public String toString() { public String toString() {
return name; return name;
......
package cn.quantgroup.xyqb.exception; package cn.quantgroup.xyqb.exception;
/** /**
* @author mengfan.feng * @author mengfan.feng
* @time 2015-09-08 17:43 * @time 2015-09-08 17:43
*/ */
public class UserNotExistException extends RuntimeException{ public class UserNotExistException extends RuntimeException {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
......
...@@ -22,12 +22,6 @@ import java.util.Set; ...@@ -22,12 +22,6 @@ import java.util.Set;
@Configuration @Configuration
public class CrosFilter implements Filter { public class CrosFilter implements Filter {
@Value("${xyqb.filter.allowedOrigin}")
private String allowedOrigin;
@Value("${xyqb.filter.allowedHeaders}")
private String allowedHeaders;
private static final Set<String> DISALLOWED_METHOD = new HashSet<>(); private static final Set<String> DISALLOWED_METHOD = new HashSet<>();
static { static {
...@@ -36,6 +30,10 @@ public class CrosFilter implements Filter { ...@@ -36,6 +30,10 @@ public class CrosFilter implements Filter {
DISALLOWED_METHOD.add("DELETE"); DISALLOWED_METHOD.add("DELETE");
} }
@Value("${xyqb.filter.allowedOrigin}")
private String allowedOrigin;
@Value("${xyqb.filter.allowedHeaders}")
private String allowedHeaders;
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException { public void init(FilterConfig filterConfig) throws ServletException {
......
...@@ -25,17 +25,24 @@ import java.io.PrintWriter; ...@@ -25,17 +25,24 @@ import java.io.PrintWriter;
@Order(Ordered.HIGHEST_PRECEDENCE + 100) @Order(Ordered.HIGHEST_PRECEDENCE + 100)
public class RequestFilter implements Filter { public class RequestFilter implements Filter {
//private static final String[] ALLOWED_PATTERNS = {
// "/innerapi/**", "/user/exist", "/motan/**", "/user/register", "/user/login", "/user/register/fast","/auth/info/login",
// "/user/login/fast", "/user/reset_password", "/user/exist_check",
// "/jr58/**", "/app/login", "/app/login_super", "/wechat/**", "/config/**", "/api/**", "/user/exists_token",
// "/platform/api/page/return_url", "/MP_" +
// "verify_AWiagUn4kZiwmTt0.txt"
//};
private static final String[] ALLOWED_PATTERNS = {
"/innerapi/**", "/user/exist", "/motan/**", "/user/register", "/user/login", "/user/register/fast","/auth/info/login",
"/user/login/fast", "/user/reset_password", "/user/exist_check",
"/jr58/**", "/app/login", "/app/login_super", "/wechat/**", "/config/**", "/api/**", "/user/exists_token",
"/platform/api/page/return_url", "/MP_" +
"verify_AWiagUn4kZiwmTt0.txt"
};
private static final String UNAUTH_RESULT = JSONObject.toJSONString(JsonResult.buildErrorStateResult("登录失败", null));
@Autowired @Autowired
private ISessionService sessionService; private ISessionService sessionService;
private AntPathMatcher matcher = new AntPathMatcher(); private AntPathMatcher matcher = new AntPathMatcher();
private static final String [] ALLOWED_PATTERNS = {
"/innerapi/**", "/user/exist","/user/register","/user/login","/user/register/fast",
"/user/login/fast", "/user/reset_password","/user/exist_check",
"/jr58/**","/app/login","/app/login_super", "/wechat/**", "/config/**","/api/**","/user/exists_token",
"/platform/api/page/return_url", "/MP_verify_AWiagUn4kZiwmTt0.txt"
};
private static final String UNAUTH_RESULT = JSONObject.toJSONString(JsonResult.buildErrorStateResult("登录失败", null));
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException { public void init(FilterConfig filterConfig) throws ServletException {
...@@ -47,10 +54,10 @@ public class RequestFilter implements Filter { ...@@ -47,10 +54,10 @@ public class RequestFilter implements Filter {
HttpServletResponse response = (HttpServletResponse) servletResponse; HttpServletResponse response = (HttpServletResponse) servletResponse;
String requestPath = getRequestPath(request); String requestPath = getRequestPath(request);
SessionStruct sessionStruct; SessionStruct sessionStruct;
if(!isMatch(requestPath)){ if (!isMatch(requestPath)) {
//获取session信息,如果没有获取到session信息则返回错误信息 //获取session信息,如果没有获取到session信息则返回错误信息
sessionStruct = XyqbSessionContextHolder.getXSession(); sessionStruct = XyqbSessionContextHolder.getXSession();
if(sessionStruct == null) { if (sessionStruct == null) {
response.setStatus(401); response.setStatus(401);
response.setHeader("Content-Type", "application/json;charset=utf-8"); response.setHeader("Content-Type", "application/json;charset=utf-8");
PrintWriter writer = response.getWriter(); PrintWriter writer = response.getWriter();
...@@ -70,7 +77,7 @@ public class RequestFilter implements Filter { ...@@ -70,7 +77,7 @@ public class RequestFilter implements Filter {
} }
} }
} }
}else { } else {
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
} }
......
package cn.quantgroup.xyqb.interceptors;
import cn.quantgroup.xyqb.util.IPUtil;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Created by Administrator on 2017/5/9.
*/
public class IPWhiteListInterceptor implements HandlerInterceptor {
private Integer isDebug;
private static final Logger LOGGER = LoggerFactory.getLogger(IPWhiteListInterceptor.class);
private static final String patternStr = "172.*";
private static final String [] allowIPs = {"139.198.7.123"};
private static Set<String> allowIPSet = Sets.newHashSet(allowIPs);
private static final Pattern pattern = Pattern.compile(patternStr);
public IPWhiteListInterceptor(Integer isDebug) {
this.isDebug = isDebug;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(isDebug !=0) return true;
String remoteIP = IPUtil.getRemoteIP(request);
if(StringUtils.isNoneBlank(remoteIP)){
remoteIP = remoteIP.trim();
boolean isMatch = pattern.matcher(remoteIP).matches();
isMatch = Boolean.logicalOr(isMatch,allowIPSet.contains(remoteIP));
if(!isMatch){
LOGGER.info("非法IP尝试访问,ip:[{}]",remoteIP);
}
return isMatch;
}
LOGGER.info("未能获取remoteIP");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
package cn.quantgroup.xyqb.model; package cn.quantgroup.xyqb.model;
import lombok.AllArgsConstructor; import lombok.*;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable; import java.io.Serializable;
......
...@@ -10,7 +10,7 @@ public class AuthBean { ...@@ -10,7 +10,7 @@ public class AuthBean {
private String token; private String token;
private String phoneNo; private String phoneNo;
public AuthBean (String token, Principal user) { public AuthBean(String token, Principal user) {
this.token = token; this.token = token;
this.phoneNo = user.getName(); this.phoneNo = user.getName();
} }
......
...@@ -26,7 +26,7 @@ public class ContactRet implements Serializable { ...@@ -26,7 +26,7 @@ public class ContactRet implements Serializable {
private Long updateAt; private Long updateAt;
public static ContactRet contact2ContactRet (Contact c) { public static ContactRet contact2ContactRet(Contact c) {
if (c == null) { if (c == null) {
return null; return null;
} }
......
...@@ -14,14 +14,14 @@ public enum Gender { ...@@ -14,14 +14,14 @@ public enum Gender {
this.name = name; this.name = name;
} }
public void setName(String name) {
this.name = name;
}
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) {
this.name = name;
}
@Override @Override
public String toString() { public String toString() {
return name; return name;
......
...@@ -22,14 +22,14 @@ public enum IdType { ...@@ -22,14 +22,14 @@ public enum IdType {
this.name = name; this.name = name;
} }
public void setName(String name) {
this.name = name;
}
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) {
this.name = name;
}
@Override @Override
public String toString() { public String toString() {
return name; return name;
......
...@@ -48,6 +48,10 @@ public class JsonResult implements Serializable { ...@@ -48,6 +48,10 @@ public class JsonResult implements Serializable {
this.businessCode = String.format(Constants.ZERO_FILL_TEMPLATE, businessCode); this.businessCode = String.format(Constants.ZERO_FILL_TEMPLATE, businessCode);
} }
public JsonResult(Object data) {
this.data = data;
}
/** /**
* 构造成功的JsonResult * 构造成功的JsonResult
* *
...@@ -82,10 +86,6 @@ public class JsonResult implements Serializable { ...@@ -82,10 +86,6 @@ public class JsonResult implements Serializable {
return new JsonResult(msg, ERROR_STATE_CODE, data, busniessId); return new JsonResult(msg, ERROR_STATE_CODE, data, busniessId);
} }
public JsonResult(Object data) {
this.data = data;
}
public String getMsg() { public String getMsg() {
return msg; return msg;
} }
......
...@@ -21,14 +21,14 @@ public final class Tuple<Key, Value> { ...@@ -21,14 +21,14 @@ public final class Tuple<Key, Value> {
return key; return key;
} }
public Value getValue() {
return value;
}
public void setKey(Key key) { public void setKey(Key key) {
this.key = key; this.key = key;
} }
public Value getValue() {
return value;
}
public void setValue(Value value) { public void setValue(Value value) {
this.value = value; this.value = value;
} }
......
...@@ -4,14 +4,13 @@ import cn.quantgroup.xyqb.entity.UserDetail; ...@@ -4,14 +4,13 @@ import cn.quantgroup.xyqb.entity.UserDetail;
import lombok.Data; import lombok.Data;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Created by 11 on 2016/12/20. * Created by 11 on 2016/12/20.
*/ */
@Data @Data
public class UserDetailRet implements Serializable{ public class UserDetailRet implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private Long id; private Long id;
...@@ -46,10 +45,11 @@ public class UserDetailRet implements Serializable{ ...@@ -46,10 +45,11 @@ public class UserDetailRet implements Serializable{
/** /**
* 转换时间从timestamp到long * 转换时间从timestamp到long
*
* @param userDetail * @param userDetail
* @return return self * @return return self
*/ */
public static UserDetailRet getUserDetail(UserDetail userDetail){ public static UserDetailRet getUserDetail(UserDetail userDetail) {
long createTimeStamp = userDetail.getCreatedAt().getTime(); long createTimeStamp = userDetail.getCreatedAt().getTime();
long updateTimeStamp = userDetail.getUpdatedAt().getTime(); long updateTimeStamp = userDetail.getUpdatedAt().getTime();
UserDetailRet userDetailRet = new UserDetailRet(); UserDetailRet userDetailRet = new UserDetailRet();
......
...@@ -4,8 +4,6 @@ import cn.quantgroup.xyqb.entity.UserExtInfo; ...@@ -4,8 +4,6 @@ import cn.quantgroup.xyqb.entity.UserExtInfo;
import cn.quantgroup.xyqb.entity.enumerate.*; import cn.quantgroup.xyqb.entity.enumerate.*;
import lombok.Data; import lombok.Data;
import java.sql.Timestamp;
/** /**
* Created by Miraculous on 2017/2/13. * Created by Miraculous on 2017/2/13.
*/ */
......
...@@ -10,7 +10,7 @@ import java.io.Serializable; ...@@ -10,7 +10,7 @@ import java.io.Serializable;
* Created by 11 on 2016/12/20. * Created by 11 on 2016/12/20.
*/ */
@Data @Data
public class UserRet implements Serializable{ public class UserRet implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private Long id; private Long id;
...@@ -35,7 +35,7 @@ public class UserRet implements Serializable{ ...@@ -35,7 +35,7 @@ public class UserRet implements Serializable{
//上一次修改时间 //上一次修改时间
private Long updatedAt; private Long updatedAt;
public static UserRet getUserRet(User user){ public static UserRet getUserRet(User user) {
Long createTimeStamp = user.getCreatedAt().getTime(); Long createTimeStamp = user.getCreatedAt().getTime();
Long updateTimeStamp = user.getUpdatedAt().getTime(); Long updateTimeStamp = user.getUpdatedAt().getTime();
UserRet userRet = new UserRet(); UserRet userRet = new UserRet();
......
...@@ -18,7 +18,7 @@ public class Jr58Authorization { ...@@ -18,7 +18,7 @@ public class Jr58Authorization {
@Getter @Getter
@Setter @Setter
public static class OperatorData{ public static class OperatorData {
private OriginalData originalData; private OriginalData originalData;
private ReportData reportData; private ReportData reportData;
...@@ -33,7 +33,7 @@ public class Jr58Authorization { ...@@ -33,7 +33,7 @@ public class Jr58Authorization {
@Getter @Getter
@Setter @Setter
public static class PhoneData{ public static class PhoneData {
private Long id; private Long id;
private String phoneNum; private String phoneNum;
private String serialNo; private String serialNo;
...@@ -47,7 +47,7 @@ public class Jr58Authorization { ...@@ -47,7 +47,7 @@ public class Jr58Authorization {
@Getter @Getter
@Setter @Setter
public static class PhoneBillDataList{ public static class PhoneBillDataList {
private String localPhone; private String localPhone;
private String totalCost; private String totalCost;
private String planCost; private String planCost;
...@@ -58,7 +58,7 @@ public class Jr58Authorization { ...@@ -58,7 +58,7 @@ public class Jr58Authorization {
@Getter @Getter
@Setter @Setter
public static class PhoneCallLogList{ public static class PhoneCallLogList {
private String localPhone; private String localPhone;
private String callPhone; private String callPhone;
private String callId; private String callId;
...@@ -73,7 +73,7 @@ public class Jr58Authorization { ...@@ -73,7 +73,7 @@ public class Jr58Authorization {
@Getter @Getter
@Setter @Setter
public static class PhoneSmsLogList{ public static class PhoneSmsLogList {
private String localPhone; private String localPhone;
private String otherPhone; private String otherPhone;
private String sendId; private String sendId;
...@@ -86,13 +86,9 @@ public class Jr58Authorization { ...@@ -86,13 +86,9 @@ public class Jr58Authorization {
} }
@Getter @Getter
@Setter @Setter
public static class ReportData{ public static class ReportData {
private String localPhone; private String localPhone;
private Behavior behavior; private Behavior behavior;
private Check check; private Check check;
...@@ -105,7 +101,7 @@ public class Jr58Authorization { ...@@ -105,7 +101,7 @@ public class Jr58Authorization {
@Getter @Getter
@Setter @Setter
public static class Behavior{ public static class Behavior {
private String localPhone; private String localPhone;
private String friendCircle; private String friendCircle;
private String localLivingYear; private String localLivingYear;
...@@ -130,7 +126,7 @@ public class Jr58Authorization { ...@@ -130,7 +126,7 @@ public class Jr58Authorization {
@Getter @Getter
@Setter @Setter
public static class Check{ public static class Check {
private String localPhone; private String localPhone;
private String idCardValidate; private String idCardValidate;
private String operatorBinding; private String operatorBinding;
...@@ -147,7 +143,7 @@ public class Jr58Authorization { ...@@ -147,7 +143,7 @@ public class Jr58Authorization {
@Getter @Getter
@Setter @Setter
public static class CallList{ public static class CallList {
private String localPhone; private String localPhone;
private String phoneNum; private String phoneNum;
private String attribution; private String attribution;
...@@ -180,14 +176,14 @@ public class Jr58Authorization { ...@@ -180,14 +176,14 @@ public class Jr58Authorization {
@Setter @Setter
@Getter @Getter
public static class ContactList{ public static class ContactList {
} }
@Getter @Getter
@Setter @Setter
public static class OperatorList{ public static class OperatorList {
private String localPhone; private String localPhone;
private String operatorName; private String operatorName;
private String operatorZh; private String operatorZh;
...@@ -209,7 +205,7 @@ public class Jr58Authorization { ...@@ -209,7 +205,7 @@ public class Jr58Authorization {
@Getter @Getter
@Setter @Setter
public static class RegionList{ public static class RegionList {
private String localphone; private String localphone;
private String regionName; private String regionName;
private String numCount; private String numCount;
...@@ -230,7 +226,7 @@ public class Jr58Authorization { ...@@ -230,7 +226,7 @@ public class Jr58Authorization {
@Setter @Setter
@Getter @Getter
public static class ServiceList{ public static class ServiceList {
private String localPhone; private String localPhone;
private String companyName; private String companyName;
private String companyType; private String companyType;
...@@ -243,7 +239,7 @@ public class Jr58Authorization { ...@@ -243,7 +239,7 @@ public class Jr58Authorization {
@Setter @Setter
@Getter @Getter
public static class TripConsumeList{ public static class TripConsumeList {
} }
...@@ -251,5 +247,4 @@ public class Jr58Authorization { ...@@ -251,5 +247,4 @@ public class Jr58Authorization {
} }
} }
package cn.quantgroup.xyqb.model.session; package cn.quantgroup.xyqb.model.session;
import cn.quantgroup.motan.retbean.XLoginInfo;
import cn.quantgroup.xyqb.model.UserRet; import cn.quantgroup.xyqb.model.UserRet;
import com.alibaba.fastjson.JSON;
import lombok.Data; import lombok.Data;
/** /**
...@@ -13,6 +15,14 @@ public class LoginInfo { ...@@ -13,6 +15,14 @@ public class LoginInfo {
private UserRet user; private UserRet user;
private LoginContext loginContext; private LoginContext loginContext;
public static XLoginInfo getXLoginInfo(LoginInfo loginInfo) {
if (null == loginInfo) {
return null;
}
String userJson = JSON.toJSONString(loginInfo);
return JSON.parseObject(userJson, XLoginInfo.class);
}
@Data @Data
public static class LoginContext { public static class LoginContext {
......
...@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.model.session; ...@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.model.session;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import org.apache.commons.collections.map.HashedMap;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashMap; import java.util.HashMap;
......
...@@ -15,7 +15,7 @@ import java.util.Map; ...@@ -15,7 +15,7 @@ import java.util.Map;
*/ */
@Data @Data
@NoArgsConstructor @NoArgsConstructor
public class SessionValue{ public class SessionValue {
private User user; private User user;
private Map<String, String> values; private Map<String, String> values;
......
...@@ -9,7 +9,7 @@ import java.io.Serializable; ...@@ -9,7 +9,7 @@ import java.io.Serializable;
* 微信获取access_token接口的返回值 * 微信获取access_token接口的返回值
*/ */
@Data @Data
public class AccessTokenResponse implements Serializable{ public class AccessTokenResponse implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private String accessToken; private String accessToken;
private Long expiresIn; private Long expiresIn;
......
...@@ -6,5 +6,5 @@ import org.springframework.data.jpa.repository.JpaRepository; ...@@ -6,5 +6,5 @@ import org.springframework.data.jpa.repository.JpaRepository;
/** /**
* Created by 11 on 2016/12/30. * Created by 11 on 2016/12/30.
*/ */
public interface IMerchantConfigRepository extends JpaRepository<MerchantConfig, Long>{ public interface IMerchantConfigRepository extends JpaRepository<MerchantConfig, Long> {
} }
...@@ -4,14 +4,18 @@ import cn.quantgroup.xyqb.entity.User; ...@@ -4,14 +4,18 @@ import cn.quantgroup.xyqb.entity.User;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
/** /**
* Created by Miraculous on 15/7/4. * Created by Miraculous on 15/7/4.
*/ */
public interface IUserRepository extends JpaRepository<User, Long> ,JpaSpecificationExecutor<User>{ public interface IUserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
User findByPhoneNo(String phoneNo); User findByPhoneNo(String phoneNo);
User findByUuid(String uuid); User findByUuid(String uuid);
List<User> findByIdIn(List<Long> ids);
User findById(Long id); User findById(Long id);
} }
...@@ -6,7 +6,7 @@ import org.springframework.data.jpa.repository.JpaRepository; ...@@ -6,7 +6,7 @@ import org.springframework.data.jpa.repository.JpaRepository;
/** /**
* Created by Miraculous on 15/10/29. * Created by Miraculous on 15/10/29.
*/ */
public interface IUuidPhoneMappingRepository extends JpaRepository<UuidPhoneMapping, Long>{ public interface IUuidPhoneMappingRepository extends JpaRepository<UuidPhoneMapping, Long> {
UuidPhoneMapping findByUuid(String uuid); UuidPhoneMapping findByUuid(String uuid);
......
...@@ -9,6 +9,8 @@ import org.springframework.data.jpa.repository.JpaRepository; ...@@ -9,6 +9,8 @@ import org.springframework.data.jpa.repository.JpaRepository;
*/ */
public interface IWeChatUserRepository extends JpaRepository<WechatUserInfo, Long> { public interface IWeChatUserRepository extends JpaRepository<WechatUserInfo, Long> {
WechatUserInfo findByOpenId(String openId); WechatUserInfo findByOpenId(String openId);
WechatUserInfo findByPhoneNo(String phoneNo); WechatUserInfo findByPhoneNo(String phoneNo);
WechatUserInfo findByUserId(Long userId); WechatUserInfo findByUserId(Long userId);
} }
...@@ -21,12 +21,11 @@ public class UserApiServiceImpl implements IUserApiService { ...@@ -21,12 +21,11 @@ public class UserApiServiceImpl implements IUserApiService {
private IUserService userService; private IUserService userService;
@Override @Override
public boolean userImportCheck(String phoneNo) { public boolean userImportCheck(String phoneNo) {
User user=userService.findByPhoneWithCache(phoneNo); User user = userService.findByPhoneWithCache(phoneNo);
if (user!=null){ if (user != null) {
return false; return false;
} }
......
...@@ -10,6 +10,7 @@ public interface IHttpService { ...@@ -10,6 +10,7 @@ public interface IHttpService {
/** /**
* Http Get * Http Get
*
* @param uri * @param uri
* @return * @return
*/ */
...@@ -17,6 +18,7 @@ public interface IHttpService { ...@@ -17,6 +18,7 @@ public interface IHttpService {
/** /**
* Http Get * Http Get
*
* @param uri * @param uri
* @param parameters * @param parameters
* @return * @return
...@@ -25,6 +27,7 @@ public interface IHttpService { ...@@ -25,6 +27,7 @@ public interface IHttpService {
/** /**
* Http Get * Http Get
*
* @param uri * @param uri
* @param headers * @param headers
* @param parameters * @param parameters
...@@ -34,6 +37,7 @@ public interface IHttpService { ...@@ -34,6 +37,7 @@ public interface IHttpService {
/** /**
* Http Post * Http Post
*
* @param uri * @param uri
* @return * @return
*/ */
...@@ -41,6 +45,7 @@ public interface IHttpService { ...@@ -41,6 +45,7 @@ public interface IHttpService {
/** /**
* Http Post * Http Post
*
* @param uri * @param uri
* @param parameters * @param parameters
* @return * @return
...@@ -49,6 +54,7 @@ public interface IHttpService { ...@@ -49,6 +54,7 @@ public interface IHttpService {
/** /**
* Http Post * Http Post
*
* @param uri * @param uri
* @param headers * @param headers
* @param parameters * @param parameters
......
...@@ -23,7 +23,7 @@ public interface Jr58Service { ...@@ -23,7 +23,7 @@ public interface Jr58Service {
/** /**
* 避免填写资料 * 避免填写资料
*/ */
void getRidOfFillingProfile(User user,String phoneNo) throws UnsupportedEncodingException; void getRidOfFillingProfile(User user, String phoneNo) throws UnsupportedEncodingException;
/** /**
* 推送授权数据 * 推送授权数据
...@@ -32,10 +32,11 @@ public interface Jr58Service { ...@@ -32,10 +32,11 @@ public interface Jr58Service {
/** /**
* 推送授权开始的状态 * 推送授权开始的状态
*
* @param userId * @param userId
* @param account * @param account
* @param authorizationType * @param authorizationType
*/ */
void pushAuthorizationStatus(String userId,String account,String authorizationType); void pushAuthorizationStatus(String userId, String account, String authorizationType);
} }
...@@ -6,7 +6,6 @@ import cn.quantgroup.xyqb.entity.UserDetail; ...@@ -6,7 +6,6 @@ import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.entity.UserJr58; import cn.quantgroup.xyqb.entity.UserJr58;
import cn.quantgroup.xyqb.model.IdCardInfo; import cn.quantgroup.xyqb.model.IdCardInfo;
import cn.quantgroup.xyqb.model.IdType; import cn.quantgroup.xyqb.model.IdType;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.jr58.Jr58Authorization; import cn.quantgroup.xyqb.model.jr58.Jr58Authorization;
import cn.quantgroup.xyqb.model.jr58.Jr58RegisterParam; import cn.quantgroup.xyqb.model.jr58.Jr58RegisterParam;
import cn.quantgroup.xyqb.model.jr58.Jr58RegisterResult; import cn.quantgroup.xyqb.model.jr58.Jr58RegisterResult;
...@@ -18,15 +17,12 @@ import cn.quantgroup.xyqb.service.http.IHttpService; ...@@ -18,15 +17,12 @@ import cn.quantgroup.xyqb.service.http.IHttpService;
import cn.quantgroup.xyqb.service.jr58.Jr58Service; import cn.quantgroup.xyqb.service.jr58.Jr58Service;
import cn.quantgroup.xyqb.service.user.ILkbUserService; import cn.quantgroup.xyqb.service.user.ILkbUserService;
import cn.quantgroup.xyqb.util.GZipUtil; import cn.quantgroup.xyqb.util.GZipUtil;
import cn.quantgroup.xyqb.util.PasswordUtil;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -116,7 +112,7 @@ public class Jr58ServiceImpl implements Jr58Service { ...@@ -116,7 +112,7 @@ public class Jr58ServiceImpl implements Jr58Service {
} }
@Override @Override
public void getRidOfFillingProfile(User user,String phoneNo) throws UnsupportedEncodingException { public void getRidOfFillingProfile(User user, String phoneNo) throws UnsupportedEncodingException {
if (user == null) { if (user == null) {
LOGGER.info("58用户不存在"); LOGGER.info("58用户不存在");
return; return;
...@@ -211,7 +207,6 @@ public class Jr58ServiceImpl implements Jr58Service { ...@@ -211,7 +207,6 @@ public class Jr58ServiceImpl implements Jr58Service {
} }
/** /**
* 推送授权数据 * 推送授权数据
*/ */
...@@ -221,39 +216,39 @@ public class Jr58ServiceImpl implements Jr58Service { ...@@ -221,39 +216,39 @@ public class Jr58ServiceImpl implements Jr58Service {
Map<String, String> parameters = null; Map<String, String> parameters = null;
String url = ""; String url = "";
//量化派数据 //量化派数据
if("0".equals(authorizationData.getSourceFrom())){ if ("0".equals(authorizationData.getSourceFrom())) {
parameters = ImmutableMap.<String, String>builder() parameters = ImmutableMap.<String, String>builder()
.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") .put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
.put("loginName", authorizationData.getOperator_data().getOriginalData().getPhone()) .put("loginName", authorizationData.getOperator_data().getOriginalData().getPhone())
.put("currentUser", authorizationData.getUserId()) .put("currentUser", authorizationData.getUserId())
.put("userSource", "YUNYINGSHANG") .put("userSource", "YUNYINGSHANG")
.build(); .build();
url= pushImportForJr58Url + "/SpiderServer/api/dataTransfer/saveUserAuthInfo.json"; url = pushImportForJr58Url + "/SpiderServer/api/dataTransfer/saveUserAuthInfo.json";
}else if("1".equals(authorizationData.getSourceFrom())){ } else if ("1".equals(authorizationData.getSourceFrom())) {
//读秒数据 //读秒数据
//String graspingJson = Constants.GSON.toJson(authorizationData.getOperator_data()); //String graspingJson = Constants.GSON.toJson(authorizationData.getOperator_data());
String graspingJson = JSONObject.toJSONString(authorizationData.getOperator_data()); String graspingJson = JSONObject.toJSONString(authorizationData.getOperator_data());
byte[] graspingJsonBytes = GZipUtil.compressToByte(graspingJson); byte[] graspingJsonBytes = GZipUtil.compressToByte(graspingJson);
String authorizationDataStr = Base64.getEncoder().encodeToString(graspingJsonBytes); String authorizationDataStr = Base64.getEncoder().encodeToString(graspingJsonBytes);
parameters = ImmutableMap.<String, String>builder() parameters = ImmutableMap.<String, String>builder()
.put("Content-Type","application/x-www-form-urlencoded;charset=utf-8") .put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
.put("data", authorizationDataStr) .put("data", authorizationDataStr)
.put("currentUser", authorizationData.getUserId()) .put("currentUser", authorizationData.getUserId())
.put("source", "58") .put("source", "58")
.build(); .build();
url= pushImportForJr58Url + "/SpiderServer/api/dataTransfer/receive.json"; url = pushImportForJr58Url + "/SpiderServer/api/dataTransfer/receive.json";
} }
for (int i = 0; i <4 ; i++) { for (int i = 0; i < 4; i++) {
try { try {
String response = httpService.post(url, parameters); String response = httpService.post(url, parameters);
if(response.contains(",\"status\":1,")){ if (response.contains(",\"status\":1,")) {
LOGGER.info("运营商授权数据推送到lkb成功"); LOGGER.info("运营商授权数据推送到lkb成功");
break; break;
}else{ } else {
Thread.sleep(2000); Thread.sleep(2000);
LOGGER.error("运营商授权数据推送到lkb中失败 - {} ,userId ={}, response = {} url ={}", i+1, authorizationData.getUserId(),response,url); LOGGER.error("运营商授权数据推送到lkb中失败 - {} ,userId ={}, response = {} url ={}", i + 1, authorizationData.getUserId(), response, url);
} }
}catch (InterruptedException e) { } catch (InterruptedException e) {
LOGGER.error("运营商授权数据推送到失败 url ={}", url); LOGGER.error("运营商授权数据推送到失败 url ={}", url);
} }
} }
...@@ -269,21 +264,21 @@ public class Jr58ServiceImpl implements Jr58Service { ...@@ -269,21 +264,21 @@ public class Jr58ServiceImpl implements Jr58Service {
Map<String, String> parameters = ImmutableMap.<String, String>builder() Map<String, String> parameters = ImmutableMap.<String, String>builder()
.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") .put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
.put("loginName", account) .put("loginName", account)
.put("currentUser",userId) .put("currentUser", userId)
.put("userSource", "YUNYINGSHANG") .put("userSource", "YUNYINGSHANG")
.build(); .build();
String url = pushImportForJr58Url + "/SpiderServer/api/dataTransfer/saveUserAuthInfo.json"; String url = pushImportForJr58Url + "/SpiderServer/api/dataTransfer/saveUserAuthInfo.json";
for (int i = 0; i <4 ; i++) { for (int i = 0; i < 4; i++) {
try { try {
String response = httpService.post(url, parameters); String response = httpService.post(url, parameters);
if(response.contains(",\"status\":1,")){ if (response.contains(",\"status\":1,")) {
LOGGER.info("通知lkb授权成功"); LOGGER.info("通知lkb授权成功");
break; break;
}else{ } else {
Thread.sleep(2000); Thread.sleep(2000);
LOGGER.error("通知lkb授权失败 - {} ,userId ={}, response = {} url ={}", i+1, userId,response,url); LOGGER.error("通知lkb授权失败 - {} ,userId ={}, response = {} url ={}", i + 1, userId, response, url);
} }
}catch (InterruptedException e) { } catch (InterruptedException e) {
LOGGER.error("通知lkb授权失败 url ={}", url); LOGGER.error("通知lkb授权失败 url ={}", url);
} }
} }
......
...@@ -9,6 +9,7 @@ public interface IModelService { ...@@ -9,6 +9,7 @@ public interface IModelService {
/** /**
* 验证用户是否在黑名单里 * 验证用户是否在黑名单里
*
* @param phoneNo * @param phoneNo
* @return * @return
*/ */
......
package cn.quantgroup.xyqb.service.model.impl; package cn.quantgroup.xyqb.service.model.impl;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.model.model.BlacklistMatchResult; import cn.quantgroup.xyqb.model.model.BlacklistMatchResult;
import cn.quantgroup.xyqb.service.http.IHttpService; import cn.quantgroup.xyqb.service.http.IHttpService;
import cn.quantgroup.xyqb.service.model.IModelService; import cn.quantgroup.xyqb.service.model.IModelService;
...@@ -17,17 +16,14 @@ import org.springframework.stereotype.Service; ...@@ -17,17 +16,14 @@ import org.springframework.stereotype.Service;
@Service @Service
public class ModelServiceImpl implements IModelService { public class ModelServiceImpl implements IModelService {
private static final String BLACKLIST_URL_PATTERN =
"%s/Model/openapi/checkBlack.json?appId=0001&userId=0001_001&timeunit=%s&token=%s&phone=%s";
String TOKEN_PATTERN = "timeunit=%sappkey=wer123!@";
@Value("${model.quantgroup.url}") @Value("${model.quantgroup.url}")
private String modelUrlPrefix; private String modelUrlPrefix;
@Autowired @Autowired
private IHttpService httpService; private IHttpService httpService;
String TOKEN_PATTERN = "timeunit=%sappkey=wer123!@";
private static final String BLACKLIST_URL_PATTERN =
"%s/Model/openapi/checkBlack.json?appId=0001&userId=0001_001&timeunit=%s&token=%s&phone=%s";
@Override @Override
public BlacklistMatchResult getBlacklistMatchResult(String phoneNo) { public BlacklistMatchResult getBlacklistMatchResult(String phoneNo) {
if (StringUtils.isEmpty(phoneNo)) { if (StringUtils.isEmpty(phoneNo)) {
......
package cn.quantgroup.xyqb.service.page.bean; package cn.quantgroup.xyqb.service.page.bean;
import cn.quantgroup.xyqb.entity.User; import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.Tuple;
/** /**
* Created by Miraculous on 2017/1/3. * Created by Miraculous on 2017/1/3.
......
...@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.service.page.impl; ...@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.service.page.impl;
import cn.quantgroup.xyqb.entity.*; import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.model.Tuple; import cn.quantgroup.xyqb.model.Tuple;
import cn.quantgroup.xyqb.repository.IUserExtInfoRepository;
import cn.quantgroup.xyqb.service.page.IPageService; import cn.quantgroup.xyqb.service.page.IPageService;
import cn.quantgroup.xyqb.service.page.bean.PageType; import cn.quantgroup.xyqb.service.page.bean.PageType;
import cn.quantgroup.xyqb.service.user.IAddressService; import cn.quantgroup.xyqb.service.user.IAddressService;
...@@ -24,6 +23,8 @@ import java.util.Map; ...@@ -24,6 +23,8 @@ import java.util.Map;
public class PageServiceImpl implements IPageService { public class PageServiceImpl implements IPageService {
private Map<String, PageType[]> routerDefinetion; private Map<String, PageType[]> routerDefinetion;
@Autowired
private IUserDetailService userDetailService;
private PageType pageIdNo = new PageType("name", false) { private PageType pageIdNo = new PageType("name", false) {
@Override @Override
public boolean canPass(User user) { public boolean canPass(User user) {
...@@ -31,6 +32,8 @@ public class PageServiceImpl implements IPageService { ...@@ -31,6 +32,8 @@ public class PageServiceImpl implements IPageService {
return userDetail != null; return userDetail != null;
} }
}; };
@Autowired
private IUserExtInfoService userExtInfoService;
private PageType pageUserFinance = new PageType("info", false) { private PageType pageUserFinance = new PageType("info", false) {
@Override @Override
public boolean canPass(User user) { public boolean canPass(User user) {
...@@ -38,6 +41,8 @@ public class PageServiceImpl implements IPageService { ...@@ -38,6 +41,8 @@ public class PageServiceImpl implements IPageService {
return null != extInfo; return null != extInfo;
} }
}; };
@Autowired
private IAddressService addressService;
private PageType pageAddress = new PageType("address", false) { private PageType pageAddress = new PageType("address", false) {
@Override @Override
public boolean canPass(User user) { public boolean canPass(User user) {
...@@ -45,6 +50,8 @@ public class PageServiceImpl implements IPageService { ...@@ -45,6 +50,8 @@ public class PageServiceImpl implements IPageService {
return null != address; return null != address;
} }
}; };
@Autowired
private IContactService contactService;
private PageType pageContacts = new PageType("contacts", false) { private PageType pageContacts = new PageType("contacts", false) {
@Override @Override
public boolean canPass(User user) { public boolean canPass(User user) {
...@@ -52,41 +59,33 @@ public class PageServiceImpl implements IPageService { ...@@ -52,41 +59,33 @@ public class PageServiceImpl implements IPageService {
return contacts != null && contacts.size() != 0; return contacts != null && contacts.size() != 0;
} }
}; };
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IUserExtInfoService userExtInfoService;
@Autowired
private IAddressService addressService;
@Autowired
private IContactService contactService;
@PostConstruct @PostConstruct
private void init() { private void init() {
routerDefinetion = new HashMap<>(); routerDefinetion = new HashMap<>();
routerDefinetion.put("cashTarget1", new PageType[] { routerDefinetion.put("cashTarget1", new PageType[]{
pageIdNo, pageUserFinance pageIdNo, pageUserFinance
}); });
routerDefinetion.put("cashTarget2", new PageType[] { routerDefinetion.put("cashTarget2", new PageType[]{
pageIdNo, pageAddress pageIdNo, pageAddress
}); });
routerDefinetion.put("cashTarget3", new PageType[] { routerDefinetion.put("cashTarget3", new PageType[]{
pageIdNo, pageContacts pageIdNo, pageContacts
}); });
routerDefinetion.put("cashTarget4", new PageType[] { routerDefinetion.put("cashTarget4", new PageType[]{
pageIdNo pageIdNo
}); });
routerDefinetion.put("cashTarget5", new PageType[] { routerDefinetion.put("cashTarget5", new PageType[]{
}); });
} }
@Override @Override
public Tuple<String, Boolean> nextPage(User user, String target, String currentPage) { public Tuple<String, Boolean> nextPage(User user, String target, String currentPage) {
if (user == null ) { if (user == null) {
return new Tuple<>("", false); return new Tuple<>("", false);
} }
PageType[] processLists = routerDefinetion.containsKey(target) ? routerDefinetion.get(target): null; PageType[] processLists = routerDefinetion.containsKey(target) ? routerDefinetion.get(target) : null;
if (processLists == null) { if (processLists == null) {
return new Tuple<>("", false); return new Tuple<>("", false);
} }
......
...@@ -14,6 +14,8 @@ public interface ISmsService { ...@@ -14,6 +14,8 @@ public interface ISmsService {
void sendAfterRegister(String phoneNo); void sendAfterRegister(String phoneNo);
void sendAfterRegister(String phoneNo,String contentId);
boolean validRegisterOrResetPasswdVerificationCode(String phoneNo, String smsVerificationCode); boolean validRegisterOrResetPasswdVerificationCode(String phoneNo, String smsVerificationCode);
boolean validateFastLoginVerificationCode(String phoneNo, String verificationCode); boolean validateFastLoginVerificationCode(String phoneNo, String verificationCode);
......
package cn.quantgroup.xyqb.service.sms.impl; package cn.quantgroup.xyqb.service.sms.impl;
import cn.quantgroup.sms.MsgParams; import cn.quantgroup.sms.MsgParams;
import cn.quantgroup.sms.SendAndForgetMsg;
import cn.quantgroup.sms.SmsSender; import cn.quantgroup.sms.SmsSender;
import cn.quantgroup.xyqb.Constants; import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.service.sms.ISmsService; import cn.quantgroup.xyqb.service.sms.ISmsService;
...@@ -27,16 +26,13 @@ public class SmsServiceImpl implements ISmsService { ...@@ -27,16 +26,13 @@ public class SmsServiceImpl implements ISmsService {
private static final int SMS_VERIFICATION_MAXLEN = 6; private static final int SMS_VERIFICATION_MAXLEN = 6;
private static final String SMS_VERIFY_PREFIX = "sms:verify:"; private static final String SMS_VERIFY_PREFIX = "sms:verify:";
private static final SmsSender smsSender = new SmsSender();
@Value("${sms.is.debug}") @Value("${sms.is.debug}")
private boolean isDebug; private boolean isDebug;
@Autowired @Autowired
@Qualifier("stringRedisTemplate") @Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate; private RedisTemplate<String, String> stringRedisTemplate;
private static final SmsSender smsSender = new SmsSender();
@Override @Override
public SmsSender getSmsSender() { public SmsSender getSmsSender() {
if (null == smsSender) { if (null == smsSender) {
...@@ -57,6 +53,20 @@ public class SmsServiceImpl implements ISmsService { ...@@ -57,6 +53,20 @@ public class SmsServiceImpl implements ISmsService {
} }
} }
@Override
public void sendAfterRegister(String phoneNo, String contentId) {
try {
if(StringUtils.isBlank(contentId)){
contentId = "24";
}
MsgParams msgParams = new MsgParams(Collections.singletonList(2), phoneNo, "1", contentId, Collections.emptyList());
smsSender.sendMsg(msgParams);
LOGGER.info("注册完成,发送短信, phoneNo:{}", phoneNo);
} catch (Exception e) {
e.printStackTrace();
}
}
/** /**
* 检查验证码是否正确 * 检查验证码是否正确
* *
...@@ -71,7 +81,7 @@ public class SmsServiceImpl implements ISmsService { ...@@ -71,7 +81,7 @@ public class SmsServiceImpl implements ISmsService {
} }
String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo; String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
String randomCode = stringRedisTemplate.opsForValue().get(key); String randomCode = stringRedisTemplate.opsForValue().get(key);
if(StringUtils.isEmpty(randomCode)){ if (StringUtils.isEmpty(randomCode)) {
return false; return false;
} }
String[] arr = randomCode.split(":"); String[] arr = randomCode.split(":");
...@@ -81,14 +91,14 @@ public class SmsServiceImpl implements ISmsService { ...@@ -81,14 +91,14 @@ public class SmsServiceImpl implements ISmsService {
} }
@Override @Override
public boolean validateFastLoginVerificationCode(String phoneNo, String verificationCode){ public boolean validateFastLoginVerificationCode(String phoneNo, String verificationCode) {
String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo; String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
String randomCode = stringRedisTemplate.opsForValue().get(key); String randomCode = stringRedisTemplate.opsForValue().get(key);
if(StringUtils.isBlank(randomCode)){ if (StringUtils.isBlank(randomCode)) {
return false; return false;
} }
String[] arr = randomCode.split(":"); String[] arr = randomCode.split(":");
if(arr.length != 2){ if (arr.length != 2) {
return false; return false;
} }
String uniqueId = arr[0]; String uniqueId = arr[0];
......
...@@ -10,5 +10,6 @@ public interface IAddressService { ...@@ -10,5 +10,6 @@ public interface IAddressService {
Address findByUserId(Long userId); Address findByUserId(Long userId);
Address save(Address addressObj); Address save(Address addressObj);
Address saveAddress(Address address); Address saveAddress(Address address);
} }
package cn.quantgroup.xyqb.service.user; package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.User; import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WechatUserInfo;
import java.util.List;
import java.util.Map;
/** /**
* Created by Miraculous on 15/7/5. * Created by Miraculous on 15/7/5.
...@@ -24,6 +26,8 @@ public interface IUserService { ...@@ -24,6 +26,8 @@ public interface IUserService {
User findByUuidInDb(String uuid); User findByUuidInDb(String uuid);
Map<Long, String> findPhoneByIdsInDb(List<Long> userIds);
User saveUser(User user); User saveUser(User user);
User findById(Long userId); User findById(Long userId);
......
...@@ -56,7 +56,6 @@ public class UserDetailServiceImpl implements IUserDetailService { ...@@ -56,7 +56,6 @@ public class UserDetailServiceImpl implements IUserDetailService {
@Override @Override
public List<UserDetailVO> searchUserDetailList(String name, String phoneNo, String idNo) { public List<UserDetailVO> searchUserDetailList(String name, String phoneNo, String idNo) {
// return
List<UserDetail> details = userDetailRepository.findAll(getSpecification(name, phoneNo, idNo)); List<UserDetail> details = userDetailRepository.findAll(getSpecification(name, phoneNo, idNo));
Map<Long, User> userMap = Maps.newHashMap(); Map<Long, User> userMap = Maps.newHashMap();
if (!CollectionUtils.isEmpty(details)) { if (!CollectionUtils.isEmpty(details)) {
......
...@@ -7,21 +7,27 @@ import cn.quantgroup.xyqb.service.sms.ISmsService; ...@@ -7,21 +7,27 @@ import cn.quantgroup.xyqb.service.sms.ISmsService;
import cn.quantgroup.xyqb.service.user.ILkbUserService; import cn.quantgroup.xyqb.service.user.ILkbUserService;
import cn.quantgroup.xyqb.service.user.IUserService; import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.util.PasswordUtil; import cn.quantgroup.xyqb.util.PasswordUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* Created by Miraculous on 15/7/5. * Created by Miraculous on 15/7/5.
*/ */
@Service @Service
@Slf4j
public class UserServiceImpl implements IUserService { public class UserServiceImpl implements IUserService {
@Autowired @Autowired
...@@ -41,6 +47,31 @@ public class UserServiceImpl implements IUserService { ...@@ -41,6 +47,31 @@ public class UserServiceImpl implements IUserService {
return userRepository.findByPhoneNo(phone); return userRepository.findByPhoneNo(phone);
} }
@Override
public Map<Long, String> findPhoneByIdsInDb(List<Long> userIds) {
if (CollectionUtils.isEmpty(userIds)) {
return Maps.newHashMap();
}
Map<Long, String> userIdAndPhoneMap = Maps.newHashMap();
int pageSize = 1000;
int idSize = userIds.size();
for (int i = 0; i < idSize; i += pageSize) {
List<Long> subList = userIds.subList(i, Math.min(idSize, i + pageSize));
List<User> users = userRepository.findByIdIn(subList);
users.stream().forEach(user -> {
userIdAndPhoneMap.put(user.getId(), user.getPhoneNo());
});
if (i + pageSize < idSize) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
log.error("线程sleep失败", e);
}
}
}
return userIdAndPhoneMap;
}
@Override @Override
public User findByUuidInDb(String uuid) { public User findByUuidInDb(String uuid) {
return userRepository.findByUuid(uuid); return userRepository.findByUuid(uuid);
......
...@@ -21,5 +21,4 @@ public class UuidPhoneMappingServiceImpl implements IUuidPhoneMappingService { ...@@ -21,5 +21,4 @@ public class UuidPhoneMappingServiceImpl implements IUuidPhoneMappingService {
} }
} }
package cn.quantgroup.xyqb.service.user.vo; package cn.quantgroup.xyqb.service.user.vo;
import cn.quantgroup.motan.retbean.XUserDetail;
import cn.quantgroup.xyqb.entity.UserDetail; import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.model.Gender; import cn.quantgroup.xyqb.model.Gender;
import cn.quantgroup.xyqb.model.IdType; import cn.quantgroup.xyqb.model.IdType;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.sql.Timestamp;
@Data @Data
@NoArgsConstructor @NoArgsConstructor
public class UserDetailVO { public class UserDetailVO {
...@@ -56,4 +59,32 @@ public class UserDetailVO { ...@@ -56,4 +59,32 @@ public class UserDetailVO {
} }
return userDetailVO; return userDetailVO;
} }
public XUserDetail toXUserDetail() {
XUserDetail xUserDetail = new XUserDetail();
xUserDetail.setId(this.getId());
xUserDetail.setUserId(this.getUserId());
xUserDetail.setPhoneNo(this.getPhoneNo());
xUserDetail.setName(this.getName());
xUserDetail.setIdNo(this.getIdNo());
if (this.getIdType() != null) {
xUserDetail.setIdType(cn.quantgroup.motan.enums.IdType.valueOf(this.getIdType().name()));
}
if (this.getGender() != null) {
xUserDetail.setGender(cn.quantgroup.motan.enums.Gender.valueOf(this.getGender().name()));
}
xUserDetail.setEmail(this.getEmail());
xUserDetail.setQq(this.getQq());
xUserDetail.setId(this.getId());
if (this.getCreatedAt() != null) {
xUserDetail.setCreatedAt(new Timestamp(this.getCreatedAt()));
}
if (this.getUpdatedAt() != null) {
xUserDetail.setUpdatedAt(new Timestamp(this.getUpdatedAt()));
}
xUserDetail.setIsAuthenticated(this.getIsAuthenticated());
xUserDetail.setEnable(this.getEnable());
return xUserDetail;
}
} }
...@@ -8,6 +8,7 @@ import cn.quantgroup.xyqb.model.webchat.AccessTokenResponse; ...@@ -8,6 +8,7 @@ import cn.quantgroup.xyqb.model.webchat.AccessTokenResponse;
*/ */
public interface IWechatService { public interface IWechatService {
AccessTokenResponse getToken(String code); AccessTokenResponse getToken(String code);
WechatUserInfo getWechatUserInfoFromWechatServer(String token, String openId); WechatUserInfo getWechatUserInfoFromWechatServer(String token, String openId);
WechatUserInfo findWechatUserInfoFromDb(String openId); WechatUserInfo findWechatUserInfoFromDb(String openId);
......
...@@ -22,24 +22,20 @@ import java.util.concurrent.TimeUnit; ...@@ -22,24 +22,20 @@ import java.util.concurrent.TimeUnit;
*/ */
@Service @Service
public class WechatServiceImpl implements IWechatService { public class WechatServiceImpl implements IWechatService {
private static final String WECHAT_TOKEN_KEY_PREFIX = "wechat:token:";
@Autowired @Autowired
private IHttpService httpService; private IHttpService httpService;
@Autowired @Autowired
@Qualifier("stringRedisTemplate") @Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate; private RedisTemplate<String, String> redisTemplate;
@SafeValue("wechat.appid") @SafeValue("wechat.appid")
private String appId; private String appId;
@SafeValue("wechat.secret") @SafeValue("wechat.secret")
private String secret; private String secret;
@Autowired @Autowired
private IWeChatUserRepository weChatUserRepository; private IWeChatUserRepository weChatUserRepository;
private String accessTokenUrl; private String accessTokenUrl;
private String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s"; private String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s";
private static final String WECHAT_TOKEN_KEY_PREFIX = "wechat:token:";
@PostConstruct @PostConstruct
private void init() { private void init() {
...@@ -77,7 +73,7 @@ public class WechatServiceImpl implements IWechatService { ...@@ -77,7 +73,7 @@ public class WechatServiceImpl implements IWechatService {
try { try {
AccessTokenResponse response = JSONObject.parseObject(resultStr, AccessTokenResponse.class); AccessTokenResponse response = JSONObject.parseObject(resultStr, AccessTokenResponse.class);
// 刷新 // 刷新
if (response.getInitialTime() + response.getExpiresIn()*1000 > System.currentTimeMillis()) { if (response.getInitialTime() + response.getExpiresIn() * 1000 > System.currentTimeMillis()) {
String refreshTokenStr = refreshToken(response.getRefreshToken()); String refreshTokenStr = refreshToken(response.getRefreshToken());
response = JSONObject.parseObject(refreshTokenStr, AccessTokenResponse.class); response = JSONObject.parseObject(refreshTokenStr, AccessTokenResponse.class);
if (response == null) { if (response == null) {
...@@ -112,7 +108,7 @@ public class WechatServiceImpl implements IWechatService { ...@@ -112,7 +108,7 @@ public class WechatServiceImpl implements IWechatService {
@Override @Override
@Transactional @Transactional
public WechatUserInfo saveWechatUserInfo(WechatUserInfo userInfo) { public WechatUserInfo saveWechatUserInfo(WechatUserInfo userInfo) {
if(null == userInfo.getPhoneNo()) { if (null == userInfo.getPhoneNo()) {
userInfo.setPhoneNo(""); userInfo.setPhoneNo("");
} }
return weChatUserRepository.save(userInfo); return weChatUserRepository.save(userInfo);
......
...@@ -19,14 +19,14 @@ import javax.servlet.http.HttpServletRequest; ...@@ -19,14 +19,14 @@ import javax.servlet.http.HttpServletRequest;
public class XyqbSessionContextHolder { public class XyqbSessionContextHolder {
private static final ThreadLocal<SessionStruct> threadSession = new ThreadLocal<>(); private static final ThreadLocal<SessionStruct> threadSession = new ThreadLocal<>();
public static RedisTemplate<String, String> redisTemplate = null;
private static final Logger LOGGER = LoggerFactory.getLogger(XyqbSessionContextHolder.class); private static final Logger LOGGER = LoggerFactory.getLogger(XyqbSessionContextHolder.class);
public static RedisTemplate<String, String> redisTemplate = null;
public static SessionStruct getXSession() { public static SessionStruct getXSession() {
if (threadSession.get() != null) { if (threadSession.get() != null) {
return threadSession.get(); return threadSession.get();
} }
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("x-auth-token"); String token = request.getHeader("x-auth-token");
if (token == null || token.length() != 36) { if (token == null || token.length() != 36) {
return null; return null;
...@@ -52,6 +52,32 @@ public class XyqbSessionContextHolder { ...@@ -52,6 +52,32 @@ public class XyqbSessionContextHolder {
} }
} }
public static SessionStruct getXSessionFromRedis(){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("x-auth-token");
if (token == null || token.length() != 36) {
return null;
}
String result = redisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + token);
if (StringUtils.isEmpty(result)) {
return null;
}
try {
SessionValue values = JSON.parseObject(result, SessionValue.class);
if (values == null) {
return null;
}
SessionStruct sessionStruct = new SessionStruct();
sessionStruct.setSid(token);
sessionStruct.setValues(values);
return sessionStruct;
}catch (Exception ex){
LOGGER.error("序列化session出错", ex);
return null;
}
}
public static void releaseSession() { public static void releaseSession() {
threadSession.remove(); threadSession.remove();
} }
......
...@@ -47,13 +47,13 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -47,13 +47,13 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
this.oldestCaptcha = 0L; this.oldestCaptcha = 0L;
this.setCaptchaStoreMaxSize(maxCaptchaStoreSize); this.setCaptchaStoreMaxSize(maxCaptchaStoreSize);
this.setMinGuarantedStorageDelayInSeconds(minGuarantedStorageDelayInSeconds); this.setMinGuarantedStorageDelayInSeconds(minGuarantedStorageDelayInSeconds);
this.setCaptchaStoreSizeBeforeGarbageCollection((int)Math.round(0.8D * (double)maxCaptchaStoreSize)); this.setCaptchaStoreSizeBeforeGarbageCollection((int) Math.round(0.8D * (double) maxCaptchaStoreSize));
this.times = new FastHashMap(); this.times = new FastHashMap();
} }
protected AbstractManageableCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) { protected AbstractManageableCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) {
this(captchaStore, captchaEngine, minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize); this(captchaStore, captchaEngine, minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize);
if(maxCaptchaStoreSize < captchaStoreLoadBeforeGarbageCollection) { if (maxCaptchaStoreSize < captchaStoreLoadBeforeGarbageCollection) {
throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)"); throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)");
} else { } else {
this.setCaptchaStoreSizeBeforeGarbageCollection(captchaStoreLoadBeforeGarbageCollection); this.setCaptchaStoreSizeBeforeGarbageCollection(captchaStoreLoadBeforeGarbageCollection);
...@@ -67,8 +67,8 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -67,8 +67,8 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
public void setCaptchaEngineClass(String theClassName) throws IllegalArgumentException { public void setCaptchaEngineClass(String theClassName) throws IllegalArgumentException {
try { try {
Object e = Class.forName(theClassName).newInstance(); Object e = Class.forName(theClassName).newInstance();
if(e instanceof CaptchaEngine) { if (e instanceof CaptchaEngine) {
this.engine = (CaptchaEngine)e; this.engine = (CaptchaEngine) e;
} else { } else {
throw new IllegalArgumentException("Class is not instance of CaptchaEngine! " + theClassName); throw new IllegalArgumentException("Class is not instance of CaptchaEngine! " + theClassName);
} }
...@@ -94,15 +94,19 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -94,15 +94,19 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
} }
public long getNumberOfGeneratedCaptchas() { public long getNumberOfGeneratedCaptchas() {
return (long)this.numberOfGeneratedCaptchas; return (long) this.numberOfGeneratedCaptchas;
}
public void setNumberOfGeneratedCaptchas(int numberOfGeneratedCaptchas) {
this.numberOfGeneratedCaptchas = numberOfGeneratedCaptchas;
} }
public long getNumberOfCorrectResponses() { public long getNumberOfCorrectResponses() {
return (long)this.numberOfCorrectResponse; return (long) this.numberOfCorrectResponse;
} }
public long getNumberOfUncorrectResponses() { public long getNumberOfUncorrectResponses() {
return (long)this.numberOfUncorrectResponse; return (long) this.numberOfUncorrectResponse;
} }
public int getCaptchaStoreSize() { public int getCaptchaStoreSize() {
...@@ -115,7 +119,11 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -115,7 +119,11 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
} }
public long getNumberOfGarbageCollectedCaptcha() { public long getNumberOfGarbageCollectedCaptcha() {
return (long)this.numberOfGarbageCollectedCaptcha; return (long) this.numberOfGarbageCollectedCaptcha;
}
public void setNumberOfGarbageCollectedCaptcha(int numberOfGarbageCollectedCaptcha) {
this.numberOfGarbageCollectedCaptcha = numberOfGarbageCollectedCaptcha;
} }
public int getCaptchaStoreSizeBeforeGarbageCollection() { public int getCaptchaStoreSizeBeforeGarbageCollection() {
...@@ -123,25 +131,25 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -123,25 +131,25 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
} }
public void setCaptchaStoreSizeBeforeGarbageCollection(int captchaStoreSizeBeforeGarbageCollection) { public void setCaptchaStoreSizeBeforeGarbageCollection(int captchaStoreSizeBeforeGarbageCollection) {
if(this.captchaStoreMaxSize < captchaStoreSizeBeforeGarbageCollection) { if (this.captchaStoreMaxSize < captchaStoreSizeBeforeGarbageCollection) {
throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)"); throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)");
} else { } else {
this.captchaStoreSizeBeforeGarbageCollection = captchaStoreSizeBeforeGarbageCollection; this.captchaStoreSizeBeforeGarbageCollection = captchaStoreSizeBeforeGarbageCollection;
} }
} }
public int getCaptchaStoreMaxSize() {
return this.captchaStoreMaxSize;
}
public void setCaptchaStoreMaxSize(int size) { public void setCaptchaStoreMaxSize(int size) {
if(size < this.captchaStoreSizeBeforeGarbageCollection) { if (size < this.captchaStoreSizeBeforeGarbageCollection) {
throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)"); throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)");
} else { } else {
this.captchaStoreMaxSize = size; this.captchaStoreMaxSize = size;
} }
} }
public int getCaptchaStoreMaxSize() {
return this.captchaStoreMaxSize;
}
public void garbageCollectCaptchaStore() { public void garbageCollectCaptchaStore() {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
// id 垃圾回收 // id 垃圾回收
...@@ -152,15 +160,15 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -152,15 +160,15 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
protected void garbageCollectCaptchaStore(Iterator garbageCollectableCaptchaIds) { protected void garbageCollectCaptchaStore(Iterator garbageCollectableCaptchaIds) {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
long limit = now - (long)(1000 * this.minGuarantedStorageDelayInSeconds); long limit = now - (long) (1000 * this.minGuarantedStorageDelayInSeconds);
while(garbageCollectableCaptchaIds.hasNext()) { while (garbageCollectableCaptchaIds.hasNext()) {
String id = garbageCollectableCaptchaIds.next().toString(); String id = garbageCollectableCaptchaIds.next().toString();
if((Long) this.times.get(id) < limit) { if ((Long) this.times.get(id) < limit) {
// 清理计数器 // 清理计数器
this.times.remove(id); this.times.remove(id);
// 对于 redis 存储, 使用其自动失效机制, 不手动清理 // 对于 redis 存储, 使用其自动失效机制, 不手动清理
if(this.store.getClass() != RedisCaptchaStore.class){ if (this.store.getClass() != RedisCaptchaStore.class) {
this.store.removeCaptcha(id); this.store.removeCaptcha(id);
} }
++this.numberOfGarbageCollectedCaptcha; ++this.numberOfGarbageCollectedCaptcha;
...@@ -171,8 +179,8 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -171,8 +179,8 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
private Collection getGarbageCollectableCaptchaIds(long now) { private Collection getGarbageCollectableCaptchaIds(long now) {
HashSet garbageCollectableCaptchas = new HashSet(); HashSet garbageCollectableCaptchas = new HashSet();
long limit = now - (long)(1000 * this.getMinGuarantedStorageDelayInSeconds()); long limit = now - (long) (1000 * this.getMinGuarantedStorageDelayInSeconds());
if(limit > this.oldestCaptcha) { if (limit > this.oldestCaptcha) {
for (Object o : this.times.keySet()) { for (Object o : this.times.keySet()) {
String id = (String) o; String id = (String) o;
long captchaDate = (Long) this.times.get(id); long captchaDate = (Long) this.times.get(id);
...@@ -192,11 +200,11 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -192,11 +200,11 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
} }
protected Captcha generateAndStoreCaptcha(Locale locale, String ID) { protected Captcha generateAndStoreCaptcha(Locale locale, String ID) {
if(this.isCaptchaStoreFull()) { if (this.isCaptchaStoreFull()) {
logger.info("生成图形验证码时检测到, 容量已满, 执行垃圾回收"); logger.info("生成图形验证码时检测到, 容量已满, 执行垃圾回收");
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Collection garbageCollectableCaptchaIds = this.getGarbageCollectableCaptchaIds(now); Collection garbageCollectableCaptchaIds = this.getGarbageCollectableCaptchaIds(now);
if(garbageCollectableCaptchaIds.size() > 0) { if (garbageCollectableCaptchaIds.size() > 0) {
this.garbageCollectCaptchaStore(garbageCollectableCaptchaIds.iterator()); this.garbageCollectCaptchaStore(garbageCollectableCaptchaIds.iterator());
return this.generateAndStoreCaptcha(locale, ID); return this.generateAndStoreCaptcha(locale, ID);
} else { } else {
...@@ -204,7 +212,7 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -204,7 +212,7 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
throw new CaptchaServiceException("Store is full, try to increase CaptchaStore Size orto decrease time out, or to decrease CaptchaStoreSizeBeforeGrbageCollection"); throw new CaptchaServiceException("Store is full, try to increase CaptchaStore Size orto decrease time out, or to decrease CaptchaStoreSizeBeforeGrbageCollection");
} }
} else { } else {
if(this.isCaptchaStoreQuotaReached()) { if (this.isCaptchaStoreQuotaReached()) {
logger.info("生成图形验证码时检测到, 容量已达配额, 执行垃圾回收"); logger.info("生成图形验证码时检测到, 容量已达配额, 执行垃圾回收");
this.garbageCollectCaptchaStore(); this.garbageCollectCaptchaStore();
} }
...@@ -231,7 +239,7 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -231,7 +239,7 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
public Boolean validateResponseForID(String ID, Object response) throws CaptchaServiceException { public Boolean validateResponseForID(String ID, Object response) throws CaptchaServiceException {
Boolean valid = super.validateResponseForID(ID, response); Boolean valid = super.validateResponseForID(ID, response);
this.times.remove(ID); this.times.remove(ID);
if(valid) { if (valid) {
++this.numberOfCorrectResponse; ++this.numberOfCorrectResponse;
} else { } else {
++this.numberOfUncorrectResponse; ++this.numberOfUncorrectResponse;
...@@ -240,10 +248,6 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -240,10 +248,6 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
return valid; return valid;
} }
public void setNumberOfGeneratedCaptchas(int numberOfGeneratedCaptchas) {
this.numberOfGeneratedCaptchas = numberOfGeneratedCaptchas;
}
public int getNumberOfCorrectResponse() { public int getNumberOfCorrectResponse() {
return numberOfCorrectResponse; return numberOfCorrectResponse;
} }
...@@ -260,10 +264,6 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -260,10 +264,6 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
this.numberOfUncorrectResponse = numberOfUncorrectResponse; this.numberOfUncorrectResponse = numberOfUncorrectResponse;
} }
public void setNumberOfGarbageCollectedCaptcha(int numberOfGarbageCollectedCaptcha) {
this.numberOfGarbageCollectedCaptcha = numberOfGarbageCollectedCaptcha;
}
public void addNumberOfGarbageCollectedCaptcha(int num) { public void addNumberOfGarbageCollectedCaptcha(int num) {
this.numberOfGarbageCollectedCaptcha += num; this.numberOfGarbageCollectedCaptcha += num;
} }
...@@ -272,7 +272,7 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe ...@@ -272,7 +272,7 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
this.numberOfUncorrectResponse += num; this.numberOfUncorrectResponse += num;
} }
public void addNumberOfCorrectResponse(int num){ public void addNumberOfCorrectResponse(int num) {
this.numberOfCorrectResponse += num; this.numberOfCorrectResponse += num;
} }
......
...@@ -26,15 +26,15 @@ public abstract class AbstractManageableImageCaptchaService extends AbstractMana ...@@ -26,15 +26,15 @@ public abstract class AbstractManageableImageCaptchaService extends AbstractMana
} }
public BufferedImage getImageChallengeForID(String ID) throws CaptchaServiceException { public BufferedImage getImageChallengeForID(String ID) throws CaptchaServiceException {
return (BufferedImage)this.getChallengeForID(ID); return (BufferedImage) this.getChallengeForID(ID);
} }
public BufferedImage getImageChallengeForID(String ID, Locale locale) throws CaptchaServiceException { public BufferedImage getImageChallengeForID(String ID, Locale locale) throws CaptchaServiceException {
return (BufferedImage)this.getChallengeForID(ID, locale); return (BufferedImage) this.getChallengeForID(ID, locale);
} }
protected Object getChallengeClone(Captcha captcha) { protected Object getChallengeClone(Captcha captcha) {
BufferedImage challenge = (BufferedImage)captcha.getChallenge(); BufferedImage challenge = (BufferedImage) captcha.getChallenge();
BufferedImage clone = new BufferedImage(challenge.getWidth(), challenge.getHeight(), challenge.getType()); BufferedImage clone = new BufferedImage(challenge.getWidth(), challenge.getHeight(), challenge.getType());
clone.getGraphics().drawImage(challenge, 0, 0, clone.getWidth(), clone.getHeight(), null); clone.getGraphics().drawImage(challenge, 0, 0, clone.getWidth(), clone.getHeight(), null);
clone.getGraphics().dispose(); clone.getGraphics().dispose();
......
...@@ -13,15 +13,24 @@ import org.springframework.stereotype.Component; ...@@ -13,15 +13,24 @@ import org.springframework.stereotype.Component;
@Component @Component
public class ApplicationContextHolder implements ApplicationContextAware { public class ApplicationContextHolder implements ApplicationContextAware {
/**
* Spring应用上下文环境
*/
private static ApplicationContext applicationContext;
@Autowired @Autowired
public ApplicationContextHolder(ApplicationContext applicationContext) { public ApplicationContextHolder(ApplicationContext applicationContext) {
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
} }
/** /**
* Spring应用上下文环境 * 获取一个ApplicationContext.
*
* @return ApplicationContext
*/ */
private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/** /**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境. * 实现ApplicationContextAware接口的回调方法,设置上下文环境.
...@@ -32,15 +41,6 @@ public class ApplicationContextHolder implements ApplicationContextAware { ...@@ -32,15 +41,6 @@ public class ApplicationContextHolder implements ApplicationContextAware {
ApplicationContextHolder.applicationContext = applicationContext; ApplicationContextHolder.applicationContext = applicationContext;
} }
/**
* 获取一个ApplicationContext.
*
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/** /**
* 根据名称获取一个对象. * 根据名称获取一个对象.
* *
......
...@@ -13,16 +13,9 @@ public class GZipUtil { ...@@ -13,16 +13,9 @@ public class GZipUtil {
private static String encode = "utf-8";//"ISO-8859-1" private static String encode = "utf-8";//"ISO-8859-1"
public String getEncode() { /**
return encode; * 字符串压缩为字节数组
} */
/** 设置 编码,默认编码:UTF-8 */
public void setEncode(String encode) {
this.encode = encode;
}
/** 字符串压缩为字节数组 */
public static byte[] compressToByte(String str) { public static byte[] compressToByte(String str) {
if (str == null || str.length() == 0) { if (str == null || str.length() == 0) {
return null; return null;
...@@ -42,7 +35,9 @@ public class GZipUtil { ...@@ -42,7 +35,9 @@ public class GZipUtil {
} }
/** 字符串压缩为字节数组 */ /**
* 字符串压缩为字节数组
*/
public static byte[] compressToByte(String str, String encoding) { public static byte[] compressToByte(String str, String encoding) {
if (str == null || str.length() == 0) { if (str == null || str.length() == 0) {
return null; return null;
...@@ -64,7 +59,9 @@ public class GZipUtil { ...@@ -64,7 +59,9 @@ public class GZipUtil {
} }
/** 字节数组解压缩后返回字符串 */ /**
* 字节数组解压缩后返回字符串
*/
public static String uncompressToString(byte[] b) { public static String uncompressToString(byte[] b) {
if (b == null || b.length == 0) { if (b == null || b.length == 0) {
return null; return null;
...@@ -90,7 +87,9 @@ public class GZipUtil { ...@@ -90,7 +87,9 @@ public class GZipUtil {
} }
/** 字节数组解压缩后返回字符串 */ /**
* 字节数组解压缩后返回字符串
*/
public static String uncompressToString(byte[] b, String encoding) { public static String uncompressToString(byte[] b, String encoding) {
if (b == null || b.length == 0) { if (b == null || b.length == 0) {
return null; return null;
...@@ -116,4 +115,15 @@ public class GZipUtil { ...@@ -116,4 +115,15 @@ public class GZipUtil {
return null; return null;
} }
public String getEncode() {
return encode;
}
/**
* 设置 编码,默认编码:UTF-8
*/
public void setEncode(String encode) {
this.encode = encode;
}
} }
...@@ -11,28 +11,29 @@ import java.util.zip.GZIPOutputStream; ...@@ -11,28 +11,29 @@ import java.util.zip.GZIPOutputStream;
public class JR58GzipUtil { public class JR58GzipUtil {
public static String bytesTogzip(byte[] bytes, String encode) { public static String bytesTogzip(byte[] bytes, String encode) {
if(bytes==null || bytes.length==0){ if (bytes == null || bytes.length == 0) {
return null; return null;
} }
ByteArrayInputStream byteArrayIn=null; ByteArrayInputStream byteArrayIn = null;
GZIPInputStream in = null; GZIPInputStream in = null;
ByteArrayOutputStream byteArrayout = new ByteArrayOutputStream(); ByteArrayOutputStream byteArrayout = new ByteArrayOutputStream();
PrintStream out= new PrintStream(byteArrayout); PrintStream out = new PrintStream(byteArrayout);
try { try {
byteArrayIn= new ByteArrayInputStream(bytes); byteArrayIn = new ByteArrayInputStream(bytes);
in = new GZIPInputStream(byteArrayIn); in = new GZIPInputStream(byteArrayIn);
byte[] b = new byte[1024]; byte[] b = new byte[1024];
int readlen = 0;; int readlen = 0;
while((readlen=in.read(b))!=-1){ ;
while ((readlen = in.read(b)) != -1) {
out.write(b, 0, readlen); out.write(b, 0, readlen);
} }
out.flush(); out.flush();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally{ } finally {
try { try {
byteArrayIn.close(); byteArrayIn.close();
in.close(); in.close();
...@@ -41,21 +42,22 @@ public class JR58GzipUtil { ...@@ -41,21 +42,22 @@ public class JR58GzipUtil {
} }
} }
System.out.println("解密后的数据:"); System.out.println("解密后的数据:");
return new String(byteArrayout.toByteArray(),Charset.forName(encode)); return new String(byteArrayout.toByteArray(), Charset.forName(encode));
} }
public static byte[] gzipTobytes(String str, String encode) { public static byte[] gzipTobytes(String str, String encode) {
if(str==null || str.length()==0){ if (str == null || str.length() == 0) {
return null; return null;
} }
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = null; GZIPOutputStream gzip = null;
try { try {
gzip= new GZIPOutputStream(out); gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encode)); gzip.write(str.getBytes(encode));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
}finally{ } finally {
try { try {
gzip.close(); gzip.close();
} catch (IOException e) { } catch (IOException e) {
......
package cn.quantgroup.xyqb.util; package cn.quantgroup.xyqb.util;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Map; import java.util.Map;
/** /**
......
server.port=8080 server.port=8080
security.sessions=if_required security.sessions=if_required
spring.aop.proxy-target-class=true spring.aop.proxy-target-class=true
configserver.disable=1 configserver.disable=1
configserver.system=xyqb-user configserver.system=xyqb-user
xyqb.data.mysql.jdbc-url=jdbc:mysql://192.168.4.104:3306/xyqb_user?useUnicode=true&characterEncoding=UTF8 xyqb.data.mysql.jdbc-url=jdbc:mysql://192.168.4.163:3306/xyqb_user?useUnicode=true&characterEncoding=UTF8
xyqb.data.mysql.password=qatest xyqb.data.mysql.password=qatest
...@@ -15,7 +15,7 @@ xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If- ...@@ -15,7 +15,7 @@ xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-
xyqb.data.redis.defaultExpiration=3600 xyqb.data.redis.defaultExpiration=3600
# redis # redis
xyqb.redis.master.host=192.168.4.13 xyqb.redis.master.host=192.168.4.163
xyqb.redis.master.port=6379 xyqb.redis.master.port=6379
xyqb.redis.master.name= xyqb.redis.master.name=
xyqb.redis.sentinel1.host= xyqb.redis.sentinel1.host=
...@@ -29,7 +29,7 @@ xyqb.redis.sentinel3.port=0 ...@@ -29,7 +29,7 @@ xyqb.redis.sentinel3.port=0
sms.is.debug=1 sms.is.debug=1
# LKB client # LKB client
lkb.client.url=http://192.168.192.251:8082/LKBClient/openapi lkb.client.url=http://192.168.192.163:8082/LKBClient/openapi
lkb.client.user.register.app=/new/register/registerApp.json lkb.client.user.register.app=/new/register/registerApp.json
lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json
lkb.client.user.update=/new/register/updateUser.json lkb.client.user.update=/new/register/updateUser.json
...@@ -42,9 +42,9 @@ lkb.url=http://192.168.192.251:8081/LKB ...@@ -42,9 +42,9 @@ lkb.url=http://192.168.192.251:8081/LKB
lkb.entrypoint.jr58=/jr58/arc_all.html lkb.entrypoint.jr58=/jr58/arc_all.html
# xyqb # xyqb
xyqb.url=http://192.168.192.206:8999 xyqb.url=http://192.168.192.163:8999
xyqb.api.url=http://192.168.192.206:9004 xyqb.api.url=http://192.168.192.163:9004
# JR58 # JR58
jr58.sign.key=MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKG/Y0J/c+JguU6cPdFHRC9eHrkgaZ9bpYpeQVujBpL+OkA8pAQTZ1XhoLZu/IH4Rv2kx85e8WVF7FxIFkgqJobjvai2XsD7QRYHGb6EEsqjROPndxnlpLeXmyp+WvbPhtRMoLyP3bZncaR1xsPkmW4ajXSUCa4+qlEfrEMskG79AgMBAAECgYAYmA5StSh8unJSxqULpkdy4F/RjGEjDv9by7sqYN6GCUv4KoBR8lVbFKSoOLYCWSsKND0BXyRbXsdyvK9Op8IVsKIbUnpen5V2cgNrVhlomy7E7RFSdoyFcRuWzck0NGtjJLPzi4qztiKprFH8yMf3tfD8aEKMo7pFpqetGfkezQJBANZTUTiGePRsiO7igin92jf9pWeSiI9OecQ/9hxwIlXXxQAwMUcvvyjoKfp6TRs3HlYugoiP/5VwTWRM/iTbf18CQQDBMtpKI5NtgrpfqbN2czP35S7VOnYO0QofEEuLj3oVCo2CxXfz0cViY/ng3BFk/oTykbMmS/TxCD5VHi17QRsjAkEAv9/3ZtN8ldZVAQhn35AUPOwnmIHnH+TxvnBEtVDubEuvYmvCsihcyxKOAmBbh3HhBua8leXUusS/hHwpSnX3oQJAc4eLTYZUpMnl1UrPjGd7jiO4i72310hduxGtezlDEc4LrUWUY3Lvi9SpGjO/GxuwOLWz4ZTOVkxNqeyv2eKm7QJAQHvgO0ciDFuFuhahFli7ktyZcn5CV8PPkQrbMXUFrMbX3AP61HPyH9EGCqBvsdyRYqPxFseDFY3yYveOWMPq0Q== jr58.sign.key=MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKG/Y0J/c+JguU6cPdFHRC9eHrkgaZ9bpYpeQVujBpL+OkA8pAQTZ1XhoLZu/IH4Rv2kx85e8WVF7FxIFkgqJobjvai2XsD7QRYHGb6EEsqjROPndxnlpLeXmyp+WvbPhtRMoLyP3bZncaR1xsPkmW4ajXSUCa4+qlEfrEMskG79AgMBAAECgYAYmA5StSh8unJSxqULpkdy4F/RjGEjDv9by7sqYN6GCUv4KoBR8lVbFKSoOLYCWSsKND0BXyRbXsdyvK9Op8IVsKIbUnpen5V2cgNrVhlomy7E7RFSdoyFcRuWzck0NGtjJLPzi4qztiKprFH8yMf3tfD8aEKMo7pFpqetGfkezQJBANZTUTiGePRsiO7igin92jf9pWeSiI9OecQ/9hxwIlXXxQAwMUcvvyjoKfp6TRs3HlYugoiP/5VwTWRM/iTbf18CQQDBMtpKI5NtgrpfqbN2czP35S7VOnYO0QofEEuLj3oVCo2CxXfz0cViY/ng3BFk/oTykbMmS/TxCD5VHi17QRsjAkEAv9/3ZtN8ldZVAQhn35AUPOwnmIHnH+TxvnBEtVDubEuvYmvCsihcyxKOAmBbh3HhBua8leXUusS/hHwpSnX3oQJAc4eLTYZUpMnl1UrPjGd7jiO4i72310hduxGtezlDEc4LrUWUY3Lvi9SpGjO/GxuwOLWz4ZTOVkxNqeyv2eKm7QJAQHvgO0ciDFuFuhahFli7ktyZcn5CV8PPkQrbMXUFrMbX3AP61HPyH9EGCqBvsdyRYqPxFseDFY3yYveOWMPq0Q==
...@@ -70,3 +70,18 @@ usersys.url=http://localhost:9001 ...@@ -70,3 +70,18 @@ usersys.url=http://localhost:9001
xyqb-user.ui=http://192.168.100.36:7043 xyqb-user.ui=http://192.168.100.36:7043
wechat.appid=wxcdf6077af8127559 wechat.appid=wxcdf6077af8127559
wechat.secret=16eaec16084d0d9c52d4114f359cc72c wechat.secret=16eaec16084d0d9c52d4114f359cc72c
#motan protocol
protocol.name=motan
protocol.contentLength=1048576
protocol.isDefault=true
#motan registry center
registry.protocol=zookeeper
registry.address=192.168.4.163:2181
motan.port=8086
motan.user.group=userGroup
motan.user.module=user-motan-rpc
motan.application=xyqbUserMotan
#xyqb-user-域名
xyqb.user.domain=passport.xyqb.com
\ No newline at end of file
server.port=9001 server.port=9001
security.sessions=if_required security.sessions=if_required
server.session-timeout=5184000 server.session-timeout=5184000
spring.aop.proxy-target-class=true spring.aop.proxy-target-class=true
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
<logger name="ch.qos.logback" level="warn"/> <logger name="ch.qos.logback" level="warn"/>
<root level="info"> <root level="info">
<appender-ref ref="FILE" /> <appender-ref ref="FILE"/>
</root> </root>
</configuration> </configuration>
\ No newline at end of file
configserver.disable=0 configserver.disable=0
configserver.system=xyqb-user configserver.system=xyqb-user
xyqb.data.mysql.max-pool-size=1000 xyqb.data.mysql.max-pool-size=1000
# CORS # CORS
xyqb.filter.allowedOrigin=* xyqb.filter.allowedOrigin=*
xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,Authorization xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,Authorization
xyqb.data.redis.defaultExpiration=3600 xyqb.data.redis.defaultExpiration=3600
# redis # redis
xyqb.redis.master.host=172.16.1.179 xyqb.redis.master.host=172.16.1.179
xyqb.redis.master.port=6373 xyqb.redis.master.port=6373
...@@ -19,34 +15,38 @@ xyqb.redis.sentinel2.host=172.16.1.180 ...@@ -19,34 +15,38 @@ xyqb.redis.sentinel2.host=172.16.1.180
xyqb.redis.sentinel2.port=26373 xyqb.redis.sentinel2.port=26373
xyqb.redis.sentinel3.host=172.16.1.181 xyqb.redis.sentinel3.host=172.16.1.181
xyqb.redis.sentinel3.port=26373 xyqb.redis.sentinel3.port=26373
# 短信平台配置 # 短信平台配置
sms.is.debug=0 sms.is.debug=0
# LKB client # LKB client
lkb.client.url=http://openapi.quantgroup.cn/LKBClient/openapi lkb.client.url=http://openapi.quantgroup.cn/LKBClient/openapi
lkb.client.user.register.app=/new/register/registerApp.json lkb.client.user.register.app=/new/register/registerApp.json
lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json
lkb.client.user.update=/new/register/updateUser.json lkb.client.user.update=/new/register/updateUser.json
# LKB import # LKB import
lkb.import.url=http://spider.quantgroup.cn lkb.import.url=http://spider.quantgroup.cn
# LKB # LKB
lkb.url=http://58.xyqb.com/LKB lkb.url=http://58.xyqb.com/LKB
lkb.entrypoint.jr58=/jr58/arc_all.html lkb.entrypoint.jr58=/jr58/arc_all.html
# xyqb # xyqb
xyqb.url=http://m.xyqb.com xyqb.url=http://m.xyqb.com
xyqb.api.url=http://api.xyqb.com xyqb.api.url=http://api.xyqb.com
# JR58 # JR58
jr58.notify.userinfo=http://dk.58.com/customer/quantgroup_user_info jr58.notify.userinfo=http://dk.58.com/customer/quantgroup_user_info
#sdk #sdk
model.quantgroup.url=http://model.quantgroup.cn model.quantgroup.url=http://model.quantgroup.cn
xyqb.auth.url=http://auth.xyqb.com xyqb.auth.url=http://auth.xyqb.com
xyqb-user.ui=http://passport.xyqb.com xyqb-user.ui=http://passport.xyqb.com
#motan protocol
protocol.name=motan
protocol.contentLength=1048576
protocol.isDefault=true
#motan registry center
registry.protocol=zookeeper
registry.address=172.16.1.63:2181,172.16.1.64:2181,172.16.1.65:2181
motan.port=8082
motan.user.group=userGroup
motan.user.module=user-motan-rpc
motan.application=xyqbUserMotan
#xyqb-user-域名
xyqb.user.domain=passport.xyqb.com
\ No newline at end of file
server.port=9001 server.port=9001
security.sessions=if_required security.sessions=if_required
spring.aop.proxy-target-class=true spring.aop.proxy-target-class=true
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
<logger name="ch.qos.logback" level="warn"/> <logger name="ch.qos.logback" level="warn"/>
<root level="info"> <root level="info">
<appender-ref ref="FILE" /> <appender-ref ref="FILE"/>
</root> </root>
</configuration> </configuration>
\ No newline at end of file
configserver.disable=1 configserver.disable=1
configserver.system=xyqb-user configserver.system=xyqb-user
xyqb.data.mysql.jdbc-url=jdbc:mysql://192.168.4.104:3306/xyqb_user?useUnicode=true&characterEncoding=UTF8 xyqb.data.mysql.jdbc-url=jdbc:mysql://192.168.4.104:3306/xyqb_user?useUnicode=true&characterEncoding=UTF8
xyqb.data.mysql.password=qatest xyqb.data.mysql.password=qatest
xyqb.data.mysql.user=qa xyqb.data.mysql.user=qa
xyqb.data.mysql.max-pool-size=20 xyqb.data.mysql.max-pool-size=20
# CORS # CORS
xyqb.filter.allowedOrigin=* xyqb.filter.allowedOrigin=*
xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,Authorization xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,Authorization
xyqb.data.redis.defaultExpiration=3600 xyqb.data.redis.defaultExpiration=3600
# redis # redis
xyqb.redis.master.host=192.168.4.103 xyqb.redis.master.host=192.168.4.103
xyqb.redis.master.port=6379 xyqb.redis.master.port=6379
...@@ -24,49 +18,37 @@ xyqb.redis.sentinel2.host= ...@@ -24,49 +18,37 @@ xyqb.redis.sentinel2.host=
xyqb.redis.sentinel2.port=0 xyqb.redis.sentinel2.port=0
xyqb.redis.sentinel3.host= xyqb.redis.sentinel3.host=
xyqb.redis.sentinel3.port=0 xyqb.redis.sentinel3.port=0
# 短信平台配置 # 短信平台配置
sms.is.debug=1 sms.is.debug=1
# LKB client # LKB client
lkb.client.url=http://192.168.192.251:8082/LKBClient/openapi lkb.client.url=http://192.168.192.251:8082/LKBClient/openapi
lkb.client.user.register.app=/new/register/registerApp.json lkb.client.user.register.app=/new/register/registerApp.json
lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json
lkb.client.user.update=/new/register/updateUser.json lkb.client.user.update=/new/register/updateUser.json
# LKB import # LKB import
lkb.import.url=http://spider.quantgroup.cn lkb.import.url=http://spider.quantgroup.cn
# LKB # LKB
lkb.url=http://192.168.192.251:8081/LKB lkb.url=http://192.168.192.251:8081/LKB
lkb.entrypoint.jr58=/jr58/arc_all.html lkb.entrypoint.jr58=/jr58/arc_all.html
# xyqb # xyqb
xyqb.url=http://192.168.192.206:8999 xyqb.url=http://192.168.192.206:8999
xyqb.api.url=http://192.168.192.206:9004 xyqb.api.url=http://192.168.192.206:9004
# JR58 # JR58
jr58.sign.key=MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKG/Y0J/c+JguU6cPdFHRC9eHrkgaZ9bpYpeQVujBpL+OkA8pAQTZ1XhoLZu/IH4Rv2kx85e8WVF7FxIFkgqJobjvai2XsD7QRYHGb6EEsqjROPndxnlpLeXmyp+WvbPhtRMoLyP3bZncaR1xsPkmW4ajXSUCa4+qlEfrEMskG79AgMBAAECgYAYmA5StSh8unJSxqULpkdy4F/RjGEjDv9by7sqYN6GCUv4KoBR8lVbFKSoOLYCWSsKND0BXyRbXsdyvK9Op8IVsKIbUnpen5V2cgNrVhlomy7E7RFSdoyFcRuWzck0NGtjJLPzi4qztiKprFH8yMf3tfD8aEKMo7pFpqetGfkezQJBANZTUTiGePRsiO7igin92jf9pWeSiI9OecQ/9hxwIlXXxQAwMUcvvyjoKfp6TRs3HlYugoiP/5VwTWRM/iTbf18CQQDBMtpKI5NtgrpfqbN2czP35S7VOnYO0QofEEuLj3oVCo2CxXfz0cViY/ng3BFk/oTykbMmS/TxCD5VHi17QRsjAkEAv9/3ZtN8ldZVAQhn35AUPOwnmIHnH+TxvnBEtVDubEuvYmvCsihcyxKOAmBbh3HhBua8leXUusS/hHwpSnX3oQJAc4eLTYZUpMnl1UrPjGd7jiO4i72310hduxGtezlDEc4LrUWUY3Lvi9SpGjO/GxuwOLWz4ZTOVkxNqeyv2eKm7QJAQHvgO0ciDFuFuhahFli7ktyZcn5CV8PPkQrbMXUFrMbX3AP61HPyH9EGCqBvsdyRYqPxFseDFY3yYveOWMPq0Q== jr58.sign.key=MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKG/Y0J/c+JguU6cPdFHRC9eHrkgaZ9bpYpeQVujBpL+OkA8pAQTZ1XhoLZu/IH4Rv2kx85e8WVF7FxIFkgqJobjvai2XsD7QRYHGb6EEsqjROPndxnlpLeXmyp+WvbPhtRMoLyP3bZncaR1xsPkmW4ajXSUCa4+qlEfrEMskG79AgMBAAECgYAYmA5StSh8unJSxqULpkdy4F/RjGEjDv9by7sqYN6GCUv4KoBR8lVbFKSoOLYCWSsKND0BXyRbXsdyvK9Op8IVsKIbUnpen5V2cgNrVhlomy7E7RFSdoyFcRuWzck0NGtjJLPzi4qztiKprFH8yMf3tfD8aEKMo7pFpqetGfkezQJBANZTUTiGePRsiO7igin92jf9pWeSiI9OecQ/9hxwIlXXxQAwMUcvvyjoKfp6TRs3HlYugoiP/5VwTWRM/iTbf18CQQDBMtpKI5NtgrpfqbN2czP35S7VOnYO0QofEEuLj3oVCo2CxXfz0cViY/ng3BFk/oTykbMmS/TxCD5VHi17QRsjAkEAv9/3ZtN8ldZVAQhn35AUPOwnmIHnH+TxvnBEtVDubEuvYmvCsihcyxKOAmBbh3HhBua8leXUusS/hHwpSnX3oQJAc4eLTYZUpMnl1UrPjGd7jiO4i72310hduxGtezlDEc4LrUWUY3Lvi9SpGjO/GxuwOLWz4ZTOVkxNqeyv2eKm7QJAQHvgO0ciDFuFuhahFli7ktyZcn5CV8PPkQrbMXUFrMbX3AP61HPyH9EGCqBvsdyRYqPxFseDFY3yYveOWMPq0Q==
jr58.notify.userinfo=http://xfd.test.58v5.cn/customer/quantgroup_user_info jr58.notify.userinfo=http://xfd.test.58v5.cn/customer/quantgroup_user_info
# 图形验证码 # 图形验证码
# 是否启用超级验证码 "__SUPERQG__", 用于测试环境自动化测试, 线上环境可忽略此参数 # 是否启用超级验证码 "__SUPERQG__", 用于测试环境自动化测试, 线上环境可忽略此参数
xyqb.auth.captcha.super.enable=1 xyqb.auth.captcha.super.enable=1
#首参数校验 #首参数校验
xyqb.fplock.limit.byhour=3 xyqb.fplock.limit.byhour=3
xyqb.fplock.limit.byday=5 xyqb.fplock.limit.byday=5
#sdk #sdk
model.quantgroup.url=http://model.quantgroup.cn model.quantgroup.url=http://model.quantgroup.cn
xyqb.auth.url=http://192.168.192.206:9001 xyqb.auth.url=http://192.168.192.206:9001
usersys.url=http://localhost:9001 usersys.url=http://localhost:9001
xyqb-user.ui=http://192.168.12.40:8080 xyqb-user.ui=http://192.168.12.40:8080
wechat.appid=wxcdf6077af8127559 wechat.appid=wxcdf6077af8127559
wechat.secret=16eaec16084d0d9c52d4114f359cc72c wechat.secret=16eaec16084d0d9c52d4114f359cc72c
#xyqb-user-域名
xyqb.user.domain=passport.xyqb.com
\ No newline at end of file
...@@ -8,11 +8,9 @@ import org.junit.Assert; ...@@ -8,11 +8,9 @@ import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import javax.validation.constraints.AssertTrue;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Bootstrap.class) @SpringApplicationConfiguration(classes = Bootstrap.class)
......
...@@ -4,8 +4,6 @@ import cn.quantgroup.xyqb.Bootstrap; ...@@ -4,8 +4,6 @@ import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.controller.internal.user.UserController; import cn.quantgroup.xyqb.controller.internal.user.UserController;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
...@@ -20,22 +18,13 @@ import org.springframework.test.context.web.WebAppConfiguration; ...@@ -20,22 +18,13 @@ import org.springframework.test.context.web.WebAppConfiguration;
@WebAppConfiguration @WebAppConfiguration
public class TestUserLogin { public class TestUserLogin {
private static final Logger LOGGER = LoggerFactory.getLogger(TestUserLogin.class);
private MockHttpServletRequest request; private MockHttpServletRequest request;
@Autowired @Autowired
private UserController userController; private UserController userController;
@Test @Test
public void testLogAppender(){ public void testUserLogin() {
LOGGER.info("test customer logger appender:[{}]",74646);
System.out.println("%%%%%%");
}
@Test
public void testUserLogin(){
//访问xyqb-user拿到登录token //访问xyqb-user拿到登录token
/*Long channelId = 1L; /*Long channelId = 1L;
String appChannel = "3"; String appChannel = "3";
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment