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>
......
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);
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.
*/
......@@ -47,7 +46,7 @@ public interface Constants {
long WECHAT = 198L;
}
interface Session{
interface Session {
String USER_SESSION_CACHE = "user:session:";
String USER_SESSION_ID_CACHE = "userid-sessionvalue:cache:";
Long ONE_DAY = 24 * 60 * 60L;
......
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.
......@@ -15,5 +11,6 @@ import java.lang.annotation.Target;
public @interface FPLock {
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;
/**
......@@ -16,10 +12,13 @@ import java.util.concurrent.TimeUnit;
public @interface FPRestriction {
// 持续时间
int duration() default 1;
// 持续时间单位
TimeUnit type() default TimeUnit.MINUTES;
// 限制值, -1表示不限制
int limit() default -1;
// 使用可覆盖
boolean override() default true;
}
......@@ -35,11 +35,6 @@ import java.util.stream.Stream;
public class FirstParamLockAspect {
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 Long MAX_COUNTER = 1L;
private static final Long MAX_TO_LIVE = 10L;
......@@ -50,6 +45,9 @@ public class FirstParamLockAspect {
LOCK_PARAM = fastHashMap;
}
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate;
/* 自定义限制策略 (FPRestriction) 的情况下, 可配置的限制数值 */
@Value("${xyqb.fplock.limit.byhour:3}")
private Integer limitByHour; // 每小时限制值
......@@ -129,8 +127,8 @@ public class FirstParamLockAspect {
public void setLimitation(String key, Integer duration, Integer limit) {
FPRestrictionWraper restriction = LOCK_PARAM.get(key);
if (restriction != null) {
if(duration != null) restriction.duration(duration);
if(limit != null) restriction.limit(limit);
if (duration != null) restriction.duration(duration);
if (limit != null) restriction.limit(limit);
}
}
......@@ -213,6 +211,28 @@ public class FirstParamLockAspect {
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 {
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 {
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};
......
......@@ -75,7 +75,7 @@ public class CustomJCaptchaService extends AbstractManageableImageCaptchaService
}
this.getTimes().remove(id);
if(valid) {
if (valid) {
addNumberOfCorrectResponse(1);
} else {
addNumberOfUncorrectResponse(1);
......
......@@ -87,7 +87,6 @@ public class JpaConfig {
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
......
......@@ -6,8 +6,6 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
......
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.
......
......@@ -12,9 +12,10 @@ import java.sql.Timestamp;
*/
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;
Timestamp time = (Timestamp) object;
if (time == null) {
serializer.write(String.valueOf(0L));
} 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;
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,7 +13,11 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
@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 = "帐号或密码错误";
}
......@@ -51,7 +51,6 @@ public class ExceptionHandlingController implements IBaseController {
}
@ExceptionHandler(Exception.class)
public JsonResult exceptionOccurs(Exception e) {
HttpServletRequest request = getRequest();
......
......@@ -7,7 +7,8 @@ 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.
......
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;
......@@ -78,4 +79,13 @@ public class ImageCaptchaController implements IBaseController {
}
/**
* 图片验证码验证
*/
@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);
}
}
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;
}
}
......@@ -31,6 +31,8 @@ import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Random;
import static cn.quantgroup.xyqb.constant.UserConstant.USER_ERROR_OR_PASSWORD_ERROR;
/**
* @author mengfan.feng
* @time 2015-10-27 11:41
......@@ -40,7 +42,7 @@ import java.util.Random;
public class AppController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(AppController.class);
private final static Random random = new Random();
@Autowired
private ISessionService sessionService;
@Autowired
......@@ -51,7 +53,6 @@ public class AppController implements IBaseController {
private IUserRepository userRepository;
@Autowired
private ISmsService smsService;
@Autowired
private IUserDetailService userDetailService;
@Autowired
......@@ -59,21 +60,18 @@ public class AppController implements IBaseController {
@Autowired
private IMerchantService merchantService;
private final static Random random = new Random();
/**
* 第三方用户登录
*
*/
@RequestMapping("/login")
public JsonResult login(
String phoneNo,
@RequestParam(required = false, defaultValue = "1") Long registerFrom,
@RequestParam(required = false, defaultValue = "1") Long channelId,
String idNo, String name, String key, @RequestParam(required = false, defaultValue = "")String appChannel, HttpServletRequest request
String idNo, String name, String key, @RequestParam(required = false, defaultValue = "") String appChannel, HttpServletRequest request
) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return JsonResult.buildErrorStateResult("该用户名不存在,<br/>请重新输入或注册新账号。", null);
return JsonResult.buildErrorStateResult(USER_ERROR_OR_PASSWORD_ERROR, null);
}
String requestIp = IPUtil.getRemoteIP(request);
......@@ -83,7 +81,10 @@ public class AppController implements IBaseController {
user = register(registerFrom, phoneNo, idNo, name, channelId);
}
if (user == null) {
return JsonResult.buildErrorStateResult("该用户名不存在,<br/>请重新输入或注册新账号。", null);
return JsonResult.buildErrorStateResult(USER_ERROR_OR_PASSWORD_ERROR, null);
}
if (!user.getEnable()) {
return JsonResult.buildErrorStateResult("登录失败", null);
}
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
......@@ -104,17 +105,16 @@ public class AppController implements IBaseController {
/**
* 第三方用户登录并返回用户信息
*
*/
@RequestMapping("/login_super")
public JsonResult loginSuper (
public JsonResult loginSuper(
String phoneNo,
@RequestParam(required = false, defaultValue = "1") Long registerFrom,
@RequestParam(required = false, defaultValue = "1") Long channelId,
String idNo, String name, String key, @RequestParam(required = false, defaultValue = "")String appChannel, HttpServletRequest request
String idNo, String name, String key, @RequestParam(required = false, defaultValue = "") String appChannel, HttpServletRequest request
) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return JsonResult.buildErrorStateResult("该用户名不存在,<br/>请重新输入或注册新账号。", null);
return JsonResult.buildErrorStateResult(USER_ERROR_OR_PASSWORD_ERROR, null);
}
String requestIp = IPUtil.getRemoteIP(request);
......@@ -124,7 +124,10 @@ public class AppController implements IBaseController {
user = register(registerFrom, phoneNo, idNo, name, channelId);
}
if (user == null) {
return JsonResult.buildErrorStateResult("该用户名不存在,<br/>请重新输入或注册新账号。", null);
return JsonResult.buildErrorStateResult(USER_ERROR_OR_PASSWORD_ERROR, null);
}
if (!user.getEnable()) {
return JsonResult.buildErrorStateResult("登录失败", null);
}
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
......@@ -166,7 +169,7 @@ public class AppController implements IBaseController {
LOGGER.info("第三方登录用户,保存 User");
User user = new User();
if(channelId == 222L) {
if (channelId == 222L) {
user.setRegisteredFrom(channelId);
} else {
user.setRegisteredFrom(registerFrom);
......@@ -180,14 +183,16 @@ public class AppController implements IBaseController {
user.setCreatedAt(currentTime);
userRepository.saveAndFlush(user);
if(registerFrom != 645L) {
if (registerFrom != 645L && registerFrom != 900L) {
smsService.sendAfterRegister(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)) {
LOGGER.info("第三方登录用户,保存 UserDetail");
IdCardInfo cardInfo;
try {
cardInfo = idCardService.getIdCardInfoWithExceptions(idNo);
......
......@@ -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);
if (info == null) {
Timestamp now = new Timestamp(System.currentTimeMillis());
if (info == null) {
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
......@@ -57,12 +57,14 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
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 List<String> authorizationTypeList= new ArrayList<>();
private static List<String> authorizationTypeList = new ArrayList<>();
static {
//授权类型
authorizationTypeList.add("1");
authorizationTypeList.add("2");
}
@Value("${xyqb.url}")
private String xyqbUrl;
......@@ -102,13 +104,13 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
result.put("errorcode", Jr58.ERROR_PHONE_NUMBER);
return result;
}
if(StringUtils.isBlank(param.getAccount())){
LOGGER.error("58金融授权账号-account={}",param.getAccount());
if (StringUtils.isBlank(param.getAccount())) {
LOGGER.error("58金融授权账号-account={}", param.getAccount());
result.put("errorcode", Jr58.ERROR_ACCOUNT);
return result;
}
if(StringUtils.isBlank(param.getAuthorizationType()) || !authorizationTypeList.contains(param.getAuthorizationType())){
LOGGER.error("58金融授权类型-authorization={} ",param.getAuthorizationType());
if (StringUtils.isBlank(param.getAuthorizationType()) || !authorizationTypeList.contains(param.getAuthorizationType())) {
LOGGER.error("58金融授权类型-authorization={} ", param.getAuthorizationType());
result.put("errorcode", Jr58.ERROR_AUTH_TYPE);
return result;
}
......@@ -120,16 +122,16 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
return result;
}
try {
if(StringUtils.isNotBlank(param.getWbUserName())){
if (StringUtils.isNotBlank(param.getWbUserName())) {
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"));
}
if(StringUtils.isNotBlank(param.getName())){
if (StringUtils.isNotBlank(param.getName())) {
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"));
}
......@@ -147,7 +149,7 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
} catch (Exception 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金融运营商授权状态更新结束");
result.put("customerid", uuid);
result.put("success", true);
......@@ -190,9 +192,9 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
UuidPhoneMapping phoneMapping = uuidPhoneMappingService.findByUuid(uuid);
String phoneNo = null;
if(phoneMapping != null){
if (phoneMapping != null) {
phoneNo = phoneMapping.getPhoneNo();
}else{
} else {
LOGGER.error("58金融运营商授权数据导入接口 - uuid对应的UuidPhoneMapping为空");
}
// 手机号在新系统中存在,说明之前已经注册过
......@@ -216,57 +218,58 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
/**
* 58金融运营商授权数据导入接口
*
* @param authorizationData 入参
* @return JsonResult
*/
@RequestMapping(value = "/import_authorization_data", method= RequestMethod.POST)
@RequestMapping(value = "/import_authorization_data", method = RequestMethod.POST)
public JsonResult importAuthorizationData(@RequestBody Jr58Authorization authorizationData) {
String authorizationDataStr = null;
LOGGER.info("推送的运营商数据userId={}",authorizationData.getUserId());
LOGGER.info("推送的运营商数据sourceFrom={}",authorizationData.getSourceFrom());
if(StringUtils.isEmpty(authorizationData.getAuthorizationData())){
LOGGER.info("推送的运营商数据userId={}", authorizationData.getUserId());
LOGGER.info("推送的运营商数据sourceFrom={}", authorizationData.getSourceFrom());
if (StringUtils.isEmpty(authorizationData.getAuthorizationData())) {
LOGGER.error("58金融运营商授权数据导入接口 - authorizationData不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - authorizationData不能为空",null);
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - authorizationData不能为空", null);
}
//try {
authorizationDataStr = JR58GzipUtil.bytesTogzip(Base64.decodeBase64(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) {
LOGGER.error("58金融生成借款申请失败,base64转换失败");
return JsonResult.buildErrorStateResult("58金融导入运营商授权数据失败",null);
}*/
//authorizationData.setOperator_data(new Gson().fromJson(authorizationDataStr, Jr58Authorization.OperatorData.class));
authorizationData.setOperator_data(JSONObject.parseObject(authorizationDataStr, Jr58Authorization.OperatorData.class));
if(authorizationData == null){
if (authorizationData == null) {
LOGGER.error("58金融运营商授权数据导入接口 - 入参不完整");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入 - 入参不完整",null);
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入 - 入参不完整", null);
}
String userId = authorizationData.getUserId();
String phoneNo= null;
if(authorizationData.getOperator_data() != null && authorizationData.getOperator_data().getOriginalData() != null){
phoneNo= authorizationData.getOperator_data().getOriginalData().getPhone();
String phoneNo = null;
if (authorizationData.getOperator_data() != null && authorizationData.getOperator_data().getOriginalData() != null) {
phoneNo = authorizationData.getOperator_data().getOriginalData().getPhone();
}
if(phoneNo == null){
LOGGER.info("推送的运营商数据authorizationData={}",authorizationData.getAuthorizationData());
if (phoneNo == null) {
LOGGER.info("推送的运营商数据authorizationData={}", authorizationData.getAuthorizationData());
LOGGER.error("58金融运营商授权数据导入接口 - phoneNo不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整",null);
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整", null);
}
LOGGER.info("收到来自58金融运营商授权导入请求, userId:{}", userId);
if (StringUtils.isEmpty(authorizationData.getSourceFrom())) {
LOGGER.error("58金融运营商授权数据导入接口 - sourceFrom不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - sourceFrom不能为空",null);
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - sourceFrom不能为空", null);
}
if (StringUtils.isEmpty(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()
|| null == authorizationData.getOperator_data().getOriginalData())){
LOGGER.error("58金融运营商授权数据导入接口 - 入参不完整, sourceFrom : {}, authorizationDataStr={}", authorizationData.getSourceFrom(),authorizationDataStr);
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整",null);
if ("1".equals(authorizationData.getSourceFrom()) && (null == authorizationData.getOperator_data()
|| null == authorizationData.getOperator_data().getOriginalData())) {
LOGGER.error("58金融运营商授权数据导入接口 - 入参不完整, sourceFrom : {}, authorizationDataStr={}", authorizationData.getSourceFrom(), authorizationDataStr);
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整", null);
}
String uuid = userId.toLowerCase();
......@@ -276,13 +279,13 @@ public class Jr58Controller implements ApplicationEventPublisherAware {
// 用户不存在
if (user == null) {
LOGGER.error("58金融运营商授权数据导入接口 - 用户不存在,userId=[{}]", userId);
return JsonResult.buildErrorStateResult("用户不存在,userId="+userId,null);
return JsonResult.buildErrorStateResult("用户不存在,userId=" + userId, null);
}
// 推送授权to风控
jr58Service.pushAuthorizationData(authorizationData);
LOGGER.info("58金融运营商数据导入结束");
return JsonResult.buildSuccessResult("success",null);
return JsonResult.buildSuccessResult("success", null);
}
}
......@@ -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;
......
......@@ -5,19 +5,15 @@ import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.entity.Merchant;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WechatUserInfo;
import cn.quantgroup.xyqb.event.UserinfoChangedEvent;
import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.webchat.AccessTokenResponse;
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.user.IUserService;
import cn.quantgroup.xyqb.service.wechat.IWechatService;
import cn.quantgroup.xyqb.util.EmojiUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
......@@ -34,6 +30,7 @@ import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
/**
* Created by 11 on 2017/1/17.
......@@ -60,13 +57,12 @@ public class WeChatController implements IBaseController {
@Autowired
private IUserService userService;
@Autowired
private IPageService pageService;
// https://passport.xyqb.com/landing?key=xxx&target=cashTarget5&registerFrom=198&channelId=%d
@Value("${xyqb-user.ui}")
private String userUIAddr;
@Value("${xyqb.user.domain}")
private String userDomainStr;
/**
* 开发者资质认证,有必要吗?
......@@ -83,30 +79,6 @@ public class WeChatController implements IBaseController {
return "";
}
/**
* 微信登录
*
* @param name 姓名
* @param idNo 身份证号
* @param phoneNo 手机号
* @param registerFrom ${registerFrom}
* @param channelId ${channelId}
* @param appChannel ${appChanel}
* @param key "xyqb"
* @return
*/
public JsonResult webChatLogin(String name, String idNo, String phoneNo, String registerFrom,
String channelId, String appChannel, String key) {
if (StringUtils.isBlank(name) || StringUtils.isBlank(idNo) || StringUtils.isBlank(phoneNo)) {
return JsonResult.buildErrorStateResult("请填写完整的用户信息.", null);
}
if (StringUtils.isBlank(key)) {
return JsonResult.buildErrorStateResult("无效的商户信息.", null);
}
return null;
}
/**
* 验签:步骤
* 1.获取signature, timestamp, nonce三个参数
......@@ -121,8 +93,7 @@ public class WeChatController implements IBaseController {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String token = TOKEN;
String[] arrs = new String[]{token, timestamp, nonce};
String[] arrs = new String[]{TOKEN, timestamp, nonce};
Arrays.sort(arrs);
String joinStr = joinArray(arrs);
joinStr = sha1(joinStr);
......@@ -135,16 +106,16 @@ public class WeChatController implements IBaseController {
* @param decript
* @return 返回40位16进制字符串
*/
public String sha1(String decript) {
private String sha1(String decript) {
try {
MessageDigest digest = java.security.MessageDigest
.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
StringBuilder hexString = new StringBuilder();
// 字节数组转换为十六进制数
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
for (byte aMessageDigest : messageDigest) {
String shaHex = Integer.toHexString(aMessageDigest & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
......@@ -172,65 +143,6 @@ public class WeChatController implements IBaseController {
return builder.toString();
}
/**
* 通过redirect_url获取code
*
* @param response
* @return
*/
@RequestMapping("/receiveCode/{key}/{redirect}")
public void receiveCode(
String code, @PathVariable(value = "key") String systemKey,
@PathVariable String redirect, HttpServletRequest request, HttpServletResponse response) {
String schema = request.getScheme();
LOGGER.info("HTTP协议:" + schema);
// 从code获取token
Merchant merchant = merchantService.findMerchantByName(systemKey);
AccessTokenResponse token = wechatService.getToken(code);
if (token == null) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
return;
}
WechatUserInfo userInfo = wechatService.getWechatUserInfoFromWechatServer(token.getAccessToken(), token.getOpenId());
if (userInfo == null || StringUtils.isEmpty(userInfo.getOpenId())) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
return;
}
WechatUserInfo userInfoInDb = wechatService.findWechatUserInfoFromDb(userInfo.getOpenId());
// welcome 首次登录
if (userInfoInDb == null) {
// 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面
if(StringUtils.isNotBlank(userInfo.getNickName())) {
String nickName = EmojiUtil.filter(userInfo.getNickName());
userInfo.setNickName(nickName);
}
userInfo = wechatService.saveWechatUserInfo(userInfo);
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfo, Constants.Channel.WECHAT);
return;
}
if (userInfoInDb.getUserId() == null) {
// 用户已经微信登录了,但是没有关联信用钱包,跳转到注册页面
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb, Constants.Channel.WECHAT);
return;
}
User user = userService.findById(userInfoInDb.getUserId());
if (user == null) {
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb, Constants.Channel.WECHAT);
return;
}
// 已经关联了用户
// create session, 登进去,该怎么玩怎么玩。
String redirectUrl = createUserSession(user, merchant, redirect, schema, Constants.Channel.WECHAT);
response.setHeader("Location", redirectUrl);
response.setStatus(301);
}
/**
* 前端微信跳转页面,通过extdata
*
......@@ -239,8 +151,8 @@ public class WeChatController implements IBaseController {
*/
@RequestMapping("/receiveCode/extdata/{key}/{extdata}")
public void receiveCodeWithExtData(
String code, @PathVariable(value = "key") String systemKey, @PathVariable(value = "extdata") String extData,
HttpServletRequest request, HttpServletResponse response
String code, @PathVariable(value = "key") String systemKey,
@PathVariable(value = "extdata") String extData, HttpServletResponse response
) {
try {
String schema = getProtocol();
......@@ -409,12 +321,8 @@ public class WeChatController implements IBaseController {
LOGGER.error("发生异常", ex);
throw ex;
}
}
/**
* 通过redirect_url获取code
*
......@@ -444,7 +352,7 @@ public class WeChatController implements IBaseController {
// welcome 首次登录
if (userInfoInDb == null) {
// 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面
if(StringUtils.isNotBlank(userInfo.getNickName())) {
if (StringUtils.isNotBlank(userInfo.getNickName())) {
String nickName = EmojiUtil.filter(userInfo.getNickName());
userInfo.setNickName(nickName);
}
......@@ -465,38 +373,43 @@ public class WeChatController implements IBaseController {
// 已经关联了用户
// create session, 登进去,该怎么玩怎么玩。
String redirectUrl = createUserSession(user, merchant, "", schema, Constants.Channel.WECHAT);
LOGGER.info("Location={}", redirectUrl);
response.setHeader("Location", redirectUrl);
response.setStatus(301);
}
private String createUserSession(User user, Merchant merchant, String redirect, String schema, Long registerFrom) {
//TODO 临时紧急上线修改的.下次上线的时候修复一下,不能这样写.
String url = "http://passport.xyqb.com";
if("https".equals(schema)) {
url = "https://passport.xyqb.com";
//String url = "http://passport.xyqb.com";
String url = "http://"+userDomainStr;
if ("https:".equals(schema)) {
url = "https://"+userDomainStr;
}
if(StringUtils.isEmpty(redirect) || "redirect".equals(redirect)) {
if (StringUtils.isEmpty(redirect) || "redirect".equals(redirect)) {
LOGGER.info("微信登录:redirect为null,走正常流程.");
if ("baitiao".equals(merchant.getName())) {
return loginInWechatWithSessionCreated(user, merchant, "cashTarget5", Constants.Channel.BAITIAO, url, Constants.Channel.WECHAT);
} else if ("wechat-pay".equals(merchant.getName())) {
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";
} else {
return loginInWechatWithSessionCreated(user, merchant, "cashTarget4", 1L, url, registerFrom);
}
} else if("local".equals(redirect)){
} else if ("local".equals(redirect)) {
LOGGER.info("微信登录:redirect不为null,创建session跳到指定前端页面.");
AuthBean authBean = sessionService.createSession(Constants.Channel.WECHAT, Constants.Channel.WECHAT, "", user, merchant);
LOGGER.info("微信登录:跳转地址{}", url + "/weixin/callback?phoneNo=" + user.getPhoneNo() + "&token=" + authBean.getToken());
Long channelId = "baitiao".equals(merchant.getName()) ? 222L : 1L;
String target = "baitiao".equals(merchant.getName()) ? "cashTarget5" : "cashTarget4";
return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom+
"&channelId=" + channelId +"&key=" + merchant.getName() +"&target=" + target + "&isWechat=true";
return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom +
"&channelId=" + channelId + "&key=" + merchant.getName() + "&target=" + target + "&isWechat=true";
}
return null;
}
private String loginInWechatWithSessionCreated(User user, Merchant merchant, String target, Long channelId, String url, Long registerFrom) {
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) {
......@@ -514,6 +427,8 @@ public class WeChatController implements IBaseController {
private String assembleNormalRedirectUrl(Merchant merchant, Long registerFrom) {
if ("baitiao".equals(merchant.getName())) {
return userUIAddr + "/landing?key=baitiao&target=cashTarget5&channelId=222&registerFrom=198";
} else if ("wechat-pay".equals(merchant.getName())) {
return userUIAddr + "/landing?key=wechat-pay&target=cashTarget5&channelId=1&page=landing/4&registerFrom" + registerFrom;
} else {
return userUIAddr + "/landing?key=xyqb&target=cashTarget4&channelId=1&registerFrom=" + registerFrom;
}
......@@ -522,6 +437,8 @@ public class WeChatController implements IBaseController {
private String assembleWechatRedirectUrl(Merchant merchant, WechatUserInfo userInfo, Long registerFrom) {
if ("baitiao".equals(merchant.getName())) {
return userUIAddr + "/landing?key=baitiao&target=cashTarget5&registerFrom=198&channelId=222&isWechat=true&openId=" + userInfo.getOpenId();
} else if ("wechat-pay".equals(merchant.getName())) {
return userUIAddr + "/landing?key=wechat-pay&target=cashTarget5&page=landing/4&registerFrom= " + registerFrom + "&channelId=1&isWechat=true&openId=" + userInfo.getOpenId();
} else {
return userUIAddr + "/landing?key=xyqb&target=cashTarget4&registerFrom= " + registerFrom + "&channelId=1&isWechat=true&openId=" + userInfo.getOpenId();
}
......
......@@ -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,6 +24,9 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/platform/api")
public class PlatformAPIController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(PlatformAPIController.class);
@Autowired
private IPageService pageService;
@Autowired
......@@ -33,7 +38,7 @@ public class PlatformAPIController implements IBaseController {
if (null == merchant) {
return JsonResult.buildErrorStateResult("", null);
}
MerchantConfig config= merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl");
MerchantConfig config = merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl");
if (null == config) {
return JsonResult.buildSuccessResult("", null);
}
......@@ -67,5 +72,4 @@ public class PlatformAPIController implements IBaseController {
}
}
......@@ -27,20 +27,16 @@ import java.util.concurrent.TimeUnit;
public class SmsController {
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;
private static final Random random = new Random();
private static final long EXPIRE_MINUTES = 10;
/**
* 短信验证码: for H5
* 使用 @FPLock 注解并加入自定义限制参数, 做针对手机号的发送次数限制
......
......@@ -106,6 +106,9 @@ public class UserController implements IBaseController {
JsonResult successResult = validMap.get("success");
String phoneNo = successResult.getData().toString();
User user = userService.findByPhoneWithCache(phoneNo);
if (user != null && !user.getEnable()) {
return JsonResult.buildErrorStateResult("登录失败", null);
}
if (user == null) {
user = registerFastWhenLogin(phoneNo, channelId, createdFrom, appChannel);
if (user == null) {
......@@ -403,7 +406,7 @@ public class UserController implements IBaseController {
String userName = credentialArr[0];
String pass = credentialArr[1];
User user = userService.findByPhoneWithCache(userName);
if (user == null) {
if (user == null || !user.getEnable()) {
return null;
}
//验证密码
......@@ -421,7 +424,7 @@ public class UserController implements IBaseController {
//查询用户,存在则保存用户session信息,userId为uuid
User user = userService.findByUuidInDb(userId);
//用户信息存在,更新session中的最后访问时间,重新写入缓存.
if (null != user) {
if (null != user || !user.getEnable()) {
return new JsonResult(sessionService.createSession(channelId, createdFrom, appChannel, user, merchant));
} else {
return JsonResult.buildErrorStateResult("登录失败", null);
......
......@@ -26,11 +26,11 @@ import java.text.ParseException;
@RequestMapping("/user_detail")
public class UserDetailController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailController.class);
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IIdCardService idCardService;
private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailController.class);
@RequestMapping("/save")
public JsonResult saveUserdetail(String idNo, String name) {
......
......@@ -13,7 +13,7 @@ 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;
......
......@@ -15,7 +15,7 @@ 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
......
package cn.quantgroup.xyqb.entity;
import cn.quantgroup.motan.retbean.XUser;
import cn.quantgroup.xyqb.config.http.Timestamp2LongConverter;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.*;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.jws.soap.SOAPBinding;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
......@@ -57,4 +58,18 @@ public class User implements Serializable {
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;
import cn.quantgroup.motan.retbean.XUserDetail;
import cn.quantgroup.xyqb.model.Gender;
import cn.quantgroup.xyqb.model.IdType;
import lombok.*;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.io.Serializable;
......@@ -64,5 +67,27 @@ public class UserDetail implements Serializable {
@Column(name = "updated_at")
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;
import cn.quantgroup.xyqb.entity.enumerate.*;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.Data;
import javax.persistence.*;
......
......@@ -24,10 +24,10 @@ public class UuidPhoneMapping implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column (name = "uuid")
@Column(name = "uuid")
private String uuid;
@Column (name = "phone_no")
@Column(name = "phone_no")
private String phoneNo;
......
......@@ -13,7 +13,7 @@ import java.sql.Timestamp;
@Entity
@Table(name = "wechat_userinfo")
@Data
public class WechatUserInfo implements Serializable{
public class WechatUserInfo implements Serializable {
private static final long serialVersionUID = -1L;
@Id
......
......@@ -21,14 +21,14 @@ public enum EducationEnum {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
......
......@@ -10,7 +10,7 @@ public enum IncomeEnum {
CASH_AND_PAY_CARD("混合");
private String desc;
private IncomeEnum(String desc){
private IncomeEnum(String desc) {
this.desc = desc;
}
}
\ No newline at end of file
......@@ -16,7 +16,7 @@ public enum IncomeRangeEnum {
private String desc;
private IncomeRangeEnum(String desc){
private IncomeRangeEnum(String desc) {
this.desc = desc;
}
......
......@@ -23,14 +23,14 @@ public enum OccupationEnum {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
......
package cn.quantgroup.xyqb.exception;
/**
* @author mengfan.feng
* @time 2015-09-08 17:43
*/
public class UserNotExistException extends RuntimeException{
public class UserNotExistException extends RuntimeException {
private static final long serialVersionUID = -1L;
......
......@@ -22,12 +22,6 @@ import java.util.Set;
@Configuration
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<>();
static {
......@@ -36,6 +30,10 @@ public class CrosFilter implements Filter {
DISALLOWED_METHOD.add("DELETE");
}
@Value("${xyqb.filter.allowedOrigin}")
private String allowedOrigin;
@Value("${xyqb.filter.allowedHeaders}")
private String allowedHeaders;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
......
......@@ -25,17 +25,17 @@ import java.io.PrintWriter;
@Order(Ordered.HIGHEST_PRECEDENCE + 100)
public class RequestFilter implements Filter {
private static final String[] ALLOWED_PATTERNS = {
"/innerapi/**", "/user/exist", "/motan/**", "/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));
@Autowired
private ISessionService sessionService;
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", "/user/center/**"
};
private static final String UNAUTH_RESULT = JSONObject.toJSONString(JsonResult.buildErrorStateResult("登录失败", null));
@Override
public void init(FilterConfig filterConfig) throws ServletException {
......@@ -47,10 +47,10 @@ public class RequestFilter implements Filter {
HttpServletResponse response = (HttpServletResponse) servletResponse;
String requestPath = getRequestPath(request);
SessionStruct sessionStruct;
if(!isMatch(requestPath)){
if (!isMatch(requestPath)) {
//获取session信息,如果没有获取到session信息则返回错误信息
sessionStruct = XyqbSessionContextHolder.getXSession();
if(sessionStruct == null) {
if (sessionStruct == null) {
response.setStatus(401);
response.setHeader("Content-Type", "application/json;charset=utf-8");
PrintWriter writer = response.getWriter();
......@@ -70,7 +70,7 @@ public class RequestFilter implements Filter {
}
}
}
}else {
} else {
filterChain.doFilter(request, response);
}
......
package cn.quantgroup.xyqb.interceptors;
import cn.quantgroup.xyqb.util.IPUtil;
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.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 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)){
/*boolean isMatch = pattern.matcher(remoteIP).matches();
if(!isMatch){
LOGGER.info("非法IP尝试访问,ip:[{}]",remoteIP);
}
return isMatch;*/
LOGGER.info("来源IP:[{}]",remoteIP);
}
// LOGGER.info("未能获取remoteIP");
return true;
}
@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;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.*;
import java.io.Serializable;
......
......@@ -10,7 +10,7 @@ public class AuthBean {
private String token;
private String phoneNo;
public AuthBean (String token, Principal user) {
public AuthBean(String token, Principal user) {
this.token = token;
this.phoneNo = user.getName();
}
......
......@@ -26,7 +26,7 @@ public class ContactRet implements Serializable {
private Long updateAt;
public static ContactRet contact2ContactRet (Contact c) {
public static ContactRet contact2ContactRet(Contact c) {
if (c == null) {
return null;
}
......
......@@ -14,14 +14,14 @@ public enum Gender {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
......
......@@ -22,14 +22,14 @@ public enum IdType {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
......
......@@ -48,6 +48,10 @@ public class JsonResult implements Serializable {
this.businessCode = String.format(Constants.ZERO_FILL_TEMPLATE, businessCode);
}
public JsonResult(Object data) {
this.data = data;
}
/**
* 构造成功的JsonResult
*
......@@ -82,10 +86,6 @@ public class JsonResult implements Serializable {
return new JsonResult(msg, ERROR_STATE_CODE, data, busniessId);
}
public JsonResult(Object data) {
this.data = data;
}
public String getMsg() {
return msg;
}
......
......@@ -21,14 +21,14 @@ public final class Tuple<Key, Value> {
return key;
}
public Value getValue() {
return value;
}
public void setKey(Key key) {
this.key = key;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
......
......@@ -4,14 +4,13 @@ import cn.quantgroup.xyqb.entity.UserDetail;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import java.io.Serializable;
/**
* Created by 11 on 2016/12/20.
*/
@Data
public class UserDetailRet implements Serializable{
public class UserDetailRet implements Serializable {
private static final long serialVersionUID = -1L;
private Long id;
......@@ -46,10 +45,11 @@ public class UserDetailRet implements Serializable{
/**
* 转换时间从timestamp到long
*
* @param userDetail
* @return return self
*/
public static UserDetailRet getUserDetail(UserDetail userDetail){
public static UserDetailRet getUserDetail(UserDetail userDetail) {
long createTimeStamp = userDetail.getCreatedAt().getTime();
long updateTimeStamp = userDetail.getUpdatedAt().getTime();
UserDetailRet userDetailRet = new UserDetailRet();
......
......@@ -4,8 +4,6 @@ import cn.quantgroup.xyqb.entity.UserExtInfo;
import cn.quantgroup.xyqb.entity.enumerate.*;
import lombok.Data;
import java.sql.Timestamp;
/**
* Created by Miraculous on 2017/2/13.
*/
......
......@@ -10,7 +10,7 @@ import java.io.Serializable;
* Created by 11 on 2016/12/20.
*/
@Data
public class UserRet implements Serializable{
public class UserRet implements Serializable {
private static final long serialVersionUID = -1L;
private Long id;
......@@ -35,7 +35,7 @@ public class UserRet implements Serializable{
//上一次修改时间
private Long updatedAt;
public static UserRet getUserRet(User user){
public static UserRet getUserRet(User user) {
Long createTimeStamp = user.getCreatedAt().getTime();
Long updateTimeStamp = user.getUpdatedAt().getTime();
UserRet userRet = new UserRet();
......
......@@ -18,7 +18,7 @@ public class Jr58Authorization {
@Getter
@Setter
public static class OperatorData{
public static class OperatorData {
private OriginalData originalData;
private ReportData reportData;
......@@ -33,7 +33,7 @@ public class Jr58Authorization {
@Getter
@Setter
public static class PhoneData{
public static class PhoneData {
private Long id;
private String phoneNum;
private String serialNo;
......@@ -47,7 +47,7 @@ public class Jr58Authorization {
@Getter
@Setter
public static class PhoneBillDataList{
public static class PhoneBillDataList {
private String localPhone;
private String totalCost;
private String planCost;
......@@ -58,7 +58,7 @@ public class Jr58Authorization {
@Getter
@Setter
public static class PhoneCallLogList{
public static class PhoneCallLogList {
private String localPhone;
private String callPhone;
private String callId;
......@@ -73,7 +73,7 @@ public class Jr58Authorization {
@Getter
@Setter
public static class PhoneSmsLogList{
public static class PhoneSmsLogList {
private String localPhone;
private String otherPhone;
private String sendId;
......@@ -86,13 +86,9 @@ public class Jr58Authorization {
}
@Getter
@Setter
public static class ReportData{
public static class ReportData {
private String localPhone;
private Behavior behavior;
private Check check;
......@@ -105,7 +101,7 @@ public class Jr58Authorization {
@Getter
@Setter
public static class Behavior{
public static class Behavior {
private String localPhone;
private String friendCircle;
private String localLivingYear;
......@@ -130,7 +126,7 @@ public class Jr58Authorization {
@Getter
@Setter
public static class Check{
public static class Check {
private String localPhone;
private String idCardValidate;
private String operatorBinding;
......@@ -147,7 +143,7 @@ public class Jr58Authorization {
@Getter
@Setter
public static class CallList{
public static class CallList {
private String localPhone;
private String phoneNum;
private String attribution;
......@@ -180,14 +176,14 @@ public class Jr58Authorization {
@Setter
@Getter
public static class ContactList{
public static class ContactList {
}
@Getter
@Setter
public static class OperatorList{
public static class OperatorList {
private String localPhone;
private String operatorName;
private String operatorZh;
......@@ -209,7 +205,7 @@ public class Jr58Authorization {
@Getter
@Setter
public static class RegionList{
public static class RegionList {
private String localphone;
private String regionName;
private String numCount;
......@@ -230,7 +226,7 @@ public class Jr58Authorization {
@Setter
@Getter
public static class ServiceList{
public static class ServiceList {
private String localPhone;
private String companyName;
private String companyType;
......@@ -243,7 +239,7 @@ public class Jr58Authorization {
@Setter
@Getter
public static class TripConsumeList{
public static class TripConsumeList {
}
......@@ -251,5 +247,4 @@ public class Jr58Authorization {
}
}
package cn.quantgroup.xyqb.model.session;
import cn.quantgroup.motan.retbean.XLoginInfo;
import cn.quantgroup.xyqb.model.UserRet;
import com.alibaba.fastjson.JSON;
import lombok.Data;
/**
......@@ -13,6 +15,14 @@ public class LoginInfo {
private UserRet user;
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
public static class LoginContext {
......
......@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.model.session;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections.map.HashedMap;
import java.io.Serializable;
import java.util.HashMap;
......
......@@ -15,7 +15,7 @@ import java.util.Map;
*/
@Data
@NoArgsConstructor
public class SessionValue{
public class SessionValue {
private User user;
private Map<String, String> values;
......
......@@ -9,7 +9,7 @@ import java.io.Serializable;
* 微信获取access_token接口的返回值
*/
@Data
public class AccessTokenResponse implements Serializable{
public class AccessTokenResponse implements Serializable {
private static final long serialVersionUID = -1L;
private String accessToken;
private Long expiresIn;
......
......@@ -6,5 +6,5 @@ import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by 11 on 2016/12/30.
*/
public interface IMerchantConfigRepository extends JpaRepository<MerchantConfig, Long>{
public interface IMerchantConfigRepository extends JpaRepository<MerchantConfig, Long> {
}
......@@ -2,11 +2,12 @@ package cn.quantgroup.xyqb.repository;
import cn.quantgroup.xyqb.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* Created by Miraculous on 15/7/4.
*/
public interface IUserRepository extends JpaRepository<User, Long> {
public interface IUserRepository extends JpaRepository<User, Long> ,JpaSpecificationExecutor<User>{
User findByPhoneNo(String phoneNo);
......
......@@ -6,7 +6,7 @@ import org.springframework.data.jpa.repository.JpaRepository;
/**
* 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);
......
......@@ -9,6 +9,8 @@ import org.springframework.data.jpa.repository.JpaRepository;
*/
public interface IWeChatUserRepository extends JpaRepository<WechatUserInfo, Long> {
WechatUserInfo findByOpenId(String openId);
WechatUserInfo findByPhoneNo(String phoneNo);
WechatUserInfo findByUserId(Long userId);
}
......@@ -21,12 +21,11 @@ public class UserApiServiceImpl implements IUserApiService {
private IUserService userService;
@Override
public boolean userImportCheck(String phoneNo) {
User user=userService.findByPhoneWithCache(phoneNo);
User user = userService.findByPhoneWithCache(phoneNo);
if (user!=null){
if (user != null) {
return false;
}
......
......@@ -10,6 +10,7 @@ public interface IHttpService {
/**
* Http Get
*
* @param uri
* @return
*/
......@@ -17,6 +18,7 @@ public interface IHttpService {
/**
* Http Get
*
* @param uri
* @param parameters
* @return
......@@ -25,6 +27,7 @@ public interface IHttpService {
/**
* Http Get
*
* @param uri
* @param headers
* @param parameters
......@@ -34,6 +37,7 @@ public interface IHttpService {
/**
* Http Post
*
* @param uri
* @return
*/
......@@ -41,6 +45,7 @@ public interface IHttpService {
/**
* Http Post
*
* @param uri
* @param parameters
* @return
......@@ -49,6 +54,7 @@ public interface IHttpService {
/**
* Http Post
*
* @param uri
* @param headers
* @param parameters
......
......@@ -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 {
/**
* 推送授权开始的状态
*
* @param userId
* @param account
* @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;
import cn.quantgroup.xyqb.entity.UserJr58;
import cn.quantgroup.xyqb.model.IdCardInfo;
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.Jr58RegisterParam;
import cn.quantgroup.xyqb.model.jr58.Jr58RegisterResult;
......@@ -18,15 +17,12 @@ import cn.quantgroup.xyqb.service.http.IHttpService;
import cn.quantgroup.xyqb.service.jr58.Jr58Service;
import cn.quantgroup.xyqb.service.user.ILkbUserService;
import cn.quantgroup.xyqb.util.GZipUtil;
import cn.quantgroup.xyqb.util.PasswordUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
......@@ -116,7 +112,7 @@ public class Jr58ServiceImpl implements Jr58Service {
}
@Override
public void getRidOfFillingProfile(User user,String phoneNo) throws UnsupportedEncodingException {
public void getRidOfFillingProfile(User user, String phoneNo) throws UnsupportedEncodingException {
if (user == null) {
LOGGER.info("58用户不存在");
return;
......@@ -211,7 +207,6 @@ public class Jr58ServiceImpl implements Jr58Service {
}
/**
* 推送授权数据
*/
......@@ -221,39 +216,39 @@ public class Jr58ServiceImpl implements Jr58Service {
Map<String, String> parameters = null;
String url = "";
//量化派数据
if("0".equals(authorizationData.getSourceFrom())){
if ("0".equals(authorizationData.getSourceFrom())) {
parameters = ImmutableMap.<String, String>builder()
.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
.put("loginName", authorizationData.getOperator_data().getOriginalData().getPhone())
.put("currentUser", authorizationData.getUserId())
.put("userSource", "YUNYINGSHANG")
.build();
url= pushImportForJr58Url + "/SpiderServer/api/dataTransfer/saveUserAuthInfo.json";
}else if("1".equals(authorizationData.getSourceFrom())){
url = pushImportForJr58Url + "/SpiderServer/api/dataTransfer/saveUserAuthInfo.json";
} else if ("1".equals(authorizationData.getSourceFrom())) {
//读秒数据
//String graspingJson = Constants.GSON.toJson(authorizationData.getOperator_data());
String graspingJson = JSONObject.toJSONString(authorizationData.getOperator_data());
byte[] graspingJsonBytes = GZipUtil.compressToByte(graspingJson);
String authorizationDataStr = Base64.getEncoder().encodeToString(graspingJsonBytes);
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("currentUser", authorizationData.getUserId())
.put("source", "58")
.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 {
String response = httpService.post(url, parameters);
if(response.contains(",\"status\":1,")){
if (response.contains(",\"status\":1,")) {
LOGGER.info("运营商授权数据推送到lkb成功");
break;
}else{
} else {
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);
}
}
......@@ -269,21 +264,21 @@ public class Jr58ServiceImpl implements Jr58Service {
Map<String, String> parameters = ImmutableMap.<String, String>builder()
.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
.put("loginName", account)
.put("currentUser",userId)
.put("currentUser", userId)
.put("userSource", "YUNYINGSHANG")
.build();
String url = pushImportForJr58Url + "/SpiderServer/api/dataTransfer/saveUserAuthInfo.json";
for (int i = 0; i <4 ; i++) {
for (int i = 0; i < 4; i++) {
try {
String response = httpService.post(url, parameters);
if(response.contains(",\"status\":1,")){
if (response.contains(",\"status\":1,")) {
LOGGER.info("通知lkb授权成功");
break;
}else{
} else {
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);
}
}
......
......@@ -9,6 +9,7 @@ public interface IModelService {
/**
* 验证用户是否在黑名单里
*
* @param phoneNo
* @return
*/
......
package cn.quantgroup.xyqb.service.model.impl;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.model.model.BlacklistMatchResult;
import cn.quantgroup.xyqb.service.http.IHttpService;
import cn.quantgroup.xyqb.service.model.IModelService;
......@@ -17,17 +16,14 @@ import org.springframework.stereotype.Service;
@Service
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}")
private String modelUrlPrefix;
@Autowired
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
public BlacklistMatchResult getBlacklistMatchResult(String phoneNo) {
if (StringUtils.isEmpty(phoneNo)) {
......
package cn.quantgroup.xyqb.service.page.bean;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.Tuple;
/**
* Created by Miraculous on 2017/1/3.
......
......@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.service.page.impl;
import cn.quantgroup.xyqb.entity.*;
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.bean.PageType;
import cn.quantgroup.xyqb.service.user.IAddressService;
......@@ -24,6 +23,8 @@ import java.util.Map;
public class PageServiceImpl implements IPageService {
private Map<String, PageType[]> routerDefinetion;
@Autowired
private IUserDetailService userDetailService;
private PageType pageIdNo = new PageType("name", false) {
@Override
public boolean canPass(User user) {
......@@ -31,6 +32,8 @@ public class PageServiceImpl implements IPageService {
return userDetail != null;
}
};
@Autowired
private IUserExtInfoService userExtInfoService;
private PageType pageUserFinance = new PageType("info", false) {
@Override
public boolean canPass(User user) {
......@@ -38,6 +41,8 @@ public class PageServiceImpl implements IPageService {
return null != extInfo;
}
};
@Autowired
private IAddressService addressService;
private PageType pageAddress = new PageType("address", false) {
@Override
public boolean canPass(User user) {
......@@ -45,6 +50,8 @@ public class PageServiceImpl implements IPageService {
return null != address;
}
};
@Autowired
private IContactService contactService;
private PageType pageContacts = new PageType("contacts", false) {
@Override
public boolean canPass(User user) {
......@@ -52,41 +59,33 @@ public class PageServiceImpl implements IPageService {
return contacts != null && contacts.size() != 0;
}
};
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IUserExtInfoService userExtInfoService;
@Autowired
private IAddressService addressService;
@Autowired
private IContactService contactService;
@PostConstruct
private void init() {
routerDefinetion = new HashMap<>();
routerDefinetion.put("cashTarget1", new PageType[] {
routerDefinetion.put("cashTarget1", new PageType[]{
pageIdNo, pageUserFinance
});
routerDefinetion.put("cashTarget2", new PageType[] {
routerDefinetion.put("cashTarget2", new PageType[]{
pageIdNo, pageAddress
});
routerDefinetion.put("cashTarget3", new PageType[] {
routerDefinetion.put("cashTarget3", new PageType[]{
pageIdNo, pageContacts
});
routerDefinetion.put("cashTarget4", new PageType[] {
routerDefinetion.put("cashTarget4", new PageType[]{
pageIdNo
});
routerDefinetion.put("cashTarget5", new PageType[] {
routerDefinetion.put("cashTarget5", new PageType[]{
});
}
@Override
public Tuple<String, Boolean> nextPage(User user, String target, String currentPage) {
if (user == null ) {
if (user == null) {
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) {
return new Tuple<>("", false);
}
......
......@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.service.session;
import cn.quantgroup.xyqb.entity.Merchant;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.function.OneArgFunction;
import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.model.LoginProperties;
import cn.quantgroup.xyqb.model.session.SessionStruct;
......@@ -21,8 +20,12 @@ public interface ISessionService {
String findSessionIdByUserIdLoginProperties(Long userId, LoginProperties properties);
String findSessionValueBySessionId(String sessionId);
SessionStruct newSession(User user, LoginProperties properties);
void persistSession(String token, SessionValue sessionValue);
SessionStruct findSessionBySessionId(String sessionId);
void deleteByUserId(long userId);
}
......@@ -3,34 +3,34 @@ package cn.quantgroup.xyqb.service.session.impl;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.entity.Merchant;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.function.OneArgFunction;
import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.LoginProperties;
import cn.quantgroup.xyqb.model.session.SessionStruct;
import cn.quantgroup.xyqb.model.session.SessionValue;
import cn.quantgroup.xyqb.service.session.ISessionService;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
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.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
*
* Created by 11 on 2016/12/28.
*/
@Slf4j
@Service
public class SessionServiceImpl implements ISessionService{
public class SessionServiceImpl implements ISessionService {
@Autowired
@Qualifier("stringRedisTemplate")
......@@ -47,7 +47,7 @@ public class SessionServiceImpl implements ISessionService{
//找到用户
String sessionId = findSessionIdByUserIdLoginProperties(user.getId(), properties);
// String sessionId = sessionService.findSessionIdByUserIdAndMerchant(user.getId(), merchant);
if(org.apache.commons.lang.StringUtils.isNotEmpty(sessionId)) {
if (org.apache.commons.lang.StringUtils.isNotEmpty(sessionId)) {
SessionStruct sessionStruct = findSessionBySessionId(sessionId);
sessionStruct.setAttribute("channelId", String.valueOf(channelId));
sessionStruct.setAttribute("createdFrom", String.valueOf(createdFrom));
......@@ -99,13 +99,13 @@ public class SessionServiceImpl implements ISessionService{
}
@Override
public String findSessionValueBySessionId(String sessionId){
public String findSessionValueBySessionId(String sessionId) {
String result = stringRedisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + sessionId);
return StringUtils.defaultString(result, "");
}
@Override
public SessionStruct newSession(User user, LoginProperties loginProperties){
public SessionStruct newSession(User user, LoginProperties loginProperties) {
Timestamp now = new Timestamp(System.currentTimeMillis());
SessionStruct sessionStruct = new SessionStruct();
SessionValue sessionValue = new SessionValue();
......@@ -134,7 +134,7 @@ public class SessionServiceImpl implements ISessionService{
@Override
public SessionStruct findSessionBySessionId(String sessionId) {
String sessionValue = findSessionValueBySessionId(sessionId);
if(StringUtils.isEmpty(sessionValue)) {
if (StringUtils.isEmpty(sessionValue)) {
return null;
}
try {
......@@ -152,5 +152,15 @@ public class SessionServiceImpl implements ISessionService{
}
@Override
public void deleteByUserId(long userId) {
String pattern = Constants.Session.USER_SESSION_ID_CACHE + ":" + String.valueOf(userId) + ":*";
Set<String> keys = stringRedisTemplate.keys(pattern);
if (!CollectionUtils.isEmpty(keys)) {
log.info("删除用户userId={}的缓存信息,个数:{},keys={}", userId,
keys.size(),
Joiner.on(",").join(keys));
}
stringRedisTemplate.delete(keys);
}
}
......@@ -14,6 +14,8 @@ public interface ISmsService {
void sendAfterRegister(String phoneNo);
void sendAfterRegister(String phoneNo,String contentId);
boolean validRegisterOrResetPasswdVerificationCode(String phoneNo, String smsVerificationCode);
boolean validateFastLoginVerificationCode(String phoneNo, String verificationCode);
......
package cn.quantgroup.xyqb.service.sms.impl;
import cn.quantgroup.sms.MsgParams;
import cn.quantgroup.sms.SendAndForgetMsg;
import cn.quantgroup.sms.SmsSender;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.service.sms.ISmsService;
......@@ -27,16 +26,13 @@ public class SmsServiceImpl implements ISmsService {
private static final int SMS_VERIFICATION_MAXLEN = 6;
private static final String SMS_VERIFY_PREFIX = "sms:verify:";
private static final SmsSender smsSender = new SmsSender();
@Value("${sms.is.debug}")
private boolean isDebug;
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate;
private static final SmsSender smsSender = new SmsSender();
@Override
public SmsSender getSmsSender() {
if (null == smsSender) {
......@@ -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 {
}
String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
String randomCode = stringRedisTemplate.opsForValue().get(key);
if(StringUtils.isEmpty(randomCode)){
if (StringUtils.isEmpty(randomCode)) {
return false;
}
String[] arr = randomCode.split(":");
......@@ -81,14 +91,14 @@ public class SmsServiceImpl implements ISmsService {
}
@Override
public boolean validateFastLoginVerificationCode(String phoneNo, String verificationCode){
public boolean validateFastLoginVerificationCode(String phoneNo, String verificationCode) {
String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
String randomCode = stringRedisTemplate.opsForValue().get(key);
if(StringUtils.isBlank(randomCode)){
if (StringUtils.isBlank(randomCode)) {
return false;
}
String[] arr = randomCode.split(":");
if(arr.length != 2){
if (arr.length != 2) {
return false;
}
String uniqueId = arr[0];
......
......@@ -10,5 +10,6 @@ public interface IAddressService {
Address findByUserId(Long userId);
Address save(Address addressObj);
Address saveAddress(Address address);
}
package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.service.user.vo.UserDetailVO;
import org.springframework.dao.DataIntegrityViolationException;
import java.util.List;
......@@ -17,5 +18,5 @@ public interface IUserDetailService {
void updateUserQQ(Long userId, String qq);
List<UserDetail> searchUserDetailList(String name, String phoneNo, String idNo);
List<UserDetailVO> searchUserDetailList(String name, String phoneNo, String idNo);
}
package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WechatUserInfo;
/**
* Created by Miraculous on 15/7/5.
......
......@@ -65,6 +65,7 @@ public class LkbUserviceImpl implements ILkbUserService {
LOGGER.warn("向LKB注册用户失败, phoneNo:{}, password:{}", phoneNo, password);
return "";
}
//String uid = java.util.UUID.randomUUID().toString().replace("-","");
return result.get("uid");
}
......
package cn.quantgroup.xyqb.service.user.impl;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.repository.IUserDetailRepository;
import cn.quantgroup.xyqb.repository.IUserRepository;
import cn.quantgroup.xyqb.service.user.IUserDetailService;
import cn.quantgroup.xyqb.service.user.vo.UserDetailVO;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.persistence.criteria.*;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by 11 on 2016/12/29.
......@@ -21,6 +31,8 @@ public class UserDetailServiceImpl implements IUserDetailService {
@Autowired
private IUserDetailRepository userDetailRepository;
@Autowired
private IUserRepository userRepository;
@Override
public UserDetail findByUserId(Long userId) {
......@@ -43,8 +55,20 @@ public class UserDetailServiceImpl implements IUserDetailService {
}
@Override
public List<UserDetail> searchUserDetailList(String name, String phoneNo, String idNo) {
return userDetailRepository.findAll(getSpecification(name, phoneNo, idNo));
public List<UserDetailVO> searchUserDetailList(String name, String phoneNo, String idNo) {
List<UserDetail> details = userDetailRepository.findAll(getSpecification(name, phoneNo, idNo));
Map<Long, User> userMap = Maps.newHashMap();
if (!CollectionUtils.isEmpty(details)) {
List<Long> userIds = details.stream().map(d -> d.getUserId()).collect(Collectors.toList());
List<User> users = userRepository.findAll((root, query, cb) -> {
query.where(root.get("id").in(userIds));
return query.getRestriction();
});
userMap = users.stream().collect(Collectors.toMap(User::getId, o -> o));
}
Map<Long, User> finalUserMap = userMap;
List<UserDetailVO> userDetailVOS = details.stream().map(o -> fromUserDetailAndUserMap(o, finalUserMap)).collect(Collectors.toList());
return userDetailVOS;
}
private Specification<UserDetail> getSpecification(String name, String phoneNo, String idNo) {
......@@ -67,4 +91,13 @@ public class UserDetailServiceImpl implements IUserDetailService {
};
return specification;
}
private UserDetailVO fromUserDetailAndUserMap(UserDetail userDetail, Map<Long, User> userMap) {
UserDetailVO userDetailVO = UserDetailVO.fromUserDetail(userDetail);
User user = userMap.get(userDetail.getUserId());
if (user != null) {
userDetailVO.setEnable(user.getEnable());
}
return userDetailVO;
}
}
......@@ -47,6 +47,7 @@ public class UserServiceImpl implements IUserService {
}
@Override
@CacheEvict(value = "usercache", key = "'xyqbuser' + #user.phoneNo", cacheManager = "cacheManager")
public User saveUser(User user) {
return userRepository.save(user);
}
......@@ -101,7 +102,7 @@ public class UserServiceImpl implements IUserService {
user.setUuid(uuid);
user.setPassword(PasswordUtil.MD5(password.toLowerCase() + Constants.PASSWORD_SALT));
//解决线上白条registerFrom为1的问题
if(channelId == 222L) {
if (channelId == 222L) {
user.setRegisteredFrom(channelId);
} else {
user.setRegisteredFrom(registerFrom);
......@@ -120,10 +121,11 @@ public class UserServiceImpl implements IUserService {
/**
* 修改用户密码
* @date 2017-02-15 修改用户修改密码时,更新updatedAt时间
*
* @param phoneNo
* @param password
* @return
* @date 2017-02-15 修改用户修改密码时,更新updatedAt时间
*/
@Override
@CacheEvict(value = "usercache", key = "'xyqbuser' + #phone", cacheManager = "cacheManager")
......
......@@ -21,5 +21,4 @@ public class UuidPhoneMappingServiceImpl implements IUuidPhoneMappingService {
}
}
package cn.quantgroup.xyqb.service.user.vo;
import cn.quantgroup.motan.retbean.XUserDetail;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.model.Gender;
import cn.quantgroup.xyqb.model.IdType;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.sql.Timestamp;
@Data
@NoArgsConstructor
public class UserDetailVO {
private Long id;
private Long userId;
private String phoneNo;
private String name;
private String idNo;
private IdType idType;
private Boolean isAuthenticated = false;
private Gender gender;
private String email;
private String qq;
private Boolean enable;
private Long createdAt;
private Long updatedAt;
public static UserDetailVO fromUserDetail(UserDetail userDetail) {
UserDetailVO userDetailVO = new UserDetailVO();
userDetailVO.id = userDetail.getId();
userDetailVO.userId = userDetail.getUserId();
userDetailVO.phoneNo = userDetail.getPhoneNo();
userDetailVO.name = userDetail.getName();
userDetailVO.idNo = userDetail.getIdNo();
userDetailVO.idType = userDetail.getIdType();
userDetailVO.isAuthenticated = userDetail.getIsAuthenticated();
userDetailVO.gender = userDetail.getGender();
userDetailVO.email = userDetail.getEmail();
userDetailVO.qq = userDetail.getQq();
if (userDetail.getCreatedAt() != null) {
userDetailVO.createdAt = userDetail.getCreatedAt().getTime();
}
if (userDetail.getUpdatedAt() != null) {
userDetailVO.updatedAt = userDetail.getUpdatedAt().getTime();
}
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;
*/
public interface IWechatService {
AccessTokenResponse getToken(String code);
WechatUserInfo getWechatUserInfoFromWechatServer(String token, String openId);
WechatUserInfo findWechatUserInfoFromDb(String openId);
......
......@@ -22,24 +22,20 @@ import java.util.concurrent.TimeUnit;
*/
@Service
public class WechatServiceImpl implements IWechatService {
private static final String WECHAT_TOKEN_KEY_PREFIX = "wechat:token:";
@Autowired
private IHttpService httpService;
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate;
@SafeValue("wechat.appid")
private String appId;
@SafeValue("wechat.secret")
private String secret;
@Autowired
private IWeChatUserRepository weChatUserRepository;
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 static final String WECHAT_TOKEN_KEY_PREFIX = "wechat:token:";
@PostConstruct
private void init() {
......@@ -77,7 +73,7 @@ public class WechatServiceImpl implements IWechatService {
try {
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());
response = JSONObject.parseObject(refreshTokenStr, AccessTokenResponse.class);
if (response == null) {
......@@ -112,7 +108,7 @@ public class WechatServiceImpl implements IWechatService {
@Override
@Transactional
public WechatUserInfo saveWechatUserInfo(WechatUserInfo userInfo) {
if(null == userInfo.getPhoneNo()) {
if (null == userInfo.getPhoneNo()) {
userInfo.setPhoneNo("");
}
return weChatUserRepository.save(userInfo);
......
......@@ -19,14 +19,14 @@ import javax.servlet.http.HttpServletRequest;
public class XyqbSessionContextHolder {
private static final ThreadLocal<SessionStruct> threadSession = new ThreadLocal<>();
public static RedisTemplate<String, String> redisTemplate = null;
private static final Logger LOGGER = LoggerFactory.getLogger(XyqbSessionContextHolder.class);
public static RedisTemplate<String, String> redisTemplate = null;
public static SessionStruct getXSession() {
if (threadSession.get() != null) {
return threadSession.get();
}
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("x-auth-token");
if (token == null || token.length() != 36) {
return null;
......
......@@ -47,13 +47,13 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
this.oldestCaptcha = 0L;
this.setCaptchaStoreMaxSize(maxCaptchaStoreSize);
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();
}
protected AbstractManageableCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) {
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)");
} else {
this.setCaptchaStoreSizeBeforeGarbageCollection(captchaStoreLoadBeforeGarbageCollection);
......@@ -67,8 +67,8 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
public void setCaptchaEngineClass(String theClassName) throws IllegalArgumentException {
try {
Object e = Class.forName(theClassName).newInstance();
if(e instanceof CaptchaEngine) {
this.engine = (CaptchaEngine)e;
if (e instanceof CaptchaEngine) {
this.engine = (CaptchaEngine) e;
} else {
throw new IllegalArgumentException("Class is not instance of CaptchaEngine! " + theClassName);
}
......@@ -94,15 +94,19 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
}
public long getNumberOfGeneratedCaptchas() {
return (long)this.numberOfGeneratedCaptchas;
return (long) this.numberOfGeneratedCaptchas;
}
public void setNumberOfGeneratedCaptchas(int numberOfGeneratedCaptchas) {
this.numberOfGeneratedCaptchas = numberOfGeneratedCaptchas;
}
public long getNumberOfCorrectResponses() {
return (long)this.numberOfCorrectResponse;
return (long) this.numberOfCorrectResponse;
}
public long getNumberOfUncorrectResponses() {
return (long)this.numberOfUncorrectResponse;
return (long) this.numberOfUncorrectResponse;
}
public int getCaptchaStoreSize() {
......@@ -115,7 +119,11 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
}
public long getNumberOfGarbageCollectedCaptcha() {
return (long)this.numberOfGarbageCollectedCaptcha;
return (long) this.numberOfGarbageCollectedCaptcha;
}
public void setNumberOfGarbageCollectedCaptcha(int numberOfGarbageCollectedCaptcha) {
this.numberOfGarbageCollectedCaptcha = numberOfGarbageCollectedCaptcha;
}
public int getCaptchaStoreSizeBeforeGarbageCollection() {
......@@ -123,25 +131,25 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
}
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)");
} else {
this.captchaStoreSizeBeforeGarbageCollection = captchaStoreSizeBeforeGarbageCollection;
}
}
public int getCaptchaStoreMaxSize() {
return this.captchaStoreMaxSize;
}
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)");
} else {
this.captchaStoreMaxSize = size;
}
}
public int getCaptchaStoreMaxSize() {
return this.captchaStoreMaxSize;
}
public void garbageCollectCaptchaStore() {
long now = System.currentTimeMillis();
// id 垃圾回收
......@@ -152,15 +160,15 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
protected void garbageCollectCaptchaStore(Iterator garbageCollectableCaptchaIds) {
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();
if((Long) this.times.get(id) < limit) {
if ((Long) this.times.get(id) < limit) {
// 清理计数器
this.times.remove(id);
// 对于 redis 存储, 使用其自动失效机制, 不手动清理
if(this.store.getClass() != RedisCaptchaStore.class){
if (this.store.getClass() != RedisCaptchaStore.class) {
this.store.removeCaptcha(id);
}
++this.numberOfGarbageCollectedCaptcha;
......@@ -171,8 +179,8 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
private Collection getGarbageCollectableCaptchaIds(long now) {
HashSet garbageCollectableCaptchas = new HashSet();
long limit = now - (long)(1000 * this.getMinGuarantedStorageDelayInSeconds());
if(limit > this.oldestCaptcha) {
long limit = now - (long) (1000 * this.getMinGuarantedStorageDelayInSeconds());
if (limit > this.oldestCaptcha) {
for (Object o : this.times.keySet()) {
String id = (String) o;
long captchaDate = (Long) this.times.get(id);
......@@ -192,11 +200,11 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
}
protected Captcha generateAndStoreCaptcha(Locale locale, String ID) {
if(this.isCaptchaStoreFull()) {
if (this.isCaptchaStoreFull()) {
logger.info("生成图形验证码时检测到, 容量已满, 执行垃圾回收");
long now = System.currentTimeMillis();
Collection garbageCollectableCaptchaIds = this.getGarbageCollectableCaptchaIds(now);
if(garbageCollectableCaptchaIds.size() > 0) {
if (garbageCollectableCaptchaIds.size() > 0) {
this.garbageCollectCaptchaStore(garbageCollectableCaptchaIds.iterator());
return this.generateAndStoreCaptcha(locale, ID);
} else {
......@@ -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");
}
} else {
if(this.isCaptchaStoreQuotaReached()) {
if (this.isCaptchaStoreQuotaReached()) {
logger.info("生成图形验证码时检测到, 容量已达配额, 执行垃圾回收");
this.garbageCollectCaptchaStore();
}
......@@ -231,7 +239,7 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
public Boolean validateResponseForID(String ID, Object response) throws CaptchaServiceException {
Boolean valid = super.validateResponseForID(ID, response);
this.times.remove(ID);
if(valid) {
if (valid) {
++this.numberOfCorrectResponse;
} else {
++this.numberOfUncorrectResponse;
......@@ -240,10 +248,6 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
return valid;
}
public void setNumberOfGeneratedCaptchas(int numberOfGeneratedCaptchas) {
this.numberOfGeneratedCaptchas = numberOfGeneratedCaptchas;
}
public int getNumberOfCorrectResponse() {
return numberOfCorrectResponse;
}
......@@ -260,10 +264,6 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
this.numberOfUncorrectResponse = numberOfUncorrectResponse;
}
public void setNumberOfGarbageCollectedCaptcha(int numberOfGarbageCollectedCaptcha) {
this.numberOfGarbageCollectedCaptcha = numberOfGarbageCollectedCaptcha;
}
public void addNumberOfGarbageCollectedCaptcha(int num) {
this.numberOfGarbageCollectedCaptcha += num;
}
......@@ -272,7 +272,7 @@ public abstract class AbstractManageableCaptchaService extends AbstractCaptchaSe
this.numberOfUncorrectResponse += num;
}
public void addNumberOfCorrectResponse(int num){
public void addNumberOfCorrectResponse(int num) {
this.numberOfCorrectResponse += num;
}
......
......@@ -26,15 +26,15 @@ public abstract class AbstractManageableImageCaptchaService extends AbstractMana
}
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 {
return (BufferedImage)this.getChallengeForID(ID, locale);
return (BufferedImage) this.getChallengeForID(ID, locale);
}
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());
clone.getGraphics().drawImage(challenge, 0, 0, clone.getWidth(), clone.getHeight(), null);
clone.getGraphics().dispose();
......
......@@ -13,15 +13,24 @@ import org.springframework.stereotype.Component;
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
/**
* Spring应用上下文环境
*/
private static ApplicationContext applicationContext;
@Autowired
public ApplicationContextHolder(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* Spring应用上下文环境
* 获取一个ApplicationContext.
*
* @return ApplicationContext
*/
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境.
......@@ -32,15 +41,6 @@ public class ApplicationContextHolder implements ApplicationContextAware {
ApplicationContextHolder.applicationContext = applicationContext;
}
/**
* 获取一个ApplicationContext.
*
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 根据名称获取一个对象.
*
......
......@@ -13,16 +13,9 @@ public class GZipUtil {
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) {
if (str == null || str.length() == 0) {
return null;
......@@ -42,7 +35,9 @@ public class GZipUtil {
}
/** 字符串压缩为字节数组 */
/**
* 字符串压缩为字节数组
*/
public static byte[] compressToByte(String str, String encoding) {
if (str == null || str.length() == 0) {
return null;
......@@ -64,7 +59,9 @@ public class GZipUtil {
}
/** 字节数组解压缩后返回字符串 */
/**
* 字节数组解压缩后返回字符串
*/
public static String uncompressToString(byte[] b) {
if (b == null || b.length == 0) {
return null;
......@@ -90,7 +87,9 @@ public class GZipUtil {
}
/** 字节数组解压缩后返回字符串 */
/**
* 字节数组解压缩后返回字符串
*/
public static String uncompressToString(byte[] b, String encoding) {
if (b == null || b.length == 0) {
return null;
......@@ -116,4 +115,15 @@ public class GZipUtil {
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;
public class JR58GzipUtil {
public static String bytesTogzip(byte[] bytes, String encode) {
if(bytes==null || bytes.length==0){
if (bytes == null || bytes.length == 0) {
return null;
}
ByteArrayInputStream byteArrayIn=null;
ByteArrayInputStream byteArrayIn = null;
GZIPInputStream in = null;
ByteArrayOutputStream byteArrayout = new ByteArrayOutputStream();
PrintStream out= new PrintStream(byteArrayout);
PrintStream out = new PrintStream(byteArrayout);
try {
byteArrayIn= new ByteArrayInputStream(bytes);
byteArrayIn = new ByteArrayInputStream(bytes);
in = new GZIPInputStream(byteArrayIn);
byte[] b = new byte[1024];
int readlen = 0;;
while((readlen=in.read(b))!=-1){
int readlen = 0;
;
while ((readlen = in.read(b)) != -1) {
out.write(b, 0, readlen);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally{
} finally {
try {
byteArrayIn.close();
in.close();
......@@ -41,21 +42,22 @@ public class JR58GzipUtil {
}
}
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) {
if(str==null || str.length()==0){
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = null;
try {
gzip= new GZIPOutputStream(out);
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encode));
} catch (Exception e) {
e.printStackTrace();
}finally{
} finally {
try {
gzip.close();
} catch (IOException e) {
......
package cn.quantgroup.xyqb.util;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
......
server.port=8080
security.sessions=if_required
spring.aop.proxy-target-class=true
......@@ -2,7 +2,7 @@ config.accessable=false
configserver.disable=1
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
......@@ -16,7 +16,7 @@ xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-
xyqb.data.redis.defaultExpiration=3600
# 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.name=
xyqb.redis.sentinel1.host=
......@@ -30,7 +30,7 @@ xyqb.redis.sentinel3.port=0
sms.is.debug=1
# 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.58jr=/new/register/jr58/saveUserInfo.json
lkb.client.user.update=/new/register/updateUser.json
......@@ -43,9 +43,9 @@ lkb.url=http://192.168.192.251:8081/LKB
lkb.entrypoint.jr58=/jr58/arc_all.html
# 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.sign.key=MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKG/Y0J/c+JguU6cPdFHRC9eHrkgaZ9bpYpeQVujBpL+OkA8pAQTZ1XhoLZu/IH4Rv2kx85e8WVF7FxIFkgqJobjvai2XsD7QRYHGb6EEsqjROPndxnlpLeXmyp+WvbPhtRMoLyP3bZncaR1xsPkmW4ajXSUCa4+qlEfrEMskG79AgMBAAECgYAYmA5StSh8unJSxqULpkdy4F/RjGEjDv9by7sqYN6GCUv4KoBR8lVbFKSoOLYCWSsKND0BXyRbXsdyvK9Op8IVsKIbUnpen5V2cgNrVhlomy7E7RFSdoyFcRuWzck0NGtjJLPzi4qztiKprFH8yMf3tfD8aEKMo7pFpqetGfkezQJBANZTUTiGePRsiO7igin92jf9pWeSiI9OecQ/9hxwIlXXxQAwMUcvvyjoKfp6TRs3HlYugoiP/5VwTWRM/iTbf18CQQDBMtpKI5NtgrpfqbN2czP35S7VOnYO0QofEEuLj3oVCo2CxXfz0cViY/ng3BFk/oTykbMmS/TxCD5VHi17QRsjAkEAv9/3ZtN8ldZVAQhn35AUPOwnmIHnH+TxvnBEtVDubEuvYmvCsihcyxKOAmBbh3HhBua8leXUusS/hHwpSnX3oQJAc4eLTYZUpMnl1UrPjGd7jiO4i72310hduxGtezlDEc4LrUWUY3Lvi9SpGjO/GxuwOLWz4ZTOVkxNqeyv2eKm7QJAQHvgO0ciDFuFuhahFli7ktyZcn5CV8PPkQrbMXUFrMbX3AP61HPyH9EGCqBvsdyRYqPxFseDFY3yYveOWMPq0Q==
......@@ -71,3 +71,18 @@ usersys.url=http://localhost:9001
xyqb-user.ui=http://192.168.100.36:7043
wechat.appid=wxcdf6077af8127559
wechat.secret=16eaec16084d0d9c52d4114f359cc72c
#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
server.port=9001
security.sessions=if_required
server.session-timeout=5184000
spring.aop.proxy-target-class=true
......@@ -19,7 +19,7 @@
<logger name="ch.qos.logback" level="warn"/>
<root level="info">
<appender-ref ref="FILE" />
<appender-ref ref="FILE"/>
</root>
</configuration>
\ No newline at end of file
configserver.disable=0
configserver.system=xyqb-user
xyqb.data.mysql.max-pool-size=1000
# CORS
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.data.redis.defaultExpiration=3600
# redis
xyqb.redis.master.host=172.16.1.179
xyqb.redis.master.port=6373
......@@ -19,34 +15,38 @@ xyqb.redis.sentinel2.host=172.16.1.180
xyqb.redis.sentinel2.port=26373
xyqb.redis.sentinel3.host=172.16.1.181
xyqb.redis.sentinel3.port=26373
# 短信平台配置
sms.is.debug=0
# LKB client
lkb.client.url=http://openapi.quantgroup.cn/LKBClient/openapi
lkb.client.user.register.app=/new/register/registerApp.json
lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json
lkb.client.user.update=/new/register/updateUser.json
# LKB import
lkb.import.url=http://spider.quantgroup.cn
# LKB
lkb.url=http://58.xyqb.com/LKB
lkb.entrypoint.jr58=/jr58/arc_all.html
# xyqb
xyqb.url=http://m.xyqb.com
xyqb.api.url=http://api.xyqb.com
# JR58
jr58.notify.userinfo=http://dk.58.com/customer/quantgroup_user_info
#sdk
model.quantgroup.url=http://model.quantgroup.cn
xyqb.auth.url=http://auth.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
security.sessions=if_required
spring.aop.proxy-target-class=true
......@@ -19,7 +19,7 @@
<logger name="ch.qos.logback" level="warn"/>
<root level="info">
<appender-ref ref="FILE" />
<appender-ref ref="FILE"/>
</root>
</configuration>
\ No newline at end of file
configserver.disable=1
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.password=qatest
xyqb.data.mysql.user=qa
xyqb.data.mysql.max-pool-size=20
# CORS
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.data.redis.defaultExpiration=3600
# redis
xyqb.redis.master.host=192.168.4.103
xyqb.redis.master.port=6379
......@@ -24,49 +18,37 @@ xyqb.redis.sentinel2.host=
xyqb.redis.sentinel2.port=0
xyqb.redis.sentinel3.host=
xyqb.redis.sentinel3.port=0
# 短信平台配置
sms.is.debug=1
# LKB client
lkb.client.url=http://192.168.192.251:8082/LKBClient/openapi
lkb.client.user.register.app=/new/register/registerApp.json
lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json
lkb.client.user.update=/new/register/updateUser.json
# LKB import
lkb.import.url=http://spider.quantgroup.cn
# LKB
lkb.url=http://192.168.192.251:8081/LKB
lkb.entrypoint.jr58=/jr58/arc_all.html
# xyqb
xyqb.url=http://192.168.192.206:8999
xyqb.api.url=http://192.168.192.206:9004
# JR58
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
# 图形验证码
# 是否启用超级验证码 "__SUPERQG__", 用于测试环境自动化测试, 线上环境可忽略此参数
xyqb.auth.captcha.super.enable=1
#首参数校验
xyqb.fplock.limit.byhour=3
xyqb.fplock.limit.byday=5
#sdk
model.quantgroup.url=http://model.quantgroup.cn
xyqb.auth.url=http://192.168.192.206:9001
usersys.url=http://localhost:9001
xyqb-user.ui=http://192.168.12.40:8080
wechat.appid=wxcdf6077af8127559
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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.validation.constraints.AssertTrue;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Bootstrap.class)
......
......@@ -24,7 +24,7 @@ public class TestUserLogin {
private UserController userController;
@Test
public void testUserLogin(){
public void testUserLogin() {
//访问xyqb-user拿到登录token
/*Long channelId = 1L;
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