Commit c51585b8 authored by Java—KA—李 青's avatar Java—KA—李 青

处理冲突

parents 78c4ea32 56e358c2
......@@ -92,14 +92,6 @@ public interface Constants {
String AVATAR_DEFAULT = "https://avatar.xyqb.com/default_avatar.png";
}
interface Sms {
String VERIFICATION_CODE = "尊敬的用户,您本次的验证码为:%s,有效期10分钟。"; // 随机验证码
String BINDCARD_SMS = "用户您好,您已绑卡成功,将会在1-5个工作日内收到借款,请耐心等待。如有疑问,请致电400-002-0061,感谢您对我们的支持";//绑卡成功后的短信文案
String REPAY_SMS = "用户您好,您在信用钱包的本期账单已还款成功,保持良好的信用可升级为VIP用户,享更多特权,感谢您对信用钱包的支持";
}
String AES_KEY = "ScnmRBhuQpo9kBdn";
}
package cn.quantgroup.xyqb.aspect.accessable;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.util.IPUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
......@@ -19,7 +17,7 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.dsig.keyinfo.PGPData;
import java.util.Objects;
/**
* IP白名单检验
......@@ -36,12 +34,18 @@ public class IpValidateAdvisor {
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate;
@Pointcut("@annotation(cn.quantgroup.xyqb.aspect.accessable.IpValidator)")
private void needIpValidate() {
@Value("${configserver.disable}")
private Integer isDebug;
@Pointcut("execution(public * cn.quantgroup.xyqb.controller.external.user.InnerController.*(..))")
private void whiteIpMatch() {
}
@Around("needIpValidate()")
private Object doCapchaValidate(ProceedingJoinPoint pjp) throws Throwable {
@Around("whiteIpMatch()")
private Object doWhiteIpMatch(ProceedingJoinPoint pjp) throws Throwable {
if(Objects.equals(isDebug, 0)){
return pjp.proceed();
}
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
// 客户端IP
String clientIp = IPUtil.getRemoteIP(request);
......@@ -49,12 +53,8 @@ public class IpValidateAdvisor {
if(IPUtil.whiteOf(clientIp)){
return pjp.proceed();
}
// 补充白名单
if(redisTemplate.opsForSet().isMember(Constants.IPV4_LOCK_WHITE, clientIp)){
return pjp.proceed();
}
IPUtil.logIp(LOGGER, request);
LOGGER.error("白名单不匹配拦截:ip={}", clientIp);
LOGGER.error("Lock_ipv4: don't match white ip access:{}", clientIp);
return JsonResult.buildErrorStateResult("非法访问", null);
}
}
package cn.quantgroup.xyqb.aspect.accessable;
import java.lang.annotation.*;
/**
* Ip白名单检验标记
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IpValidator {
}
......@@ -171,16 +171,15 @@ public class CaptchaFiniteValidateAdvisor {
LOGGER.info("参数无效, credential:{}", credential);
return null;
}
// 当前用户手机号
// 当前用户手机号和密码
String phoneNo = credentialArr[0];
// 当前请求的SingleToken
String password = credentialArr[1];
headerParamValid = headerParamValid && ValidationUtil.validatePhoneNo(phoneNo) && StringUtils.isNotBlank(password);
if (!headerParamValid) {
LOGGER.info("参数无效, credential:{}, phoneNo:{}, password:{}", credential, phoneNo, password);
return null;
}
LOGGER.info("账密登录, phoneNo:{}, password:{}", phoneNo, password);
LOGGER.info("账密登录, phoneNo:{}", phoneNo);
Map<String, String> phonePasswordMap = new HashMap<String, String>(2);
phonePasswordMap.put("phoneNo", phoneNo);
phonePasswordMap.put("password", password);
......
package cn.quantgroup.xyqb.aspect.captcha;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.thirdparty.jcaptcha.AbstractManageableImageCaptchaService;
import cn.quantgroup.xyqb.util.IPUtil;
import com.octo.captcha.service.CaptchaServiceException;
import java.io.PipedReader;
import java.nio.charset.Charset;
import java.security.PrivateKey;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
......@@ -35,7 +32,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
* 类描述:
*
* @author 李宁
* @version 1.0.0 创建时间:15/11/17 14:49 修改人: 修改时间:15/11/17 14:49 修改备注:
* @version 1.0.0 创建时间:15/11/17 14:49
*/
@Aspect
@Component
......@@ -59,6 +56,11 @@ public class CaptchaNewValidateAdvisor {
@Value("${xyqb.auth.captcha.autotest.enable:false}")
private boolean autoTestCaptchaEnabled;
private static final String IMAGE_IP_COUNT = "image:ip";
private static final String IMAGE_PHONE_COUNT = "image:phone";
private static final String IMAGE_DEVICEID_COUNT = "image:deviceId:";
private static final Long FIVE_MIN = 24 * 5L;
/**
* 图形验证码切面
*/
......@@ -66,11 +68,6 @@ public class CaptchaNewValidateAdvisor {
private void needNewCaptchaValidate() {
}
private static final String IMAGE_IP_COUNT = "image:ip";
private static final String IMAGE_PHONE_COUNT = "image:phone";
private static final String IMAGE_DEVICEID_COUNT = "image:deviceId:";
private static final Long FIVE_MIN = 24 * 5L;
/**
* 在受图形验证码保护的接口方法执行前, 执行图形验证码校验
* captchaId 图形验证码key
......@@ -80,7 +77,6 @@ public class CaptchaNewValidateAdvisor {
*/
@Around("needNewCaptchaValidate()")
private Object doCapchaValidate(ProceedingJoinPoint pjp) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String registerFrom = Optional.ofNullable(request.getParameter("registerFrom")).orElse("");
String captchaId = Optional.ofNullable(request.getParameter("captchaId")).orElse("");
......@@ -88,9 +84,9 @@ public class CaptchaNewValidateAdvisor {
String phoneNo = request.getParameter("phoneNo");
String deviceId = Optional.ofNullable(request.getParameter("deviceId")).orElse("");
String clientIp = IPUtil.getRemoteIP(request);
Long countIP = countIP(clientIp);
Long countIP = countByClientId(clientIp, false);
Long countPhone = countPhone(phoneNo);
Long countDeviceId = countDeviceId(deviceId);
Long countDeviceId = countByClientId(deviceId, true);
IPUtil.logIp(LOGGER, request);
LOGGER.info("使用图形验证码, registerFrom={}, clientIp={},手机号次数:{},设备次数:{},ip次数:{},phone:{}", registerFrom, clientIp,countPhone,countDeviceId,countIP,phoneNo);
//if (countIP > Constants.Image_Need_Count || countPhone > Constants.Image_Need_Count || countDeviceId > Constants.Image_Need_Count) {
......@@ -99,7 +95,6 @@ public class CaptchaNewValidateAdvisor {
LOGGER.info("使用超级图形验证码校验, registerFrom={}, clientIp={}", registerFrom, clientIp);
return pjp.proceed();
}
JsonResult result = JsonResult.buildSuccessResult("图形验证码不正确", "");
result.setBusinessCode("0002");
if (StringUtils.isNotBlank(captchaValue)) {
......@@ -132,24 +127,6 @@ public class CaptchaNewValidateAdvisor {
return StringUtils.equals(SUPER_CAPTCHA_ID, String.valueOf(captchaId)) && StringUtils.equals(SUPER_CAPTCHA, String.valueOf(captchaValue));
}
private Long countIP(String clientIp) {
Long count = 1L;
if (StringUtils.isBlank(clientIp)) {
return count;
} else {
String countString = redisTemplate.opsForValue().get(IMAGE_IP_COUNT + clientIp);
if (StringUtils.isBlank(countString)) {
redisTemplate.opsForValue().set(IMAGE_IP_COUNT + clientIp, String.valueOf(count),
FIVE_MIN, TimeUnit.SECONDS);
} else {
count = Long.valueOf(countString) + 1L;
redisTemplate.opsForValue().set(IMAGE_IP_COUNT + clientIp, String.valueOf(count),
FIVE_MIN, TimeUnit.SECONDS);
}
return count;
}
}
private Long countPhone(String phoneNo) {
Long count = 1L;
String countString = redisTemplate.opsForValue().get(IMAGE_PHONE_COUNT + phoneNo);
......@@ -165,28 +142,26 @@ public class CaptchaNewValidateAdvisor {
}
/**
* 短信发送设备限制
* 短信发送限制
* @param clientId - 设备ID或IP
* @param device - true - 设备,false - IP
* @return
*/
private Long countDeviceId(String deviceId) {
private Long countByClientId(String clientId, boolean device) {
Long count = 1L;
if (StringUtils.isBlank(deviceId)) {
if (StringUtils.isBlank(clientId)) {
return count;
} else {
String countString = redisTemplate.opsForValue().get(IMAGE_DEVICEID_COUNT + deviceId);
String key = (device ? IMAGE_DEVICEID_COUNT : IMAGE_IP_COUNT) + clientId;
String countString = redisTemplate.opsForValue().get(key);
if (StringUtils.isBlank(countString)) {
redisTemplate.opsForValue().set(IMAGE_DEVICEID_COUNT + deviceId, String.valueOf(count),
FIVE_MIN, TimeUnit.SECONDS);
redisTemplate.opsForValue().set(key, String.valueOf(count), FIVE_MIN, TimeUnit.SECONDS);
} else {
count = Long.valueOf(countString) + 1L;
redisTemplate.opsForValue().set(IMAGE_DEVICEID_COUNT + deviceId, String.valueOf(count),
FIVE_MIN, TimeUnit.SECONDS);
redisTemplate.opsForValue().set(key, String.valueOf(count), FIVE_MIN, TimeUnit.SECONDS);
}
return count;
}
}
private HttpServletRequest getRequest() {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attrs.getRequest();
}
}
......@@ -53,10 +53,6 @@ public class PasswordErrorFiniteValidateAdvisor {
*/
@Around("passwordErrorFiniteValidate()")
private Object doFiniteValidate(ProceedingJoinPoint pjp) throws Throwable {
// Todo -- 全天候开放监控
/*if(!ValidationUtil.isAtDangerousTime()){
return pjp.proceed();
}*/
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 客户端IP
String clientIp = IPUtil.getRemoteIP(request);
......@@ -75,7 +71,7 @@ public class PasswordErrorFiniteValidateAdvisor {
// 黑名单
if(redisTemplate.opsForSet().isMember(Constants.IPV4_LOCK_BLACK, clientIp)){
IPUtil.logIp(LOGGER, request);
LOGGER.info("Lock_ipv4: locked ip access:{}", clientIp);
LOGGER.info("Lock_ipv4: black ip access:{}", clientIp);
return JsonResult.buildErrorStateResult("登录失败", null);
}
String lockIpv4Key = getLockIpv4Key(clientIp);
......
......@@ -6,7 +6,6 @@ import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
......@@ -17,6 +16,7 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* 调用者记录
......@@ -31,26 +31,32 @@ public class LogCallHttpAspect {
@Pointcut("@annotation(cn.quantgroup.xyqb.aspect.logcaller.LogHttpCaller)")
private void logHttpCaller() {
}
@Around("logHttpCaller()")
public Object record(ProceedingJoinPoint pjp) throws Throwable {
Object result = pjp.proceed();
// 异步记录调用日志
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if(Objects.nonNull(attrs)){
try {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
HttpServletRequest request = attrs.getRequest();
String remoteIP = IPUtil.getRemoteIP(request);
LogCallHttpAspect logCallHttpAspect = ApplicationContextHolder.getBean(LogCallHttpAspect.class);
// 异步记录日志
logCallHttpAspect.asyncRecordIt(pjp,result,remoteIP);
}catch (Exception e){
LOGGER.error("打印http请求日志出错", e);
}
}
return result;
}
/**
* 异步记录日志
* @param pjp
* @param result
* @param remoteIP
*/
@Async("logExecutor")
public void asyncRecordIt(ProceedingJoinPoint pjp, Object result, String remoteIP){
Object[] args = pjp.getArgs();
......
package cn.quantgroup.xyqb.config.web;
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;
/**
* Created by Miraculous on 15/7/10.
*/
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
@Value("${configserver.disable}")
private Integer isDebug;
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new IPWhiteListInterceptor(isDebug)).addPathPatterns("/innerapi/**");
}
}
package cn.quantgroup.xyqb.controller;
import cn.quantgroup.xyqb.exception.NullUserException;
import cn.quantgroup.xyqb.exception.PasswordErrorLimitException;
import cn.quantgroup.xyqb.exception.UserNotExistException;
import cn.quantgroup.xyqb.exception.VerificationCodeErrorException;
......@@ -25,15 +24,8 @@ public class ExceptionHandlingController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlingController.class);
private static final JsonResult EXCEPTION_RESULT = new JsonResult("internal error", 500L, "");
@ExceptionHandler(NullUserException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public JsonResult nullUserException(NullUserException nue) {
return new JsonResult(nue.getMessage(), 401L, null);
}
/**
* 密码错误次数达到上限异常
*
......@@ -47,7 +39,7 @@ public class ExceptionHandlingController implements IBaseController {
}
/**
* 密码错误次数过多异常,提升验证级别
* 短信验证码错误或失效异常
*
* @param vce
* @return
......@@ -58,6 +50,11 @@ public class ExceptionHandlingController implements IBaseController {
return JsonResult.buildErrorStateResult(vce.getMessage(), null, 1L);
}
/**
* 用户不存在异常
* @param unee
* @return
*/
@ExceptionHandler(UserNotExistException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public JsonResult userNotExistException(UserNotExistException unee) {
......@@ -65,7 +62,11 @@ public class ExceptionHandlingController implements IBaseController {
return new JsonResult(unee.getMessage(), 401L, null);
}
/**
* 其他全局异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
public JsonResult exceptionOccurs(Exception e) {
HttpServletRequest request = getRequest();
......
......@@ -107,7 +107,7 @@ public class LockIpv4Controller implements IBaseController {
minutes = Integer.valueOf(redisMinutes);
}
redisTemplate.opsForValue().set(lockIpv4Key, Boolean.TRUE.toString(), minutes, TimeUnit.MINUTES);
LOGGER.info("Lock_ipv4: locked ip access:{}, error overstep {} times in {} minutes, do lock {} minutes", ip, counts, Constants.IPV4_FAILED_COUNT_MINUTES, minutes);
LOGGER.info("Lock_ipv4: locked ip Success. ip:{}, error overstep {} times in {} minutes, do lock {} minutes", ip, counts, Constants.IPV4_FAILED_COUNT_MINUTES, minutes);
}else{
redisTemplate.delete(lockIpv4Key);
LOGGER.info("Lock_ipv4: unlocked ip Success. ip:{}", ip);
......
......@@ -3,13 +3,11 @@ package cn.quantgroup.xyqb.controller.external.user;
import cn.quantgroup.user.enums.Relation;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.aspect.accessable.IpValidator;
import cn.quantgroup.xyqb.aspect.logcaller.LogHttpCaller;
import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.entity.enumerate.*;
import cn.quantgroup.xyqb.model.*;
import cn.quantgroup.xyqb.repository.IUserDetailRepository;
import cn.quantgroup.xyqb.service.api.IUserApiService;
import cn.quantgroup.xyqb.service.auth.IIdCardService;
import cn.quantgroup.xyqb.service.http.IHttpService;
......@@ -41,7 +39,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.ParseException;
......@@ -527,7 +524,6 @@ public class InnerController implements IBaseController {
return JsonResult.buildSuccessResult(null, UserExtInfoRet.getUserExtInfoRet(info));
}
@IpValidator
@LogHttpCaller
@RequestMapping("/user_detail/search_list")
public JsonResult searchUserDetailList(String name, String phoneNo, String idNo) {
......@@ -581,7 +577,6 @@ public class InnerController implements IBaseController {
return JsonResult.buildSuccessResult("success", wechatUserInfo.getOpenId());
}
@IpValidator
@LogHttpCaller
@RequestMapping("/user-association/search/phone")
public JsonResult findUserAssociationByPhone(String phoneNo) {
......
......@@ -349,7 +349,8 @@ public class SmsController implements IBaseController {
try {
smsService.getSmsSender().sendMsg(message);
redisTemplate.opsForValue().set(key, uniqueId + ":" + randomCode, EXPIRE_MINUTES, TimeUnit.MINUTES);
deleteRetSendCode(phoneNo);//删除用户重置密码,多次错误逻辑
//删除用户重置密码,多次错误逻辑
deleteRetSendCode(phoneNo);
if(needImageVlidate(clientIp,deviceId,phoneNo)){
return JsonResult.buildSuccessResult("发送成功", uniqueId,0003L);
......
......@@ -9,7 +9,6 @@ import cn.quantgroup.xyqb.entity.Merchant;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.entity.WechatUserInfo;
import cn.quantgroup.xyqb.exception.PasswordErrorLimitException;
import cn.quantgroup.xyqb.exception.UserNotExistException;
import cn.quantgroup.xyqb.exception.VerificationCodeErrorException;
import cn.quantgroup.xyqb.model.JsonResult;
......@@ -23,7 +22,10 @@ import cn.quantgroup.xyqb.service.user.ILockIpv4Service;
import cn.quantgroup.xyqb.service.user.IUserDetailService;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.service.wechat.IWechatService;
import cn.quantgroup.xyqb.util.*;
import cn.quantgroup.xyqb.util.IPUtil;
import cn.quantgroup.xyqb.util.MqUtils;
import cn.quantgroup.xyqb.util.PasswordUtil;
import cn.quantgroup.xyqb.util.ValidationUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
......@@ -38,11 +40,8 @@ import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* Http服务接口:用户注册、登录、重置密码
......@@ -84,10 +83,7 @@ public class UserController implements IBaseController {
@RequestMapping("/test")
public JsonResult test() {
HttpServletRequest request = getRequest();
String remoteAddr = request.getRemoteAddr();
String xRealIp = IPUtil.getRemoteIP(request);
String xOriginalClientIp = request.getHeader("x-original-client-ip");
LOGGER.info("Test ips:[client={}, old={}, new={}]", remoteAddr, xRealIp, xOriginalClientIp);
IPUtil.logIp(LOGGER, request);
return JsonResult.buildSuccessResult("", getCurrentUserFromRedis());
}
......@@ -154,7 +150,7 @@ public class UserController implements IBaseController {
@RequestParam(required = false,defaultValue = "xyqb") String key,
HttpServletRequest request, String openId,
@RequestParam(required = false) String dimension) {
LOGGER.info("user/login,请求参数channelId:{},appChannel:{},createdFrom:{},userId:{},key:{},openId:{},dimension:{},",channelId,appChannel,createdFrom,userId,key,openId,dimension);
LOGGER.info("login -> channelId:{},appChannel:{},createdFrom:{},userId:{},key:{},openId:{},dimension:{}",channelId,appChannel,createdFrom,userId,key,openId,dimension);
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
return JsonResult.buildErrorStateResult("未知的连接", null);
......@@ -175,7 +171,7 @@ public class UserController implements IBaseController {
@RequestParam(required = false)Long btRegisterChannelId,
@RequestParam(required = false) String dimension ,HttpServletRequest request) {
Map<String, JsonResult> validMap = getHeaderParam(request);
LOGGER.info("user/login/fast,请求参数channelId:{},appChannel:{},createdFrom:{},btRegisterChannelId:{},key:{},dimension:{},",channelId,appChannel,createdFrom,btRegisterChannelId,key,dimension);
LOGGER.info("login/fast -> channelId:{},appChannel:{},createdFrom:{},btRegisterChannelId:{},key:{},dimension:{}",channelId,appChannel,createdFrom,btRegisterChannelId,key,dimension);
if (null != validMap.get("fail")) {
return validMap.get("fail");
}
......@@ -211,21 +207,6 @@ public class UserController implements IBaseController {
// return createSession(channelId, createdFrom, appChannel, user);
}
private User registerFastWhenLogin(String phoneNo, Long channelId, Long registerFrom, String appChannel, Long btRegisterChannelId,String dimension) {
String password = PasswordUtil.generateRandomPwd(15);
LOGGER.info("用户快速注册, phoneNo:{}, channelId:{}, registerFrom:{},appChannel:{},btRegisterChannelId", phoneNo, channelId, registerFrom, appChannel,btRegisterChannelId);
if (null == registerFrom) {
registerFrom = 1L;
}
if (channelId == 222L) {
registerFrom=222L;
}
User user=userService.registerAndReturn(phoneNo, password, registerFrom,btRegisterChannelId);
LOGGER.info("用户快速注册成功, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
MqUtils.sendRegisterMessage(channelId,dimension, user);
return user;
}
/**
* 快速登录验证
*
......@@ -277,17 +258,17 @@ public class UserController implements IBaseController {
@RequestParam String verificationCode, @RequestParam(required = false) Long channelId,
@RequestParam(required = false) Long registerFrom,
@RequestParam(required = false)Long btRegisterChannelId,@RequestParam(required = false)String dimension) {
LOGGER.info("[/user/register]用户注册, phoneNo:{}, verificationCode:{}, channelId:{}, registerFrom:{},btRegisterChannelId:{},dimension:{}", phoneNo, verificationCode, channelId, registerFrom,btRegisterChannelId,dimension);
LOGGER.info("用户注册:register -> phoneNo:{}, verificationCode:{}, channelId:{}, registerFrom:{},btRegisterChannelId:{},dimension:{}", phoneNo, verificationCode, channelId, registerFrom,btRegisterChannelId,dimension);
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
LOGGER.info("用户注册失败,手机号错误, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
LOGGER.info("用户注册失败,手机号错误:register -> registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("手机号错误", null);
}
if (StringUtils.isEmpty(password)) {
LOGGER.info("用户注册失败,密码不能为空, registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
LOGGER.info("用户注册失败,密码不能为空:register -> registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
return JsonResult.buildErrorStateResult("密码不能为空", null);
}
if (password.length() < 6 || password.length() > 12) {
LOGGER.info("用户注册失败,密码长度须在6位至12位之间, registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
LOGGER.info("用户注册失败,密码长度须在6位至12位之间:register -> registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
return JsonResult.buildErrorStateResult("密码应为6-12位", null);
}
if (null == registerFrom) {
......@@ -295,7 +276,7 @@ public class UserController implements IBaseController {
}
smsValidForRegister(phoneNo, verificationCode);
if (userService.exist(phoneNo)) {
LOGGER.info("用户注册失败,该手机号已经被注册, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
LOGGER.info("用户注册失败,该手机号已经被注册:register -> registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("该手机号已经被注册", null);
}
// if (!userService.register(phoneNo, password, registerFrom, getIp(), channelId,btRegisterChannelId,dimension)) { TODO
......@@ -303,7 +284,7 @@ public class UserController implements IBaseController {
LOGGER.info("用户快速注册失败,请稍后重试, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("注册失败,请稍后重试", null);
}
LOGGER.info("用户注册成功, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
LOGGER.info("用户注册成功:register -> registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildSuccessResult(null, null);
}
......@@ -439,7 +420,6 @@ public class UserController implements IBaseController {
}
String phoneNo = credentialArr[0];
String pass = credentialArr[1];
LOGGER.info("用户正在登录... [{}]", phoneNo);
User user = userService.findByPhoneWithCache(phoneNo);
if (user == null || !user.getEnable()) {
// 向该phoneNo添加错误计数器
......
package cn.quantgroup.xyqb.exception;
/**
* Created by Miraculous on 15/7/12.
*/
public class NullUserException extends RuntimeException {
private static final long serialVersionUID = -1L;
public NullUserException() {
super("未找到用户");
}
public NullUserException(String message) {
super(message);
}
}
package cn.quantgroup.xyqb.interceptors;
import cn.quantgroup.xyqb.util.IPUtil;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Created by Administrator on 2017/5/9.
*/
public class IPWhiteListInterceptor implements HandlerInterceptor {
private Integer isDebug;
private static final Logger LOGGER = LoggerFactory.getLogger(IPWhiteListInterceptor.class);
private static final String patternStr = "172.*";
private static final String [] allowIPs = {"139.198.7.123"};
private static Set<String> allowIPSet = Sets.newHashSet(allowIPs);
private static final Pattern pattern = Pattern.compile(patternStr);
public IPWhiteListInterceptor(Integer isDebug) {
this.isDebug = isDebug;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(isDebug !=0){
return true;
}
String remoteIP = IPUtil.getRemoteIP(request);
if(StringUtils.isNoneBlank(remoteIP)){
remoteIP = remoteIP.trim();
boolean isMatch = pattern.matcher(remoteIP).matches();
isMatch = Boolean.logicalOr(isMatch,allowIPSet.contains(remoteIP));
if(!isMatch){
LOGGER.info("非法IP尝试访问,ip:[{}]",remoteIP);
}
return isMatch;
}
LOGGER.info("未能获取remoteIP");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
......@@ -153,9 +153,10 @@ public class SessionServiceImpl implements ISessionService {
*/
private void setUserIdTokenKeys(long userId, String key) {
if (0L != userId) {
String setKey = getUserSessionSetKey(userId);
try {
stringRedisTemplate.opsForSet().add(Constants.Session.USER_SESSION_KEY_SET + userId, key);
stringRedisTemplate.expire(Constants.Session.USER_SESSION_KEY_SET + userId, Constants.Session.ONE_DAY, TimeUnit.SECONDS);
stringRedisTemplate.opsForSet().add(setKey, key);
stringRedisTemplate.expire(setKey, Constants.Session.ONE_DAY, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("存储用户注销件失败,userId:{},Exception:{}", userId, e);
}
......@@ -189,21 +190,16 @@ public class SessionServiceImpl implements ISessionService {
@CacheEvict(value = "userextinfocache", key = "'extinfo' + #userId", cacheManager = "cacheManager")
public void deleteByUserId(long userId) {
//1.删除session关联
Set useIdKeys = stringRedisTemplate.opsForSet().members(Constants.Session.USER_SESSION_KEY_SET + userId);
String setKey = getUserSessionSetKey(userId);
Set useIdKeys = stringRedisTemplate.opsForSet().members(setKey);
if (!CollectionUtils.isEmpty(useIdKeys)) {
useIdKeys.forEach(key -> {
log.info("删除用户userId={}的缓存信息", userId);
stringRedisTemplate.delete(String.valueOf(key));
});
//2.删除session缓存健
stringRedisTemplate.delete(Constants.Session.USER_SESSION_KEY_SET + userId);
stringRedisTemplate.delete(setKey);
}
}
/**
......@@ -221,4 +217,13 @@ public class SessionServiceImpl implements ISessionService {
public void deleteUserCatch(User user) {
}
/**
* 获取用户的会话缓存Set的Redis-Key
* @param userId - 用户主键
* @return
*/
private String getUserSessionSetKey(long userId) {
return Constants.Session.USER_SESSION_KEY_SET + userId;
}
}
......@@ -55,10 +55,6 @@ public class LockIpv4ServiceImpl implements ILockIpv4Service {
*/
@Override
public void countErrorByIpv4(String ipv4) {
// Todo -- 全天候开放监控
/*if(!ValidationUtil.isAtDangerousTime()){
return;
}*/
if (ValidationUtil.validateIpv4(ipv4) && !IPUtil.whiteOf(ipv4)) {
String ipv4Key = getErrorIpKey(ipv4);
if(!stringRedisTemplate.hasKey(ipv4Key)){
......@@ -99,10 +95,6 @@ public class LockIpv4ServiceImpl implements ILockIpv4Service {
*/
@Override
public void countSuccessByIpv4(String ipv4) {
// Todo -- 全天候开放监控
/*if(!ValidationUtil.isAtDangerousTime()){
return;
}*/
if (ValidationUtil.validateIpv4(ipv4) && !IPUtil.whiteOf(ipv4)) {
String ipv4Key = getSuccessIpKey(ipv4);
if(!stringRedisTemplate.hasKey(ipv4Key)){
......
......@@ -26,10 +26,11 @@ public class IPUtil {
* 172.20.0.0/16 - 3B私有云
* 172.30.0.0/16 - 3C私有云
*/
private static final Set<String> whiteAddr = Sets.newHashSet();
private static final Set<String> WHITE_ADDRESS = Sets.newHashSet();
private static final String LOCAL_ADDRESS = "127.0.0.1";
static {
String[] ips = {"172.16.", "172.20.", "172.30.", "192.168.3.", "192.168.4."};
whiteAddr.addAll(Arrays.asList(ips));
WHITE_ADDRESS.addAll(Arrays.asList(ips));
}
/**
......@@ -39,7 +40,7 @@ public class IPUtil {
*/
public static final boolean whiteOf(String ipv4){
if(ValidationUtil.validateIpv4(ipv4)){
for(String ipField : whiteAddr){
for(String ipField : WHITE_ADDRESS){
if(ipv4.startsWith(ipField)){
return true;
}
......@@ -70,8 +71,9 @@ public class IPUtil {
* @return
*/
public static String getRemoteIP(HttpServletRequest request) {
Objects.requireNonNull(request, "无效请求");
String ip = request.getHeader("x-original-client-ip");
if (ValidationUtil.validateIpv4(ip) && !ip.startsWith("127.")) {
if (ValidationUtil.validateIpv4(ip) && !Objects.equals(LOCAL_ADDRESS, ip)) {
return ip;
}
......
......@@ -15,7 +15,7 @@ import java.util.regex.Pattern;
*/
public class ValidationUtil {
private static String phoneRegExp = "^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
private static String phoneRegExp = "^1[345789][0-9]{9}$";
private static String chineseNameRegExp = "^[\u4e00-\u9fa5]+(\\.|·)?[\u4e00-\u9fa5]+$";
private static String ipv4RegExp = "^((2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)\\.){3}(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)$";
private static String localIpv4RegExp = "^((172\\.(1[0-6]|2[0-9]|3[01]))|(192\\.168|169\\.254)|((127|10)\\.(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)))(\\.(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)){2}$";
......@@ -42,6 +42,11 @@ public class ValidationUtil {
return matcher.find();
}
/**
* 是否是合法的IPV4地址
* @param ipv4
* @return
*/
public static boolean validateIpv4(String ipv4) {
if (StringUtils.isBlank(ipv4)) {
return false;
......@@ -50,6 +55,11 @@ public class ValidationUtil {
return matcher.find();
}
/**
* 是否是合法的私有IPV4地址
* @param localIpv4
* @return
*/
public static boolean validateLocalIpv4(String localIpv4) {
if (StringUtils.isBlank(localIpv4)) {
return false;
......@@ -83,21 +93,4 @@ public class ValidationUtil {
return MD5Util.build(_key.toString());
}
public static boolean isAtDangerousTime() {
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
return Constants.DANGEROUS_TIME_START <= hour || hour < Constants.DANGEROUS_TIME_END;
}
public static boolean validateChannelId(Long channelId) {
return channelId == 0L ? false : true;
}
public static boolean isNull(Object object) {
if (object == null) {
return true;
}
return false;
}
}
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