Commit 0c674924 authored by Java-刘 彧阳's avatar Java-刘 彧阳

Merge branch 'master' into xyqb-user2-userCenter

Conflicts:
	src/main/java/cn/quantgroup/xyqb/filter/RequestFilter.java
parents 32ba5adf f9d7da72
<?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">
<modelVersion>4.0.0</modelVersion>
......@@ -40,6 +40,12 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
......@@ -207,6 +213,78 @@
<artifactId>quantgroup-config-sdk</artifactId>
<version>1.0.3-SNAPSHOT</version>
</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>
<build>
......@@ -249,49 +327,49 @@
</build>
</profile>
<profile>
<id>dev</id>
<properties>
<profiles.activation>dev</profiles.activation>
</properties>
<dependencies>
<dependency>
<groupId>cn.quantgroup</groupId>
<artifactId>quantgroup-sms-sdk</artifactId>
<version>2.0.0.3-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>
${project.basedir}/src/main/resources/config/dev
</directory>
</resource>
</resources>
</build>
</profile>
<profile>
<id>test</id>
<properties>
<profiles.activation>test</profiles.activation>
</properties>
<dependencies>
<dependency>
<groupId>cn.quantgroup</groupId>
<artifactId>quantgroup-sms-sdk</artifactId>
<version>1.0.5-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>
${project.basedir}/src/main/resources/config/test
</directory>
</resource>
</resources>
</build>
</profile>
<id>dev</id>
<properties>
<profiles.activation>dev</profiles.activation>
</properties>
<dependencies>
<dependency>
<groupId>cn.quantgroup</groupId>
<artifactId>quantgroup-sms-sdk</artifactId>
<version>2.0.0.3-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>
${project.basedir}/src/main/resources/config/dev
</directory>
</resource>
</resources>
</build>
</profile>
<profile>
<id>test</id>
<properties>
<profiles.activation>test</profiles.activation>
</properties>
<dependencies>
<dependency>
<groupId>cn.quantgroup</groupId>
<artifactId>quantgroup-sms-sdk</artifactId>
<version>1.0.5-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>
${project.basedir}/src/main/resources/config/test
</directory>
</resource>
</resources>
</build>
</profile>
</profiles>
</project>
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.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.EnableAsync;
@ComponentScan(basePackages = {"cn.quantgroup.xyqb", "cn.quantgroup.cloudconfig"})
......@@ -18,9 +23,20 @@ import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAspectJAutoProxy
@EnableAsync
@Slf4j
public class Bootstrap {
public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args);
}
public static void main(String[] 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;
/**
* Created by Miraculous on 15/7/5.
*/
public interface Constants {
// zero fill with 4 chars...
String ZERO_FILL_TEMPLATE = "%04d";
String PASSWORD_SALT = "_lkb";
String IMAGE_CAPTCHA_KEY = "img_captcha:";
String REDIS_CAPTCHA_KEY = "auth:";
String REDIS_CAPTCHA_KEY_PATTERN = REDIS_CAPTCHA_KEY + IMAGE_CAPTCHA_KEY + "*";
String CONFIG_CAPTCHA = "cfg_captcha_%";
// app 后端白名单
String CONFIG_CAPTCHA_WHITEIP_LIST = "cfg_captcha_white_ip_appbackend";
// 每个 IP 每分钟 captcha 限制
String CONFIG_CAPTCHA_PERIP_PERMIN = "cfg_captcha_per_ip_per_min";
// 是否启用万能验证码
String CONFIG_CAPTCHA_MAGIC_CODE_ENABLED = "cfg_captcha_magic_code_enabled";
String REDIS_PREFIX_VERIFICATION_CODE = "verificationCode_";
/**
* redis中token的key值前缀
*/
String SESSION_PREFIX = "spring:session:sessions:";
interface Jr58 {
int ERROR_PHONE_NUMBER = 20007; // 手机号码格式不正确
int ERROR_ID_CARD = 20009; // 身份证格式不正确
int ERROR_ACCOUNT = 20010; // 授权账号为空
int ERROR_AUTH_TYPE = 20011; // 授权类型为空
}
interface Channel {
long LKB = 1; // 量化派
long JR58 = 175; // 58金融
long BAITIAO = 222L;
String LKB_CODE = "0002"; // 量化派channnel_code
long WECHAT = 198L;
}
interface Session{
String USER_SESSION_CACHE = "user:session:";
String USER_SESSION_ID_CACHE = "userid-sessionvalue:cache:";
Long ONE_DAY = 24 * 60 * 60L;
}
interface WeChat {
String APP_ID = "wx0a7c0bce0c3ac523";
String REDIRECT_URL = "http://wechattest.xyqb.com/webchat/receiveCode";
String SCOPE = "snsapi_userinfo";
}
// zero fill with 4 chars...
String ZERO_FILL_TEMPLATE = "%04d";
String PASSWORD_SALT = "_lkb";
String IMAGE_CAPTCHA_KEY = "img_captcha:";
String REDIS_CAPTCHA_KEY = "auth:";
String REDIS_CAPTCHA_KEY_PATTERN = REDIS_CAPTCHA_KEY + IMAGE_CAPTCHA_KEY + "*";
String CONFIG_CAPTCHA = "cfg_captcha_%";
// app 后端白名单
String CONFIG_CAPTCHA_WHITEIP_LIST = "cfg_captcha_white_ip_appbackend";
// 每个 IP 每分钟 captcha 限制
String CONFIG_CAPTCHA_PERIP_PERMIN = "cfg_captcha_per_ip_per_min";
// 是否启用万能验证码
String CONFIG_CAPTCHA_MAGIC_CODE_ENABLED = "cfg_captcha_magic_code_enabled";
String REDIS_PREFIX_VERIFICATION_CODE = "verificationCode_";
/**
* redis中token的key值前缀
*/
String SESSION_PREFIX = "spring:session:sessions:";
interface Jr58 {
int ERROR_PHONE_NUMBER = 20007; // 手机号码格式不正确
int ERROR_ID_CARD = 20009; // 身份证格式不正确
int ERROR_ACCOUNT = 20010; // 授权账号为空
int ERROR_AUTH_TYPE = 20011; // 授权类型为空
}
interface Channel {
long LKB = 1; // 量化派
long JR58 = 175; // 58金融
long BAITIAO = 222L;
String LKB_CODE = "0002"; // 量化派channnel_code
long WECHAT = 198L;
}
interface Session {
String USER_SESSION_CACHE = "user:session:";
String USER_SESSION_ID_CACHE = "userid-sessionvalue:cache:";
Long ONE_DAY = 24 * 60 * 60L;
}
interface WeChat {
String APP_ID = "wx0a7c0bce0c3ac523";
String REDIRECT_URL = "http://wechattest.xyqb.com/webchat/receiveCode";
String SCOPE = "snsapi_userinfo";
}
interface UserAvatar {
String AVATAR_DEFAULT = "https://avatar.xyqb.com/default_avatar.png";
......
......@@ -40,82 +40,82 @@ import java.util.UUID;
@Component
public class CaptchaValidateAdvisor {
private static final Logger LOGGER = LoggerFactory.getLogger(CaptchaValidateAdvisor.class);
private static final String SUPER_CAPTCHA_ID = UUID.nameUUIDFromBytes("__QG_APPCLIENT_AGENT__".getBytes(Charset.forName("UTF-8"))).toString();
private static final String SUPER_CAPTCHA = "__SUPERQG__";
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate;
@Autowired
@Qualifier("customCaptchaService")
private AbstractManageableImageCaptchaService imageCaptchaService;
/**
* 自动化测试忽略验证码
*/
@Value("${xyqb.auth.captcha.autotest.enable:false}")
private boolean autoTestCaptchaEnabled;
/**
* 图形验证码切面
*/
@Pointcut("@annotation(cn.quantgroup.xyqb.aspect.captcha.CaptchaValidator)")
private void needCaptchaValidate() {
private static final Logger LOGGER = LoggerFactory.getLogger(CaptchaValidateAdvisor.class);
private static final String SUPER_CAPTCHA_ID = UUID.nameUUIDFromBytes("__QG_APPCLIENT_AGENT__".getBytes(Charset.forName("UTF-8"))).toString();
private static final String SUPER_CAPTCHA = "__SUPERQG__";
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate;
@Autowired
@Qualifier("customCaptchaService")
private AbstractManageableImageCaptchaService imageCaptchaService;
/**
* 自动化测试忽略验证码
*/
@Value("${xyqb.auth.captcha.autotest.enable:false}")
private boolean autoTestCaptchaEnabled;
/**
* 图形验证码切面
*/
@Pointcut("@annotation(cn.quantgroup.xyqb.aspect.captcha.CaptchaValidator)")
private void needCaptchaValidate() {
}
/**
* 在受图形验证码保护的接口方法执行前, 执行图形验证码校验
*
* @param pjp
* @return
* @throws Throwable
*/
@Around("needCaptchaValidate()")
private Object doCapchaValidate(ProceedingJoinPoint pjp) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String registerFrom = Optional.ofNullable(request.getParameter("registerFrom")).orElse("");
String captchaId = Optional.ofNullable(request.getParameter("captchaId")).orElse("");
Object captchaValue = request.getParameter("captchaValue");
if (shouldSkipCaptchaValidate(registerFrom, captchaId, captchaValue)) {
LOGGER.info("使用超级图形验证码校验, registerFrom={}, clientIp={}", registerFrom, request.getRemoteAddr());
return pjp.proceed();
}
/**
* 在受图形验证码保护的接口方法执行前, 执行图形验证码校验
*
* @param pjp
* @return
* @throws Throwable
*/
@Around("needCaptchaValidate()")
private Object doCapchaValidate(ProceedingJoinPoint pjp) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String registerFrom = Optional.ofNullable(request.getParameter("registerFrom")).orElse("");
String captchaId = Optional.ofNullable(request.getParameter("captchaId")).orElse("");
Object captchaValue = request.getParameter("captchaValue");
if (shouldSkipCaptchaValidate(registerFrom, captchaId, captchaValue)) {
LOGGER.info("使用超级图形验证码校验, registerFrom={}, clientIp={}", registerFrom, request.getRemoteAddr());
return pjp.proceed();
}
JsonResult result = JsonResult.buildSuccessResult("图形验证码错误, 请重新输入", "");
result.setBusinessCode("0002");
if (captchaValue != null) {
String captcha = String.valueOf(captchaValue);
// 忽略用户输入的大小写
captcha = StringUtils.lowerCase(captcha);
// 验证码校验
Boolean validCaptcha = false;
try {
validCaptcha = imageCaptchaService.validateResponseForID(Constants.IMAGE_CAPTCHA_KEY + captchaId, captcha);
} catch (CaptchaServiceException ex) {
LOGGER.error("验证码校验异常, {}, {}", ex.getMessage(), ex);
}
if (validCaptcha) {
return pjp.proceed();
}
}
return result;
JsonResult result = JsonResult.buildSuccessResult("图形验证码错误, 请重新输入", "");
result.setBusinessCode("0002");
if (captchaValue != null) {
String captcha = String.valueOf(captchaValue);
// 忽略用户输入的大小写
captcha = StringUtils.lowerCase(captcha);
// 验证码校验
Boolean validCaptcha = false;
try {
validCaptcha = imageCaptchaService.validateResponseForID(Constants.IMAGE_CAPTCHA_KEY + captchaId, captcha);
} catch (CaptchaServiceException ex) {
LOGGER.error("验证码校验异常, {}, {}", ex.getMessage(), ex);
}
if (validCaptcha) {
return pjp.proceed();
}
}
private boolean shouldSkipCaptchaValidate(String registerFrom, String captchaId, Object captchaValue) {
return result;
}
// 如果启用了超级验证码功能, 检查超级验证码, 超级验证码区分大小写
if (autoTestCaptchaEnabled) {
return true;
}
private boolean shouldSkipCaptchaValidate(String registerFrom, String captchaId, Object captchaValue) {
return StringUtils.equals(SUPER_CAPTCHA_ID, String.valueOf(captchaId)) && StringUtils.equals(SUPER_CAPTCHA, String.valueOf(captchaValue));
// 如果启用了超级验证码功能, 检查超级验证码, 超级验证码区分大小写
if (autoTestCaptchaEnabled) {
return true;
}
return StringUtils.equals(SUPER_CAPTCHA_ID, String.valueOf(captchaId)) && StringUtils.equals(SUPER_CAPTCHA, String.valueOf(captchaValue));
}
}
package cn.quantgroup.xyqb.aspect.captcha;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.*;
/**
* 类名称:CaptchaValidate
......
package cn.quantgroup.xyqb.aspect.fplock;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.*;
/**
* Created by Miraculous on 15/11/10.
......@@ -14,6 +10,7 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
public @interface FPLock {
String uniqueName();
FPRestriction[] restrictions() default {};
String uniqueName();
FPRestriction[] restrictions() default {};
}
package cn.quantgroup.xyqb.aspect.fplock;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;
/**
......@@ -14,12 +10,15 @@ import java.util.concurrent.TimeUnit;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FPRestriction {
// 持续时间
int duration() default 1;
// 持续时间单位
TimeUnit type() default TimeUnit.MINUTES;
// 限制值, -1表示不限制
int limit() default -1;
// 使用可覆盖
boolean override() default true;
// 持续时间
int duration() default 1;
// 持续时间单位
TimeUnit type() default TimeUnit.MINUTES;
// 限制值, -1表示不限制
int limit() default -1;
// 使用可覆盖
boolean override() default true;
}
......@@ -23,23 +23,23 @@ import org.springframework.data.redis.core.RedisTemplate;
@Configuration
public class CaptchaConfig {
@Bean
public CaptchaEngine initCaptchaEngine() {
return new CustomJCaptchaEngine();
}
@Bean
public CaptchaEngine initCaptchaEngine() {
return new CustomJCaptchaEngine();
}
@Bean
@Autowired
@Qualifier("stringRedisTemplate")
public CaptchaStore initStringCaptchaStore(RedisTemplate<String, String> stringRedisTemplate) {
return new RedisCaptchaStore(stringRedisTemplate);
}
@Bean
@Autowired
@Qualifier("stringRedisTemplate")
public CaptchaStore initStringCaptchaStore(RedisTemplate<String, String> stringRedisTemplate) {
return new RedisCaptchaStore(stringRedisTemplate);
}
@Bean(name = "customCaptchaService")
@Autowired
public AbstractManageableImageCaptchaService initCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine) {
return new CustomJCaptchaService(captchaStore, captchaEngine);
}
@Bean(name = "customCaptchaService")
@Autowired
public AbstractManageableImageCaptchaService initCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine) {
return new CustomJCaptchaService(captchaStore, captchaEngine);
}
}
......@@ -35,44 +35,44 @@ import java.awt.image.ImageFilter;
*/
public class CustomJCaptchaEngine extends ListImageCaptchaEngine {
private static final int MIN_WORD_LEN = 4;
private static final int MAX_WORD_LEN = 4;
private static final int MIN_WORD_LEN = 4;
private static final int MAX_WORD_LEN = 4;
@Override
protected void buildInitialFactories() {
int minWordLength = 4;
int maxWordLength = 4;
int fontSize = 16;
int imageWidth = 80;
int imageHeight = 28;
WordGenerator wordGenerator = new RandomWordGenerator("1234567890");
SingleColorGenerator colorGenerator = new SingleColorGenerator(Color.WHITE);
@Override
protected void buildInitialFactories() {
int minWordLength = 4;
int maxWordLength = 4;
int fontSize = 16;
int imageWidth = 80;
int imageHeight = 28;
WordGenerator wordGenerator = new RandomWordGenerator("1234567890");
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);//曲线干扰
// TextDecorator[] textDecorators = new TextDecorator[]{baffleTextDecorator, lineTextDecorator};
TextDecorator[] textDecorators = new TextDecorator[]{baffleTextDecorator};
TextDecorator[] textDecorators = new TextDecorator[]{baffleTextDecorator};
TextPaster randomPaster = new DecoratedRandomTextPaster(minWordLength,
maxWordLength, new RandomListColorGenerator(new Color[]{
new Color(23, 170, 27), new Color(220, 34, 11),
new Color(23, 67, 172)}), textDecorators);
TextPaster randomPaster = new DecoratedRandomTextPaster(minWordLength,
maxWordLength, new RandomListColorGenerator(new Color[]{
new Color(23, 170, 27), new Color(220, 34, 11),
new Color(23, 67, 172)}), textDecorators);
BackgroundGenerator background = new UniColorBackgroundGenerator(imageWidth, imageHeight, colorGenerator);
FontGenerator font = new RandomFontGenerator(fontSize, fontSize,
new Font[]{new Font("nyala", Font.BOLD, fontSize),
new Font("Bell MT", Font.PLAIN, fontSize),
new Font("Credit valley", Font.BOLD, fontSize)});
BackgroundGenerator background = new UniColorBackgroundGenerator(imageWidth, imageHeight, colorGenerator);
FontGenerator font = new RandomFontGenerator(fontSize, fontSize,
new Font[]{new Font("nyala", Font.BOLD, fontSize),
new Font("Bell MT", Font.PLAIN, fontSize),
new Font("Credit valley", Font.BOLD, fontSize)});
ImageDeformation postDef = new ImageDeformationByFilters(new ImageFilter[]{});
ImageDeformation backDef = new ImageDeformationByFilters(new ImageFilter[]{});
ImageDeformation textDef = new ImageDeformationByFilters(new ImageFilter[]{});
ImageDeformation postDef = new ImageDeformationByFilters(new ImageFilter[]{});
ImageDeformation backDef = new ImageDeformationByFilters(new ImageFilter[]{});
ImageDeformation textDef = new ImageDeformationByFilters(new ImageFilter[]{});
WordToImage word2image = new DeformedComposedWordToImage(font,
background, randomPaster, backDef, textDef, postDef);
addFactory(new CustomGimpyFactory(wordGenerator, word2image));
}
WordToImage word2image = new DeformedComposedWordToImage(font,
background, randomPaster, backDef, textDef, postDef);
addFactory(new CustomGimpyFactory(wordGenerator, word2image));
}
}
......@@ -24,84 +24,84 @@ import java.util.Locale;
*/
public class CustomJCaptchaService extends AbstractManageableImageCaptchaService {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomJCaptchaService.class);
private static final Logger LOGGER = LoggerFactory.getLogger(CustomJCaptchaService.class);
/*
* 验证码管理策略:
* 1, 生成验证码时, 会进行配额检查, 当达到配额时, 进行垃圾验证码清理
* 2, 一个验证码校验完成后, 不管成功失败, 都会直接失效, 删除?
* */
private static final Integer MIN_GUARANTED_STORAGE_DELAY_IN_SECONDS = 120; // 默认值, 执行垃圾清理时, 存活超过180s的验证码都会被清除
private static final Integer MAX_CAPTCHA_STORE_SIZE = 70000; // 最大容量, 默认值是10w
private static final Integer CAPTCHA_STORE_LOAD_BEFORE_GARBAGE_COLLECTION = 52500; // 配额, 超过此配额时执行一次垃圾清除, 默认值是:75000
public CustomJCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine) {
this(captchaStore, captchaEngine, MIN_GUARANTED_STORAGE_DELAY_IN_SECONDS, MAX_CAPTCHA_STORE_SIZE, CAPTCHA_STORE_LOAD_BEFORE_GARBAGE_COLLECTION);
}
/*
* 验证码管理策略:
* 1, 生成验证码时, 会进行配额检查, 当达到配额时, 进行垃圾验证码清理
* 2, 一个验证码校验完成后, 不管成功失败, 都会直接失效, 删除?
* */
private static final Integer MIN_GUARANTED_STORAGE_DELAY_IN_SECONDS = 120; // 默认值, 执行垃圾清理时, 存活超过180s的验证码都会被清除
private static final Integer MAX_CAPTCHA_STORE_SIZE = 70000; // 最大容量, 默认值是10w
private static final Integer CAPTCHA_STORE_LOAD_BEFORE_GARBAGE_COLLECTION = 52500; // 配额, 超过此配额时执行一次垃圾清除, 默认值是:75000
public CustomJCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine) {
this(captchaStore, captchaEngine, MIN_GUARANTED_STORAGE_DELAY_IN_SECONDS, MAX_CAPTCHA_STORE_SIZE, CAPTCHA_STORE_LOAD_BEFORE_GARBAGE_COLLECTION);
}
protected CustomJCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) {
super(captchaStore, captchaEngine, minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize, captchaStoreLoadBeforeGarbageCollection);
}
@Override
public long getCustomStoreSize() {
return this.store.getSize();
}
/**
* 重写校验, 需要将原来的 key 失效
*
* @param id
* @param response
* @return
* @throws CaptchaServiceException
*/
@Override
public Boolean validateResponseForID(String id, Object response) throws CaptchaServiceException {
if (StringUtils.isBlank(id)) {
return false;
}
boolean valid;
try {
Captcha captcha = this.store.getCaptcha(id);
if (null == captcha || captcha.hasGetChalengeBeenCalled()) {
return false;
}
valid = captcha.validateResponse(response);
} catch (Exception ex) {
LOGGER.warn("can not get captcha from redis");
valid = false;
}
protected CustomJCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) {
super(captchaStore, captchaEngine, minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize, captchaStoreLoadBeforeGarbageCollection);
}
this.getTimes().remove(id);
if(valid) {
addNumberOfCorrectResponse(1);
} else {
addNumberOfUncorrectResponse(1);
}
@Override
public long getCustomStoreSize() {
return this.store.getSize();
}
return valid;
/**
* 重写校验, 需要将原来的 key 失效
*
* @param id
* @param response
* @return
* @throws CaptchaServiceException
*/
@Override
public Boolean validateResponseForID(String id, Object response) throws CaptchaServiceException {
if (StringUtils.isBlank(id)) {
return false;
}
/**
* 请求新的图形验证码
*
* @param ID
* @param locale
* @return
* @throws CaptchaServiceException
*/
public Object getChallengeForID(String ID, Locale locale) throws CaptchaServiceException {
Captcha captcha = this.generateAndStoreCaptcha(locale, ID);
Object challenge = this.getChallengeClone(captcha);
captcha.disposeChallenge();
return challenge;
boolean valid;
try {
Captcha captcha = this.store.getCaptcha(id);
if (null == captcha || captcha.hasGetChalengeBeenCalled()) {
return false;
}
valid = captcha.validateResponse(response);
} catch (Exception ex) {
LOGGER.warn("can not get captcha from redis");
valid = false;
}
@Override
public void garbageCollectCaptchaStore() {
super.garbageCollectCaptchaStore();
this.getTimes().remove(id);
if (valid) {
addNumberOfCorrectResponse(1);
} else {
addNumberOfUncorrectResponse(1);
}
return valid;
}
/**
* 请求新的图形验证码
*
* @param ID
* @param locale
* @return
* @throws CaptchaServiceException
*/
public Object getChallengeForID(String ID, Locale locale) throws CaptchaServiceException {
Captcha captcha = this.generateAndStoreCaptcha(locale, ID);
Object challenge = this.getChallengeClone(captcha);
captcha.disposeChallenge();
return challenge;
}
@Override
public void garbageCollectCaptchaStore() {
super.garbageCollectCaptchaStore();
}
}
......@@ -26,87 +26,87 @@ import java.util.concurrent.TimeUnit;
*/
public class RedisCaptchaStore implements CaptchaStore {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisCaptchaStore.class);
private static final long DEFAULT_EXPIRED_IN = 120L;
private static final TimeUnit DEFAULT_EXPIRED_TIMEUNIT = TimeUnit.SECONDS;
protected RedisTemplate<String, String> stringRedisTemplate;
public RedisCaptchaStore(RedisTemplate<String, String> stringRedisTemplate) {
super();
this.stringRedisTemplate = stringRedisTemplate;
}
@Override
public boolean hasCaptcha(String captchaId) {
return stringRedisTemplate.hasKey(buildCaptcharKey(captchaId));
}
@Override
public void storeCaptcha(String s, Captcha captcha) throws CaptchaServiceException {
stringRedisTemplate.opsForValue().set(buildCaptcharKey(s), ((SimpleCaptcha) captcha).getResponse(), DEFAULT_EXPIRED_IN, DEFAULT_EXPIRED_TIMEUNIT);
}
@Override
public void storeCaptcha(String s, Captcha captcha, Locale locale) throws CaptchaServiceException {
stringRedisTemplate.opsForValue().set(buildCaptcharKey(s), ((SimpleCaptcha) captcha).getResponse(), DEFAULT_EXPIRED_IN, DEFAULT_EXPIRED_TIMEUNIT);
}
@Override
public boolean removeCaptcha(String captchaId) {
stringRedisTemplate.delete(buildCaptcharKey(captchaId));
return true;
}
@Override
public Captcha getCaptcha(String captchaId) throws CaptchaServiceException {
return getFromRedisThenDel(captchaId);
}
@Override
public Locale getLocale(String captchaId) throws CaptchaServiceException {
return Locale.CHINA;
}
@Override
public int getSize() {
return getKeys().size();
}
@Override
public Collection getKeys() {
return stringRedisTemplate.keys(Constants.REDIS_CAPTCHA_KEY_PATTERN);
}
@Override
public void empty() {
}
@Override
public void initAndStart() {
}
@Override
public void cleanAndShutdown() {
}
private Captcha getFromRedis(String captchaId) {
Object value = stringRedisTemplate.opsForValue().get(buildCaptcharKey(captchaId));
return value != null ? new SimpleCaptcha(captchaId, String.valueOf(value)) : null;
}
private Captcha getFromRedisThenDel(String captchaId) {
String captcharKey = buildCaptcharKey(captchaId);
Object value = stringRedisTemplate.opsForValue().get(captcharKey);
stringRedisTemplate.delete(captcharKey);
return value != null ? new SimpleCaptcha(captchaId, String.valueOf(value)) : null;
}
protected String buildCaptcharKey(String captchaId) {
return Constants.REDIS_CAPTCHA_KEY + captchaId;
}
private static final Logger LOGGER = LoggerFactory.getLogger(RedisCaptchaStore.class);
private static final long DEFAULT_EXPIRED_IN = 120L;
private static final TimeUnit DEFAULT_EXPIRED_TIMEUNIT = TimeUnit.SECONDS;
protected RedisTemplate<String, String> stringRedisTemplate;
public RedisCaptchaStore(RedisTemplate<String, String> stringRedisTemplate) {
super();
this.stringRedisTemplate = stringRedisTemplate;
}
@Override
public boolean hasCaptcha(String captchaId) {
return stringRedisTemplate.hasKey(buildCaptcharKey(captchaId));
}
@Override
public void storeCaptcha(String s, Captcha captcha) throws CaptchaServiceException {
stringRedisTemplate.opsForValue().set(buildCaptcharKey(s), ((SimpleCaptcha) captcha).getResponse(), DEFAULT_EXPIRED_IN, DEFAULT_EXPIRED_TIMEUNIT);
}
@Override
public void storeCaptcha(String s, Captcha captcha, Locale locale) throws CaptchaServiceException {
stringRedisTemplate.opsForValue().set(buildCaptcharKey(s), ((SimpleCaptcha) captcha).getResponse(), DEFAULT_EXPIRED_IN, DEFAULT_EXPIRED_TIMEUNIT);
}
@Override
public boolean removeCaptcha(String captchaId) {
stringRedisTemplate.delete(buildCaptcharKey(captchaId));
return true;
}
@Override
public Captcha getCaptcha(String captchaId) throws CaptchaServiceException {
return getFromRedisThenDel(captchaId);
}
@Override
public Locale getLocale(String captchaId) throws CaptchaServiceException {
return Locale.CHINA;
}
@Override
public int getSize() {
return getKeys().size();
}
@Override
public Collection getKeys() {
return stringRedisTemplate.keys(Constants.REDIS_CAPTCHA_KEY_PATTERN);
}
@Override
public void empty() {
}
@Override
public void initAndStart() {
}
@Override
public void cleanAndShutdown() {
}
private Captcha getFromRedis(String captchaId) {
Object value = stringRedisTemplate.opsForValue().get(buildCaptcharKey(captchaId));
return value != null ? new SimpleCaptcha(captchaId, String.valueOf(value)) : null;
}
private Captcha getFromRedisThenDel(String captchaId) {
String captcharKey = buildCaptcharKey(captchaId);
Object value = stringRedisTemplate.opsForValue().get(captcharKey);
stringRedisTemplate.delete(captcharKey);
return value != null ? new SimpleCaptcha(captchaId, String.valueOf(value)) : null;
}
protected String buildCaptcharKey(String captchaId) {
return Constants.REDIS_CAPTCHA_KEY + captchaId;
}
}
......@@ -33,66 +33,65 @@ import java.util.Properties;
@EnableTransactionManagement
public class JpaConfig {
@SafeValue("xyqb.data.mysql.jdbc-url")
private String xyqbJdbcUrl;
@SafeValue("xyqb.data.mysql.password")
private String password;
@SafeValue("xyqb.data.mysql.user")
private String user;
@Value("${xyqb.data.mysql.max-pool-size}")
private Integer maxPoolSize;
@Bean
@DependsOn(value = "dataSource")
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(ApplicationContextHolder.getBean("dataSource"));
entityManager.setPackagesToScan("cn.quantgroup.xyqb");
entityManager.setPersistenceUnitName("dataSource");
Properties properties = new Properties();
properties.put("hibernate.jdbc.batch_size", 30);
properties.put("hibernate.order_inserts", true);
properties.put("hibernate.order_updates", true);
entityManager.setJpaProperties(properties);
entityManager.setJpaVendorAdapter(jpaVendorAdapter());
entityManager.afterPropertiesSet();
return entityManager.getObject();
}
@Bean
public DataSource dataSource() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(xyqbJdbcUrl);
config.setPassword(password);
config.setUsername(user);
config.setMaximumPoolSize(maxPoolSize);
config.setMinimumIdle(20);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
return new HikariDataSource(config);
}
private JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(false);
hibernateJpaVendorAdapter.setGenerateDdl(false);
hibernateJpaVendorAdapter.setDatabase(Database.MYSQL);
return hibernateJpaVendorAdapter;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
@SafeValue("xyqb.data.mysql.jdbc-url")
private String xyqbJdbcUrl;
@SafeValue("xyqb.data.mysql.password")
private String password;
@SafeValue("xyqb.data.mysql.user")
private String user;
@Value("${xyqb.data.mysql.max-pool-size}")
private Integer maxPoolSize;
@Bean
@DependsOn(value = "dataSource")
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(ApplicationContextHolder.getBean("dataSource"));
entityManager.setPackagesToScan("cn.quantgroup.xyqb");
entityManager.setPersistenceUnitName("dataSource");
Properties properties = new Properties();
properties.put("hibernate.jdbc.batch_size", 30);
properties.put("hibernate.order_inserts", true);
properties.put("hibernate.order_updates", true);
entityManager.setJpaProperties(properties);
entityManager.setJpaVendorAdapter(jpaVendorAdapter());
entityManager.afterPropertiesSet();
return entityManager.getObject();
}
@Bean
public DataSource dataSource() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(xyqbJdbcUrl);
config.setPassword(password);
config.setUsername(user);
config.setMaximumPoolSize(maxPoolSize);
config.setMinimumIdle(20);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
return new HikariDataSource(config);
}
private JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(false);
hibernateJpaVendorAdapter.setGenerateDdl(false);
hibernateJpaVendorAdapter.setDatabase(Database.MYSQL);
return hibernateJpaVendorAdapter;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
package cn.quantgroup.xyqb.config.http;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import javax.net.ssl.SSLContext;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.config.Registry;
......@@ -37,9 +33,11 @@ import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.filter.CharacterEncodingFilter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
/**
* Created by Miraculous on 15/7/12.
......@@ -47,94 +45,94 @@ import com.fasterxml.jackson.databind.SerializationFeature;
@Configuration
public class HttpConfig {
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
registrationBean.setFilter(characterEncodingFilter);
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
registrationBean.setOrder(Integer.MIN_VALUE);
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
/**
* 该方法主要对对象json序列化产生影响,其功能如下:
* 1. 禁用缩进输出
* 2. 日期格式排版
* 3. null被过滤掉
* 4. 将enum转为其ordinal
*
* @return Jackson2ObjectMapperBuilder
*/
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(false)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd"))
.defaultViewInclusion(false)
.serializationInclusion(JsonInclude.Include.NON_NULL)
.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_INDEX,
DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS);
return builder;
}
// hack spring mvc.
@Bean
public IntegerToEnumConverterFactory getIntegerToEnumConverterFactory(
ConverterRegistry defaultConversionService, ConverterRegistry mvcConversionService, ConverterRegistry integrationConversionService) {
IntegerToEnumConverterFactory factory = new IntegerToEnumConverterFactory();
defaultConversionService.removeConvertible(String.class, Enum.class);
mvcConversionService.removeConvertible(String.class, Enum.class);
integrationConversionService.removeConvertible(String.class, Enum.class);
defaultConversionService.addConverterFactory(factory);
mvcConversionService.addConverterFactory(factory);
integrationConversionService.addConverterFactory(factory);
return factory;
}
@Bean(name = "httpClient")
public CloseableHttpClient httpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// socket factory
ConnectionSocketFactory plainSocketFactory = new PlainConnectionSocketFactory();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, (x509Certificates, authType) -> true).build();
LayeredConnectionSocketFactory sslSocketFactory =
new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory)
.register("https", sslSocketFactory).build();
// cookie specification
Registry<CookieSpecProvider> cookieSpecProviderRegistry = RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory())
.register("easy", httpContext -> new BrowserCompatSpec() {
public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
}
}).build();
// connection manager
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(10000);
connectionManager.setDefaultMaxPerRoute(1000);
// retry handler
HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler(3, false);
// keep alive strategy
ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy();
// httpclient
return HttpClients.custom()
.setConnectionManager(connectionManager)
.setRetryHandler(retryHandler)
.setKeepAliveStrategy(keepAliveStrategy)
.setDefaultCookieSpecRegistry(cookieSpecProviderRegistry).build();
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
registrationBean.setFilter(characterEncodingFilter);
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
registrationBean.setOrder(Integer.MIN_VALUE);
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
/**
* 该方法主要对对象json序列化产生影响,其功能如下:
* 1. 禁用缩进输出
* 2. 日期格式排版
* 3. null被过滤掉
* 4. 将enum转为其ordinal
*
* @return Jackson2ObjectMapperBuilder
*/
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(false)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd"))
.defaultViewInclusion(false)
.serializationInclusion(JsonInclude.Include.NON_NULL)
.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_INDEX,
DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS);
return builder;
}
// hack spring mvc.
@Bean
public IntegerToEnumConverterFactory getIntegerToEnumConverterFactory(
ConverterRegistry defaultConversionService, ConverterRegistry mvcConversionService, ConverterRegistry integrationConversionService) {
IntegerToEnumConverterFactory factory = new IntegerToEnumConverterFactory();
defaultConversionService.removeConvertible(String.class, Enum.class);
mvcConversionService.removeConvertible(String.class, Enum.class);
integrationConversionService.removeConvertible(String.class, Enum.class);
defaultConversionService.addConverterFactory(factory);
mvcConversionService.addConverterFactory(factory);
integrationConversionService.addConverterFactory(factory);
return factory;
}
@Bean(name = "httpClient")
public CloseableHttpClient httpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// socket factory
ConnectionSocketFactory plainSocketFactory = new PlainConnectionSocketFactory();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, (x509Certificates, authType) -> true).build();
LayeredConnectionSocketFactory sslSocketFactory =
new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory)
.register("https", sslSocketFactory).build();
// cookie specification
Registry<CookieSpecProvider> cookieSpecProviderRegistry = RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory())
.register("easy", httpContext -> new BrowserCompatSpec() {
public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
}
}).build();
// connection manager
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(10000);
connectionManager.setDefaultMaxPerRoute(1000);
// retry handler
HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler(3, false);
// keep alive strategy
ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy();
// httpclient
return HttpClients.custom()
.setConnectionManager(connectionManager)
.setRetryHandler(retryHandler)
.setKeepAliveStrategy(keepAliveStrategy)
.setDefaultCookieSpecRegistry(cookieSpecProviderRegistry).build();
}
}
......@@ -7,33 +7,33 @@ import org.springframework.core.convert.converter.ConverterFactory;
* Created by Miraculous on 15/7/12.
*/
final class IntegerToEnumConverterFactory implements ConverterFactory<String, Enum> {
IntegerToEnumConverterFactory() {
}
IntegerToEnumConverterFactory() {
}
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
Class<?> enumType = targetType;
while (enumType != null && !enumType.isEnum()) {
enumType = enumType.getSuperclass();
}
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
Class<?> enumType = targetType;
while (enumType != null && !enumType.isEnum()) {
enumType = enumType.getSuperclass();
}
if (enumType == null) {
throw new IllegalArgumentException("The target type " + targetType.getName() + " does not refer to an enum");
} else {
return new IntegerToEnumConverterFactory.IntegerToEnum(enumType);
}
if (enumType == null) {
throw new IllegalArgumentException("The target type " + targetType.getName() + " does not refer to an enum");
} else {
return new IntegerToEnumConverterFactory.IntegerToEnum(enumType);
}
}
private class IntegerToEnum<T extends Enum> implements Converter<String, T> {
private final Class<T> enumType;
private class IntegerToEnum<T extends Enum> implements Converter<String, T> {
private final Class<T> enumType;
public IntegerToEnum(Class<T> enumType) {
this.enumType = enumType;
}
public IntegerToEnum(Class<T> enumType) {
this.enumType = enumType;
}
public T convert(String source) {
T[] ts = enumType.getEnumConstants();
int ordinal = Integer.parseInt(source);
return ordinal < ts.length && ordinal >= 0 ? ts[ordinal] : null;
}
public T convert(String source) {
T[] ts = enumType.getEnumConstants();
int ordinal = Integer.parseInt(source);
return ordinal < ts.length && ordinal >= 0 ? ts[ordinal] : null;
}
}
}
\ No newline at end of file
......@@ -11,14 +11,15 @@ import java.sql.Timestamp;
* Created by Miraculous on 2016/12/29.
*/
public class Timestamp2LongConverter implements ObjectSerializer {
;
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
Timestamp time = (Timestamp)object;
if (time == null) {
serializer.write(String.valueOf(0L));
} else {
serializer.write(String.valueOf(time.getTime()));
}
;
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
Timestamp time = (Timestamp) object;
if (time == null) {
serializer.write(String.valueOf(0L));
} else {
serializer.write(String.valueOf(time.getTime()));
}
}
}
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;
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.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
......@@ -11,8 +13,12 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ChannelIdInterceptor()).addPathPatterns("/**");
}
@Value("${configserver.disable}")
private Integer isDebug;
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new IPWhiteListInterceptor(isDebug)).addPathPatterns("/innerapi/**");
registry.addInterceptor(new ChannelIdInterceptor()).addPathPatterns("/**");
}
}
package cn.quantgroup.xyqb.constant;
public class UserConstant {
public static final String USER_ERROR_OR_PASSWORD_ERROR = "帐号或密码错误";
}
......@@ -22,42 +22,41 @@ import javax.servlet.http.HttpServletRequest;
@RestController
public class ExceptionHandlingController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlingController.class);
private static final JsonResult EXCEPTION_RESULT = new JsonResult("internal error", 500L, "");
@ExceptionHandler(NullUserException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public JsonResult nullUserException(NullUserException nue) {
return new JsonResult(nue.getMessage(), 401L, null);
}
/**
* 验证码登陆异常
*
* @param vce
* @return
*/
@ExceptionHandler(VerificationCodeErrorException.class)
public JsonResult verificationCodeErrorException(VerificationCodeErrorException vce) {
return JsonResult.buildErrorStateResult(vce.getMessage(), null, 1L);
}
@ExceptionHandler(UserNotExistException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public JsonResult userNotExistException(UserNotExistException unee) {
return new JsonResult(unee.getMessage(), 401L, null);
}
@ExceptionHandler(Exception.class)
public JsonResult exceptionOccurs(Exception e) {
HttpServletRequest request = getRequest();
String uri = request.getRequestURI();
String registerFrom = request.getParameter("registerFrom");
LOGGER.error("接口异常 URI:{}, registerFrom:{}", uri, registerFrom, e);
return EXCEPTION_RESULT;
}
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlingController.class);
private static final JsonResult EXCEPTION_RESULT = new JsonResult("internal error", 500L, "");
@ExceptionHandler(NullUserException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public JsonResult nullUserException(NullUserException nue) {
return new JsonResult(nue.getMessage(), 401L, null);
}
/**
* 验证码登陆异常
*
* @param vce
* @return
*/
@ExceptionHandler(VerificationCodeErrorException.class)
public JsonResult verificationCodeErrorException(VerificationCodeErrorException vce) {
return JsonResult.buildErrorStateResult(vce.getMessage(), null, 1L);
}
@ExceptionHandler(UserNotExistException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public JsonResult userNotExistException(UserNotExistException unee) {
return new JsonResult(unee.getMessage(), 401L, null);
}
@ExceptionHandler(Exception.class)
public JsonResult exceptionOccurs(Exception e) {
HttpServletRequest request = getRequest();
String uri = request.getRequestURI();
String registerFrom = request.getParameter("registerFrom");
LOGGER.error("接口异常 URI:{}, registerFrom:{}", uri, registerFrom, e);
return EXCEPTION_RESULT;
}
}
......@@ -7,56 +7,57 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.*;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.getXSession;
/**
* Created by Miraculous on 15/7/5.
*/
public interface IBaseController {
default User getCurrentUser() {
SessionStruct session = getXSession();
if (session == null) {
return null;
}
return getXSession().getValues().getUser();
}
default SessionStruct getSessionStruct() {
return getXSession();
default User getCurrentUser() {
SessionStruct session = getXSession();
if (session == null) {
return null;
}
return getXSession().getValues().getUser();
}
default SessionStruct getSessionStruct() {
return getXSession();
}
default HttpServletRequest getRequest() {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
return attrs.getRequest();
}
default String getIp() {
HttpServletRequest request = getRequest();
String ip = request.getHeader("x-real-ip");
if (StringUtils.isEmpty(ip)) {
ip = request.getRemoteAddr();
}
default HttpServletRequest getRequest() {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
return attrs.getRequest();
}
//过滤反向代理的ip
String[] stemps = ip.split(",");
if (stemps.length >= 1) {
//得到第一个IP,即客户端真实IP
ip = stemps[0];
}
default String getIp() {
HttpServletRequest request = getRequest();
ip = ip.trim();
if (ip.length() > 23) {
ip = ip.substring(0, 23);
}
String ip = request.getHeader("x-real-ip");
if (StringUtils.isEmpty(ip)) {
ip = request.getRemoteAddr();
}
return ip;
//过滤反向代理的ip
String[] stemps = ip.split(",");
if (stemps.length >= 1) {
//得到第一个IP,即客户端真实IP
ip = stemps[0];
}
default String getProtocol() {
return StringUtils.startsWith(getRequest().getHeader("x-forwarded-proto"), "https") ? "https:" : "http:";
ip = ip.trim();
if (ip.length() > 23) {
ip = ip.substring(0, 23);
}
return ip;
}
default String getProtocol() {
return StringUtils.startsWith(getRequest().getHeader("x-forwarded-proto"), "https") ? "https:" : "http:";
}
}
package cn.quantgroup.xyqb.controller.external.captcha;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.aspect.captcha.CaptchaValidator;
import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.thirdparty.jcaptcha.AbstractManageableImageCaptchaService;
......@@ -37,45 +38,54 @@ import java.util.UUID;
@RequestMapping("/api")
public class ImageCaptchaController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(ImageCaptchaController.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ImageCaptchaController.class);
private static final String IMAGE_FORMAT_PNG = "png";
private static final String IMG_BASE64_PATTREN = "data:image/" + IMAGE_FORMAT_PNG + ";base64,%s";
private static final String IMAGE_FORMAT_PNG = "png";
private static final String IMG_BASE64_PATTREN = "data:image/" + IMAGE_FORMAT_PNG + ";base64,%s";
@Autowired
@Qualifier("customCaptchaService")
private AbstractManageableImageCaptchaService imageCaptchaService;
@Autowired
@Qualifier("customCaptchaService")
private AbstractManageableImageCaptchaService imageCaptchaService;
@ModelAttribute("clientIp")
public String initClientIp() {
return getIp();
@ModelAttribute("clientIp")
public String initClientIp() {
return getIp();
}
/**
* 获取验证码
* 默认匹配 GET /captcha, 提供4位数字和字母混合图片验证码
*
* @return
*/
@RequestMapping(value = "/captcha")
public JsonResult fetchCaptcha(HttpServletRequest request, @ModelAttribute("clientIp") String clientIp) {
String imageId = UUID.randomUUID().toString();
BufferedImage challenge = imageCaptchaService.getImageChallengeForID(Constants.IMAGE_CAPTCHA_KEY + imageId, request.getLocale());
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
boolean write = ImageIO.write(challenge, IMAGE_FORMAT_PNG, jpegOutputStream);
} catch (IOException e) {
e.printStackTrace();
return JsonResult.buildErrorStateResult("", "fail");
}
/**
* 获取验证码
* 默认匹配 GET /captcha, 提供4位数字和字母混合图片验证码
*
* @return
*/
@RequestMapping(value = "/captcha")
public JsonResult fetchCaptcha(HttpServletRequest request, @ModelAttribute("clientIp") String clientIp) {
String imageId = UUID.randomUUID().toString();
BufferedImage challenge = imageCaptchaService.getImageChallengeForID(Constants.IMAGE_CAPTCHA_KEY + imageId, request.getLocale());
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
boolean write = ImageIO.write(challenge, IMAGE_FORMAT_PNG, jpegOutputStream);
} catch (IOException e) {
e.printStackTrace();
return JsonResult.buildErrorStateResult("", "fail");
}
String imageBase64 = Base64.encodeBase64String(jpegOutputStream.toByteArray());
String imageBase64 = Base64.encodeBase64String(jpegOutputStream.toByteArray());
Map<String, String> data = new HashMap<>();
data.put("imageId", imageId);
data.put("image", String.format(IMG_BASE64_PATTREN, imageBase64));
return JsonResult.buildSuccessResult("", data);
Map<String, String> data = new HashMap<>();
data.put("imageId", imageId);
data.put("image", String.format(IMG_BASE64_PATTREN, imageBase64));
return JsonResult.buildSuccessResult("", data);
}
}
/**
* 图片验证码验证
*/
@CaptchaValidator
@RequestMapping("/verification_image_code")
public JsonResult verificationImageCode() {
return JsonResult.buildSuccessResult("", null);
}
}
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);
}
}
......@@ -5,15 +5,18 @@ import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.entity.enumerate.*;
import cn.quantgroup.xyqb.model.*;
import cn.quantgroup.xyqb.service.auth.IIdCardService;
import cn.quantgroup.xyqb.service.session.ISessionService;
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.ValidationUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
......@@ -48,7 +51,8 @@ public class InnerController {
private IWechatService wechatService;
@Autowired
private IUserSpouseService userSpouseService;
@Autowired
private ISessionService sessionService;
@RequestMapping("/user/search/phoneNo")
public JsonResult findByPhoneNo(String phoneNo) {
......@@ -103,6 +107,7 @@ public class InnerController {
user.setUpdatedAt(new Timestamp(updatedAt));
user.setEnable(true);
user.setRegisteredFrom(registeredFrom);
user.setUuid(uuid);
user.setPassword(password);
user = userService.saveUser(user);
UserRet userRet = null;
......@@ -237,6 +242,12 @@ public class InnerController {
return JsonResult.buildErrorStateResult(null, null);
}
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) {
c.setId(null);
c.setUserId(userId);
......@@ -244,8 +255,6 @@ public class InnerController {
c.setCreatedAt(now);
c.setUpdateAt(now);
}
List<Contact> result = contactService.save(contacts);
return JsonResult.buildSuccessResult(null, ContactRet.contacts2ContactRets(result));
}
@RequestMapping("/address/search/user_id")
......@@ -297,13 +306,13 @@ public class InnerController {
return JsonResult.buildErrorStateResult("用户ID不能为空", null);
}
UserExtInfo info = userExtInfoService.findByUserId(userId);
Timestamp now = new Timestamp(System.currentTimeMillis());
if (info == null) {
Timestamp now = new Timestamp(System.currentTimeMillis());
info = new UserExtInfo();
info.setUserId(userId);
info.setCreatedAt(now);
info.setUpdateAt(now);
}
info.setUpdateAt(now);
if (incomeEnum != null) {
info.setIncomeEnum(incomeEnum);
}
......@@ -334,7 +343,10 @@ public class InnerController {
@RequestMapping("/user_detail/search_list")
public JsonResult searchUserDetailList(String name, String phoneNo, String idNo) {
List<UserDetail> userDetails = userDetailService.searchUserDetailList(name, phoneNo, idNo);
if (StringUtils.isBlank(name) && StringUtils.isBlank(phoneNo) && StringUtils.isBlank(idNo)) {
return JsonResult.buildErrorStateResult("至少必须满足一个条件不为空", null);
}
List<UserDetailVO> userDetails = userDetailService.searchUserDetailList(name, phoneNo, idNo);
return JsonResult.buildSuccessResult("success", userDetails);
}
......@@ -347,7 +359,7 @@ public class InnerController {
if (userExtInfo == null) {
return JsonResult.buildErrorStateResult(null, null);
}
return JsonResult.buildSuccessResult("success", UserExtInfoRet.getUserExtInfoRet(userExtInfo));
return JsonResult.buildSuccessResult(null, UserExtInfoRet.getUserExtInfoRet(userExtInfo));
}
@RequestMapping("/user/query/openId")
......@@ -374,6 +386,25 @@ public class InnerController {
return JsonResult.buildSuccessResult(null, null == wechatUserInfo ? null : wechatUserInfo.getOpenId());
}
@RequestMapping("/user/disable")
public JsonResult disableUser(Long userId) {
if (null == userId || 0L == userId) {
return JsonResult.buildErrorStateResult("userId不能为空", null);
}
User user = userService.findById(userId);
if (null == user) {
return JsonResult.buildErrorStateResult("未查询到该用户,用户id:" + userId, null);
}
user.setEnable(false);
user.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
LOGGER.info("注销用户的信息,userId={}", userId);
user = userService.saveUser(user);
if (!user.getEnable()) {
sessionService.deleteByUserId(userId);
}
return JsonResult.buildSuccessResult("用户已禁用.", user.getEnable() == false);
}
@RequestMapping("/user/spouse/save")
public JsonResult saveSpouse(Long userId, MaritalStatus status, String spousePhone, String spouseName) {
if (userId == null || userId == 0) {
......@@ -414,4 +445,29 @@ public class InnerController {
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
......@@ -4,7 +4,6 @@ import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.model.JsonResult;
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.IUserService;
import org.apache.commons.lang.StringUtils;
......@@ -22,73 +21,73 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/api/sync")
public class SyncUserController {
@Autowired
private IUserService userService;
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IUserService userService;
@Autowired
private IUserDetailService userDetailService;
/*@Autowired
private IUserDetailRepository userDetailRepository;*/
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate;
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate;
@RequestMapping("/user")
public JsonResult fetchUser(String key, String phoneNo) {
if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) {
return JsonResult.buildErrorStateResult(null, null);
}
if (StringUtils.isEmpty(phoneNo)) {
return JsonResult.buildErrorStateResult(null, null);
}
User user = userService.findByPhoneInDb(phoneNo);
if (null == user) {
return JsonResult.buildErrorStateResult(null, null);
}
UserDetail detail = userDetailService.findByUserId(user.getId());
if (null == detail) {
// FIXME: 16/4/15 前期不对身份证强制要求.后期对修改
@RequestMapping("/user")
public JsonResult fetchUser(String key, String phoneNo) {
if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) {
return JsonResult.buildErrorStateResult(null, null);
}
if (StringUtils.isEmpty(phoneNo)) {
return JsonResult.buildErrorStateResult(null, null);
}
User user = userService.findByPhoneInDb(phoneNo);
if (null == user) {
return JsonResult.buildErrorStateResult(null, null);
}
UserDetail detail = userDetailService.findByUserId(user.getId());
if (null == detail) {
// FIXME: 16/4/15 前期不对身份证强制要求.后期对修改
// return JsonResult.buildErrorStateResult(null, null);
}
UserModel userModel = new UserModel(user, detail);
return JsonResult.buildSuccessResult(null, userModel);
}
UserModel userModel = new UserModel(user, detail);
return JsonResult.buildSuccessResult(null, userModel);
}
@RequestMapping("/save_detail")
public JsonResult saveUserDetail(String key, UserDetail userDetail) {
if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) {
return JsonResult.buildErrorStateResult(null, null);
}
String phoneNo = userDetail.getPhoneNo();
User user = userService.findByPhoneWithCache(phoneNo);
if (null == user) {
return JsonResult.buildErrorStateResult(null, null);
}
userDetail.setId(null);
userDetail.setUserId(user.getId());
userDetailService.saveUserDetail(userDetail);
return JsonResult.buildSuccessResult(null, null);
@RequestMapping("/save_detail")
public JsonResult saveUserDetail(String key, UserDetail userDetail) {
if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) {
return JsonResult.buildErrorStateResult(null, null);
}
String phoneNo = userDetail.getPhoneNo();
User user = userService.findByPhoneWithCache(phoneNo);
if (null == user) {
return JsonResult.buildErrorStateResult(null, null);
}
userDetail.setId(null);
userDetail.setUserId(user.getId());
userDetailService.saveUserDetail(userDetail);
return JsonResult.buildSuccessResult(null, null);
}
@RequestMapping("/user_uuid")
public JsonResult fetchUserByUuid(String key, String uuid) {
if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) {
return JsonResult.buildErrorStateResult(null, null);
}
if (StringUtils.isEmpty(uuid)) {
return JsonResult.buildErrorStateResult(null, null);
}
User user = userService.findByUuidWithCache(uuid);
if (null == user) {
return JsonResult.buildErrorStateResult(null, null);
}
UserDetail detail = userDetailService.findByUserId(user.getId());
if (null == detail) {
// FIXME: 16/4/15 前期不对身份证强制要求.后期对修改
@RequestMapping("/user_uuid")
public JsonResult fetchUserByUuid(String key, String uuid) {
if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) {
return JsonResult.buildErrorStateResult(null, null);
}
if (StringUtils.isEmpty(uuid)) {
return JsonResult.buildErrorStateResult(null, null);
}
User user = userService.findByUuidWithCache(uuid);
if (null == user) {
return JsonResult.buildErrorStateResult(null, null);
}
UserDetail detail = userDetailService.findByUserId(user.getId());
if (null == detail) {
// FIXME: 16/4/15 前期不对身份证强制要求.后期对修改
// return JsonResult.buildErrorStateResult(null, null);
}
UserModel userModel = new UserModel(user, detail);
return JsonResult.buildSuccessResult(null, userModel);
}
UserModel userModel = new UserModel(user, detail);
return JsonResult.buildSuccessResult(null, userModel);
}
}
......@@ -18,45 +18,45 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/api")
public class UserApiController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserApiController.class);
private static final Logger LOGGER = LoggerFactory.getLogger(UserApiController.class);
@Autowired
private IUserApiService userApiService;
@Autowired
private IUserService userService;
@Autowired
private IUserApiService userApiService;
@Autowired
private IUserService userService;
@RequestMapping("/user/check")
public JsonResult userImportCheck(String phoneNo, String registerFrom) {
if ("244".equals(registerFrom)) {
LOGGER.info("[user_import_check]用户导入检查拒绝。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildErrorStateResult("用户导入检查拒绝", false);
}
if (StringUtils.isEmpty(phoneNo) || StringUtils.isEmpty(registerFrom)) {
LOGGER.error("[user_import_check]检查传入的参数,参数不全。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildErrorStateResult("检查传入的参数,参数不全。", null);
}
boolean checkPassed = userApiService.userImportCheck(phoneNo);
if (checkPassed) {
LOGGER.info("[user_import_check]用户可以导入。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildSuccessResult("用户可以导入", checkPassed);
}
LOGGER.info("[user_import_check]用户导入检查拒绝。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildErrorStateResult("用户导入检查拒绝", checkPassed);
@RequestMapping("/user/check")
public JsonResult userImportCheck(String phoneNo, String registerFrom) {
if ("244".equals(registerFrom)) {
LOGGER.info("[user_import_check]用户导入检查拒绝。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildErrorStateResult("用户导入检查拒绝", false);
}
if (StringUtils.isEmpty(phoneNo) || StringUtils.isEmpty(registerFrom)) {
LOGGER.error("[user_import_check]检查传入的参数,参数不全。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildErrorStateResult("检查传入的参数,参数不全。", null);
}
boolean checkPassed = userApiService.userImportCheck(phoneNo);
if (checkPassed) {
LOGGER.info("[user_import_check]用户可以导入。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildSuccessResult("用户可以导入", checkPassed);
}
LOGGER.info("[user_import_check]用户导入检查拒绝。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildErrorStateResult("用户导入检查拒绝", checkPassed);
}
@RequestMapping("/user/is_passwd_set")
public JsonResult isPasswordSet(String key, String phoneNo) {
if (!"abc1234".equals(key) || StringUtils.isEmpty(phoneNo)) {
return JsonResult.buildErrorStateResult(null, null);
}
User user = userService.findByPhoneWithCache(phoneNo);
if (null == user) {
return JsonResult.buildErrorStateResult(null, null);
}
if (StringUtils.length(user.getPassword()) == 32) {
return JsonResult.buildSuccessResult(null, null);
}
return JsonResult.buildErrorStateResult(null, null, 2L);
@RequestMapping("/user/is_passwd_set")
public JsonResult isPasswordSet(String key, String phoneNo) {
if (!"abc1234".equals(key) || StringUtils.isEmpty(phoneNo)) {
return JsonResult.buildErrorStateResult(null, null);
}
User user = userService.findByPhoneWithCache(phoneNo);
if (null == user) {
return JsonResult.buildErrorStateResult(null, null);
}
if (StringUtils.length(user.getPassword()) == 32) {
return JsonResult.buildSuccessResult(null, null);
}
return JsonResult.buildErrorStateResult(null, null, 2L);
}
}
......@@ -13,11 +13,11 @@ import java.io.PrintWriter;
@RequestMapping("/")
public class WechatVerifyController {
@RequestMapping("/MP_verify_AWiagUn4kZiwmTt0.txt")
public void verifyWechat(HttpServletResponse response) throws Exception {
response.setContentType("plain/text");
PrintWriter writer = response.getWriter();
writer.print("AWiagUn4kZiwmTt0");
writer.close();
}
@RequestMapping("/MP_verify_AWiagUn4kZiwmTt0.txt")
public void verifyWechat(HttpServletResponse response) throws Exception {
response.setContentType("plain/text");
PrintWriter writer = response.getWriter();
writer.print("AWiagUn4kZiwmTt0");
writer.close();
}
}
......@@ -15,18 +15,18 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/auth")
public class AuthInfoController implements IBaseController {
@RequestMapping("/info/login")
public JsonResult loginInfo() {
SessionStruct sessionStruct = getSessionStruct();
LoginInfo loginInfo = new LoginInfo();
loginInfo.setUser(UserRet.getUserRet(sessionStruct.getValues().getUser()));
loginInfo.setToken(sessionStruct.getSid());
LoginInfo.LoginContext context = new LoginInfo.LoginContext();
context.setChannelId(sessionStruct.getValues().getLoginProperties().getChannelId());
context.setCreatedFrom(sessionStruct.getValues().getLoginProperties().getCreatedFrom());
context.setAppChannel(sessionStruct.getValues().getLoginProperties().getAppChannel());
loginInfo.setLoginContext(context);
return JsonResult.buildSuccessResult("", loginInfo);
}
@RequestMapping("/info/login")
public JsonResult loginInfo() {
SessionStruct sessionStruct = getSessionStruct();
LoginInfo loginInfo = new LoginInfo();
loginInfo.setUser(UserRet.getUserRet(sessionStruct.getValues().getUser()));
loginInfo.setToken(sessionStruct.getSid());
LoginInfo.LoginContext context = new LoginInfo.LoginContext();
context.setChannelId(sessionStruct.getValues().getLoginProperties().getChannelId());
context.setCreatedFrom(sessionStruct.getValues().getLoginProperties().getCreatedFrom());
context.setAppChannel(sessionStruct.getValues().getLoginProperties().getAppChannel());
loginInfo.setLoginContext(context);
return JsonResult.buildSuccessResult("", loginInfo);
}
}
......@@ -10,6 +10,8 @@ import cn.quantgroup.xyqb.service.merchant.IMerchantService;
import cn.quantgroup.xyqb.service.page.IPageService;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
......@@ -22,50 +24,52 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/platform/api")
public class PlatformAPIController implements IBaseController {
@Autowired
private IPageService pageService;
@Autowired
private IMerchantService merchantService;
@RequestMapping("/page/return_url")
public JsonResult returnUrl(String key) {
Merchant merchant = merchantService.findMerchantByName(key);
if (null == merchant) {
return JsonResult.buildErrorStateResult("", null);
}
MerchantConfig config= merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl");
if (null == config) {
return JsonResult.buildSuccessResult("", null);
}
return JsonResult.buildSuccessResult("", config.getConfigValue());
}
private static final Logger LOGGER = LoggerFactory.getLogger(PlatformAPIController.class);
@Autowired
private IPageService pageService;
@Autowired
private IMerchantService merchantService;
@RequestMapping("/page/next")
public JsonResult nextPage(String key, String target, @RequestParam(required = false, defaultValue = "") String currentPage) {
User user = getCurrentUser();
if (null == user) {
return JsonResult.buildErrorStateResult("未找到用户", null);
}
Tuple<String, Boolean> nextPageTuple = pageService.nextPage(user, target, currentPage);
Boolean isFinal = nextPageTuple.getValue();
String nextPage = nextPageTuple.getKey();
if (isFinal) {
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
return JsonResult.buildSuccessResult("", null);
}
MerchantConfig merchantConfig = merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl");
if (merchantConfig == null) {
return JsonResult.buildSuccessResult("", null);
}
return JsonResult.buildSuccessResult("", ImmutableMap.of("type", "external", "transition", merchantConfig.getConfigValue()));
}
if (StringUtils.isEmpty(nextPage)) {
return JsonResult.buildErrorStateResult("", null);
}
return JsonResult.buildSuccessResult("", ImmutableMap.of("type", "user", "transition", nextPage));
@RequestMapping("/page/return_url")
public JsonResult returnUrl(String key) {
Merchant merchant = merchantService.findMerchantByName(key);
if (null == merchant) {
return JsonResult.buildErrorStateResult("", null);
}
MerchantConfig config = merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl");
if (null == config) {
return JsonResult.buildSuccessResult("", null);
}
return JsonResult.buildSuccessResult("", config.getConfigValue());
}
@RequestMapping("/page/next")
public JsonResult nextPage(String key, String target, @RequestParam(required = false, defaultValue = "") String currentPage) {
User user = getCurrentUser();
if (null == user) {
return JsonResult.buildErrorStateResult("未找到用户", null);
}
Tuple<String, Boolean> nextPageTuple = pageService.nextPage(user, target, currentPage);
Boolean isFinal = nextPageTuple.getValue();
String nextPage = nextPageTuple.getKey();
if (isFinal) {
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
return JsonResult.buildSuccessResult("", null);
}
MerchantConfig merchantConfig = merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl");
if (merchantConfig == null) {
return JsonResult.buildSuccessResult("", null);
}
return JsonResult.buildSuccessResult("", ImmutableMap.of("type", "external", "transition", merchantConfig.getConfigValue()));
}
if (StringUtils.isEmpty(nextPage)) {
return JsonResult.buildErrorStateResult("", null);
}
return JsonResult.buildSuccessResult("", ImmutableMap.of("type", "user", "transition", nextPage));
}
}
......@@ -26,95 +26,91 @@ import java.util.concurrent.TimeUnit;
@RequestMapping("/api/sms")
public class SmsController {
private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class);
@Autowired
private ISmsService smsService;
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate;
@Value("${sms.is.debug}")
private boolean smsIsDebug;
private static final Random random = new Random();
private static final long EXPIRE_MINUTES = 10;
/**
* 短信验证码: for H5
* 使用 @FPLock 注解并加入自定义限制参数, 做针对手机号的发送次数限制
*/
@CaptchaValidator
@RequestMapping("/send_sms_verification_code")
public JsonResult verifyPhoneNoH5(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("注册-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2(phoneNo);
}
@CaptchaValidator
@RequestMapping("/send_reset_code")
public JsonResult resetPasswordH5(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("重置密码-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2(phoneNo);
}
/**
* 快速登陆发送验证码
*
* @param phoneNo
* @param registerFrom
* @return
*/
@CaptchaValidator
@RequestMapping("/send_login_code")
public JsonResult sendLoginCode(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("快速登陆-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2(phoneNo);
private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class);
private static final Random random = new Random();
private static final long EXPIRE_MINUTES = 10;
@Autowired
private ISmsService smsService;
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate;
@Value("${sms.is.debug}")
private boolean smsIsDebug;
/**
* 短信验证码: for H5
* 使用 @FPLock 注解并加入自定义限制参数, 做针对手机号的发送次数限制
*/
@CaptchaValidator
@RequestMapping("/send_sms_verification_code")
public JsonResult verifyPhoneNoH5(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("注册-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2(phoneNo);
}
@CaptchaValidator
@RequestMapping("/send_reset_code")
public JsonResult resetPasswordH5(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("重置密码-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2(phoneNo);
}
/**
* 快速登陆发送验证码
*
* @param phoneNo
* @param registerFrom
* @return
*/
@CaptchaValidator
@RequestMapping("/send_login_code")
public JsonResult sendLoginCode(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("快速登陆-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2(phoneNo);
}
/**
* 快速注册发送验证码
*
* @param phoneNo
* @param registerFrom
* @return
*/
@CaptchaValidator
@RequestMapping("/send_regist_code")
public JsonResult sendRegistCode(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("快速注册-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2(phoneNo);
}
private JsonResult sendVerificationCode2(String phoneNo) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return JsonResult.buildErrorStateResult("手机号格式有误", null);
}
/**
* 快速注册发送验证码
*
* @param phoneNo
* @param registerFrom
* @return
*/
@CaptchaValidator
@RequestMapping("/send_regist_code")
public JsonResult sendRegistCode(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("快速注册-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2(phoneNo);
String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
long expire = redisTemplate.getExpire(key, TimeUnit.MINUTES);
if (expire >= EXPIRE_MINUTES - 1) {
return JsonResult.buildSuccessResult("发送成功", null);
}
private JsonResult sendVerificationCode2(String phoneNo) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return JsonResult.buildErrorStateResult("手机号格式有误", null);
}
String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
long expire = redisTemplate.getExpire(key, TimeUnit.MINUTES);
if (expire >= EXPIRE_MINUTES - 1) {
return JsonResult.buildSuccessResult("发送成功", null);
}
String randomCode = smsIsDebug ? "000000" : String.valueOf(random.nextInt(899999) + 100000);
String uniqueId = phoneNo + UUID.randomUUID().toString().replaceAll("-", "");
List<String> newList = new ArrayList<>();
newList.add(randomCode);
String randomCode = smsIsDebug ? "000000" : String.valueOf(random.nextInt(899999) + 100000);
String uniqueId = phoneNo + UUID.randomUUID().toString().replaceAll("-", "");
List<String> newList = new ArrayList<>();
newList.add(randomCode);
/*ConfirmableMsg confirmableMsg = new ConfirmableMsg(
uniqueId, newList, "1", "1", phoneNo
);*/
MsgParams message = new MsgParams(Collections.singletonList(2), phoneNo, "1", "1", Collections.singletonList(randomCode), uniqueId);
try {
//smsService.getSmsSender().sendConfirmableMessage(confirmableMsg);
smsService.getSmsSender().sendMsg(message);
redisTemplate.opsForValue().set(key, uniqueId + ":" + randomCode, EXPIRE_MINUTES, TimeUnit.MINUTES);
return JsonResult.buildSuccessResult("发送成功", uniqueId);
} catch (Exception e) {
LOGGER.error("发送短信验证码失败");
return JsonResult.buildErrorStateResult("发送失败", null);
}
MsgParams message = new MsgParams(Collections.singletonList(2), phoneNo, "1", "1", Collections.singletonList(randomCode), uniqueId);
try {
//smsService.getSmsSender().sendConfirmableMessage(confirmableMsg);
smsService.getSmsSender().sendMsg(message);
redisTemplate.opsForValue().set(key, uniqueId + ":" + randomCode, EXPIRE_MINUTES, TimeUnit.MINUTES);
return JsonResult.buildSuccessResult("发送成功", uniqueId);
} catch (Exception e) {
LOGGER.error("发送短信验证码失败");
return JsonResult.buildErrorStateResult("发送失败", null);
}
}
}
......@@ -26,49 +26,49 @@ import java.text.ParseException;
@RequestMapping("/user_detail")
public class UserDetailController implements IBaseController {
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IIdCardService idCardService;
private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailController.class);
private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailController.class);
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IIdCardService idCardService;
@RequestMapping("/save")
public JsonResult saveUserdetail(String idNo, String name) {
try {
if (!ValidationUtil.validateChinese(name)) {
return JsonResult.buildErrorStateResult("姓名错误", null);
}
IdCardInfo info = idCardService.getIdCardInfo(idNo);
if (!info.isValid()) {
return JsonResult.buildErrorStateResult("身份证号码错误", null);
}
User user = getCurrentUser();
if (user == null) {
return JsonResult.buildErrorStateResult("系统错误", null);
}
Timestamp now = new Timestamp(System.currentTimeMillis());
UserDetail userDetail = new UserDetail();
userDetail.setIdNo(idNo);
userDetail.setPhoneNo(user.getPhoneNo());
userDetail.setUserId(user.getId());
userDetail.setCreatedAt(now);
userDetail.setUpdatedAt(now);
userDetail.setName(name);
userDetail.setGender(info.getGender());
userDetail.setEmail("");
userDetail.setIdType(IdType.ID_CARD);
userDetail.setIsAuthenticated(false);
userDetail.setQq("");
try {
userDetailService.saveUserDetail(userDetail);
} catch (DataIntegrityViolationException ex) {
return JsonResult.buildSuccessResult("", null);
}
return JsonResult.buildSuccessResult("", null);
} catch (ParseException ex) {
LOGGER.error("身份证号错误, idNo: {}", idNo);
return JsonResult.buildErrorStateResult("身份证号码错误", null);
}
@RequestMapping("/save")
public JsonResult saveUserdetail(String idNo, String name) {
try {
if (!ValidationUtil.validateChinese(name)) {
return JsonResult.buildErrorStateResult("姓名错误", null);
}
IdCardInfo info = idCardService.getIdCardInfo(idNo);
if (!info.isValid()) {
return JsonResult.buildErrorStateResult("身份证号码错误", null);
}
User user = getCurrentUser();
if (user == null) {
return JsonResult.buildErrorStateResult("系统错误", null);
}
Timestamp now = new Timestamp(System.currentTimeMillis());
UserDetail userDetail = new UserDetail();
userDetail.setIdNo(idNo);
userDetail.setPhoneNo(user.getPhoneNo());
userDetail.setUserId(user.getId());
userDetail.setCreatedAt(now);
userDetail.setUpdatedAt(now);
userDetail.setName(name);
userDetail.setGender(info.getGender());
userDetail.setEmail("");
userDetail.setIdType(IdType.ID_CARD);
userDetail.setIsAuthenticated(false);
userDetail.setQq("");
try {
userDetailService.saveUserDetail(userDetail);
} catch (DataIntegrityViolationException ex) {
return JsonResult.buildSuccessResult("", null);
}
return JsonResult.buildSuccessResult("", null);
} catch (ParseException ex) {
LOGGER.error("身份证号错误, idNo: {}", idNo);
return JsonResult.buildErrorStateResult("身份证号码错误", null);
}
}
}
......@@ -13,32 +13,32 @@ import java.sql.Timestamp;
@Data
@Entity
@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;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id")
private Long userId;
@Column(name = "province_code")
private Long provinceCode;
@Column(name = "province")
private String province;
@Column(name = "city_code")
private Long cityCode;
@Column(name = "city")
private String city;
@Column(name = "districtCode")
private Long districtCode;
@Column(name = "district")
private String district;
@Column(name = "address")
private String address;
@Column(name = "created_at")
private Timestamp createdAt;
@Column(name = "updated_at")
private Timestamp updateAt;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id")
private Long userId;
@Column(name = "province_code")
private Long provinceCode;
@Column(name = "province")
private String province;
@Column(name = "city_code")
private Long cityCode;
@Column(name = "city")
private String city;
@Column(name = "districtCode")
private Long districtCode;
@Column(name = "district")
private String district;
@Column(name = "address")
private String address;
@Column(name = "created_at")
private Timestamp createdAt;
@Column(name = "updated_at")
private Timestamp updateAt;
}
......@@ -10,52 +10,52 @@ import java.io.Serializable;
@Table(name = "channel", uniqueConstraints = @UniqueConstraint(columnNames = "channel_code"))
public class Channel implements Serializable {
private static final long serialVersionUID = -1L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//渠道代号
@Column(name = "channel_code")
private String channelCode;
//渠道名称
@Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getChannelCode() {
return channelCode;
}
public void setChannelCode(String channelCode) {
this.channelCode = channelCode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Channel{" +
"channelCode='" + channelCode + '\'' +
", id=" + id +
", name='" + name + '\'' +
'}';
}
private static final long serialVersionUID = -1L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//渠道代号
@Column(name = "channel_code")
private String channelCode;
//渠道名称
@Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getChannelCode() {
return channelCode;
}
public void setChannelCode(String channelCode) {
this.channelCode = channelCode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Channel{" +
"channelCode='" + channelCode + '\'' +
", id=" + id +
", name='" + name + '\'' +
'}';
}
}
......@@ -14,22 +14,22 @@ import java.sql.Timestamp;
@Entity
@Table(name = "contact")
public class Contact implements Serializable {
private static final long serialVersionUID = -1L;
private static final long serialVersionUID = -1L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id")
private Long userId;
@Column(name = "name")
private String name;
@Column(name = "phone_no")
private String phoneNo;
@Column(name = "relation")
private Relation relation;
@Column(name = "created_at")
private Timestamp createdAt;
@Column(name = "updated_at")
private Timestamp updateAt;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id")
private Long userId;
@Column(name = "name")
private String name;
@Column(name = "phone_no")
private String phoneNo;
@Column(name = "relation")
private Relation relation;
@Column(name = "created_at")
private Timestamp createdAt;
@Column(name = "updated_at")
private Timestamp updateAt;
}
......@@ -15,18 +15,18 @@ import java.sql.Timestamp;
@Data
@Entity
@Table(name = "merchant")
public class Merchant implements Serializable{
public class Merchant implements Serializable {
private static final long serialVersionUID = -1L;
@Id
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "enable")
private boolean enable;
@Column(name = "created_at")
private Timestamp createAt;
@Column(name = "updated_at")
private Timestamp updateAt;
private static final long serialVersionUID = -1L;
@Id
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "enable")
private boolean enable;
@Column(name = "created_at")
private Timestamp createAt;
@Column(name = "updated_at")
private Timestamp updateAt;
}
This diff is collapsed.
This diff is collapsed.
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