修改app6.3.3

parent 0719d38f
...@@ -28,6 +28,9 @@ public interface Constants { ...@@ -28,6 +28,9 @@ public interface Constants {
String REDIS_PREFIX_VERIFICATION_VOICE_CODE = "verificationCode_voice_"; String REDIS_PREFIX_VERIFICATION_VOICE_CODE = "verificationCode_voice_";
String REDIS_VOICE_CODE_COUNT = "voice_verification_code_count:"; String REDIS_VOICE_CODE_COUNT = "voice_verification_code_count:";
String REDIS_SMS_CODE_COUNT = "SMS_verification_code_count:";
String REDIS_SMS_IP_COUNT = "SMS_verification_code_count:";
String REDIS_SMS_DEVICE_COUNT = "SMS_verification_code_count:";
/** /**
* redis中token的key值前缀 * redis中token的key值前缀
*/ */
......
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 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;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
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.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.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* 类名称:CaptchaValidateAdvisor
* 类描述:
*
* @author 李宁
* @version 1.0.0 创建时间:15/11/17 14:49 修改人: 修改时间:15/11/17 14:49 修改备注:
*/
@Aspect
@Component
public class CaptchaNewValidateAdvisor {
private static final Logger LOGGER = LoggerFactory.getLogger(CaptchaNewValidateAdvisor.class);
private static final String SUPER_CAPTCHA_ID = UUID.nameUUIDFromBytes("__QG_APPCLIENT_AGENT__".getBytes(Charset.forName("UTF-8"))).toString();
private static final String SUPER_CAPTCHA = "__SUPERQG__";
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate;
@Autowired
@Qualifier("customCaptchaService")
private AbstractManageableImageCaptchaService imageCaptchaService;
/**
* 自动化测试忽略验证码
*/
@Value("${xyqb.auth.captcha.autotest.enable:false}")
private boolean autoTestCaptchaEnabled;
/**
* 图形验证码切面
*/
@Pointcut("@annotation(cn.quantgroup.xyqb.aspect.captcha.CaptchaNewValidator)")
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;
/**
* 在受图形验证码保护的接口方法执行前, 执行图形验证码校验
*
* @throws Throwable
*/
@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("");
Object captchaValue = request.getParameter("captchaValue");
String phoneNo = request.getParameter("phoneNo");
String deviceId = Optional.ofNullable(request.getParameter("deviceId")).orElse("");
String clientIp = getIp();
Long countIP = countIP(clientIp);
Long countPhone = countPhone(phoneNo);
Long countDeviceId = countDeviceId(deviceId);
if (countIP > 3 || countPhone > 3 || countDeviceId > 3) {
if (shouldSkipCaptchaValidate(registerFrom, captchaId, captchaValue)) {
LOGGER.info("使用超级图形验证码校验, registerFrom={}, clientIp={}", registerFrom, request.getRemoteAddr());
return pjp.proceed();
}
JsonResult result = JsonResult.buildSuccessResult("图形验证码错误, 请重新输入", "");
result.setBusinessCode("0002");
if (captchaValue != null) {
String captcha = String.valueOf(captchaValue);
// 忽略用户输入的大小写
captcha = StringUtils.lowerCase(captcha);
// 验证码校验
Boolean validCaptcha = false;
try {
validCaptcha = imageCaptchaService.validateResponseForID(Constants.IMAGE_CAPTCHA_KEY + captchaId, captcha);
} catch (CaptchaServiceException ex) {
LOGGER.error("验证码校验异常, {}, {}", ex.getMessage(), ex);
}
if (validCaptcha) {
return pjp.proceed();
}
}
return result;
}
return pjp.proceed();
}
private boolean shouldSkipCaptchaValidate(String registerFrom, String captchaId, Object captchaValue) {
// 如果启用了超级验证码功能, 检查超级验证码, 超级验证码区分大小写
if (autoTestCaptchaEnabled) {
return true;
}
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);
if (StringUtils.isBlank(countString)) {
redisTemplate.opsForValue().set(IMAGE_PHONE_COUNT + phoneNo, String.valueOf(count),
FIVE_MIN, TimeUnit.SECONDS);
} else {
count = Long.valueOf(countString) + 1L;
redisTemplate.opsForValue().set(IMAGE_PHONE_COUNT + phoneNo, String.valueOf(count),
FIVE_MIN, TimeUnit.SECONDS);
}
return count;
}
/**
* 短信发送设备限制
*/
private Long countDeviceId(String deviceId) {
Long count = 1L;
if (StringUtils.isBlank(deviceId)) {
return count;
} else {
String countString = redisTemplate.opsForValue().get(IMAGE_DEVICEID_COUNT + deviceId);
if (StringUtils.isBlank(countString)) {
redisTemplate.opsForValue().set(IMAGE_DEVICEID_COUNT + deviceId, 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);
}
return count;
}
}
private String getIp() {
HttpServletRequest request = getRequest();
String ip = request.getHeader("x-real-ip");
if (StringUtils.isEmpty(ip)) {
ip = request.getRemoteAddr();
}
//过滤反向代理的ip
String[] stemps = ip.split(",");
if (stemps.length >= 1) {
//得到第一个IP,即客户端真实IP
ip = stemps[0];
}
ip = ip.trim();
if (ip.length() > 23) {
ip = ip.substring(0, 23);
}
return ip;
}
private HttpServletRequest getRequest() {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
return attrs.getRequest();
}
}
package cn.quantgroup.xyqb.aspect.captcha;
import java.lang.annotation.*;
/**
* Created by xuran on 2017/8/28.
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CaptchaNewValidator {
}
...@@ -50,6 +50,7 @@ public class ImageCaptchaController implements IBaseController { ...@@ -50,6 +50,7 @@ public class ImageCaptchaController implements IBaseController {
private static final String IMAGE_FORMAT_PNG = "png"; private static final String IMAGE_FORMAT_PNG = "png";
private static final String IMG_BASE64_PATTREN = "data:image/" + IMAGE_FORMAT_PNG + ";base64,%s"; private static final String IMG_BASE64_PATTREN = "data:image/" + IMAGE_FORMAT_PNG + ";base64,%s";
private static final String IMAGE_IP_COUNT = "image:ip"; private static final String IMAGE_IP_COUNT = "image:ip";
private static final String IMAGE_PHONE_COUNT = "image:phone";
private static final Long FIVE_MIN = 24 * 5L; private static final Long FIVE_MIN = 24 * 5L;
@Autowired @Autowired
@Qualifier("customCaptchaService") @Qualifier("customCaptchaService")
...@@ -93,91 +94,4 @@ public class ImageCaptchaController implements IBaseController { ...@@ -93,91 +94,4 @@ public class ImageCaptchaController implements IBaseController {
return JsonResult.buildSuccessResult("", data); return JsonResult.buildSuccessResult("", data);
} }
/**
* 新版本获取验证码
* 默认匹配 GET /captcha, 提供4位数字和字母混合图片验证码
*/
@RequestMapping(value = "/captcha_new")
public JsonResult fetchCaptchaNew(HttpServletRequest request, @ModelAttribute("clientIp") String clientIp) {
if (StringUtils.isBlank(clientIp)) {
return JsonResult.buildErrorStateResult("", "fail");
}
Long count= countIP(clientIp);
if(count>5){
String imageId = UUID.randomUUID().toString();
BufferedImage challenge = imageCaptchaService.getImageChallengeForID(Constants.IMAGE_CAPTCHA_KEY + imageId, request.getLocale());
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
boolean write = ImageIO.write(challenge, IMAGE_FORMAT_PNG, jpegOutputStream);
} catch (IOException e) {
e.printStackTrace();
return JsonResult.buildErrorStateResult("", "fail");
}
String imageBase64 = Base64.encodeBase64String(jpegOutputStream.toByteArray());
Map<String, String> data = new HashMap<>();
data.put("imageId", imageId);
data.put("image", String.format(IMG_BASE64_PATTREN, imageBase64));
return JsonResult.buildSuccessResult("", data);
}
return JsonResult.buildSuccessResult("", "success");
}
private Long countIP(@ModelAttribute("clientIp") String clientIp) {
Long count=1L;
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;
}
/**
* 图片验证码验证
*/
@CaptchaValidator
@RequestMapping("/verification_image_code")
public JsonResult verificationImageCode(HttpServletRequest request, @RequestParam String captchaId, @RequestParam Object captchaValue) {
Boolean validCaptcha = false;
String registerFrom = Optional.ofNullable(request.getParameter("registerFrom")).orElse("");
if (shouldSkipCaptchaValidate(registerFrom, captchaId, captchaValue)) {
LOGGER.info("使用超级图形验证码校验, registerFrom={}, clientIp={}", registerFrom, request.getRemoteAddr());
validCaptcha = true;
return JsonResult.buildSuccessResult("", validCaptcha);
}
JsonResult result = JsonResult.buildSuccessResult("图形验证码错误, 请重新输入", "");
result.setBusinessCode("0002");
if (captchaValue != null) {
String captcha = String.valueOf(captchaValue);
// 忽略用户输入的大小写
captcha = StringUtils.lowerCase(captcha);
// 验证码校验
try {
validCaptcha = imageCaptchaService.validateResponseForID(Constants.IMAGE_CAPTCHA_KEY + captchaId, captcha);
} catch (CaptchaServiceException ex) {
LOGGER.error("验证码校验异常, {}, {}", ex.getMessage(), ex);
}
}
return JsonResult.buildSuccessResult("", validCaptcha);
}
private boolean shouldSkipCaptchaValidate(String registerFrom, String captchaId, Object captchaValue) {
// 如果启用了超级验证码功能, 检查超级验证码, 超级验证码区分大小写
if (autoTestCaptchaEnabled) {
return true;
}
return StringUtils.equals(SUPER_CAPTCHA_ID, String.valueOf(captchaId)) && StringUtils.equals(SUPER_CAPTCHA, String.valueOf(captchaValue));
}
} }
...@@ -2,7 +2,9 @@ package cn.quantgroup.xyqb.controller.internal.sms; ...@@ -2,7 +2,9 @@ package cn.quantgroup.xyqb.controller.internal.sms;
import cn.quantgroup.sms.MsgParams; import cn.quantgroup.sms.MsgParams;
import cn.quantgroup.xyqb.Constants; import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.aspect.captcha.CaptchaNewValidator;
import cn.quantgroup.xyqb.aspect.captcha.CaptchaValidator; import cn.quantgroup.xyqb.aspect.captcha.CaptchaValidator;
import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.model.JsonResult; import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.service.sms.ISmsService; import cn.quantgroup.xyqb.service.sms.ISmsService;
import cn.quantgroup.xyqb.util.DateUtils; import cn.quantgroup.xyqb.util.DateUtils;
...@@ -14,6 +16,7 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -14,6 +16,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
...@@ -26,7 +29,7 @@ import java.util.concurrent.TimeUnit; ...@@ -26,7 +29,7 @@ import java.util.concurrent.TimeUnit;
*/ */
@RestController @RestController
@RequestMapping("/api/sms") @RequestMapping("/api/sms")
public class SmsController { public class SmsController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class); private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class);
private static final Random random = new Random(); private static final Random random = new Random();
...@@ -39,6 +42,9 @@ public class SmsController { ...@@ -39,6 +42,9 @@ public class SmsController {
@Value("${sms.is.debug}") @Value("${sms.is.debug}")
private boolean smsIsDebug; private boolean smsIsDebug;
/** /**
* 短信验证码: for H5 * 短信验证码: for H5
* 使用 @FPLock 注解并加入自定义限制参数, 做针对手机号的发送次数限制 * 使用 @FPLock 注解并加入自定义限制参数, 做针对手机号的发送次数限制
...@@ -180,35 +186,56 @@ public class SmsController { ...@@ -180,35 +186,56 @@ public class SmsController {
/** /**
* 快速登陆发送验证码新版 * 快速登陆发送验证码新版
*/ */
@CaptchaNewValidator
@RequestMapping("/send_login_code_voice_new") @RequestMapping("/send_login_code_voice_new")
public JsonResult sendLoginSmsCodeNew(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom, public JsonResult sendLoginSmsCodeNew(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom,
String usage) { String usage,@RequestParam(required = false) String deviceId) {
if (StringUtils.isEmpty(usage) || !"6".equals(usage)) { if (StringUtils.isEmpty(usage) || !"6".equals(usage)) {
LOGGER.error("参数校验失败,用户登录语音验证码usage参数为{}", usage); LOGGER.error("参数校验失败,用户登录语音验证码usage参数为{}", usage);
return JsonResult.buildErrorStateResult("参数校验失败.", null); return JsonResult.buildErrorStateResult("参数校验失败.", null);
} }
LOGGER.info("快速登陆-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom); LOGGER.info("快速登陆-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2VoiceNew(phoneNo, usage);
return sendVerificationCode2VoiceNew(phoneNo, usage,deviceId);
} }
/** /**
* 快速登陆发送短信验证码 * 快速登陆发送短信验证码
*/ */
@CaptchaNewValidator
@RequestMapping("/send_login_code_new") @RequestMapping("/send_login_code_new")
public JsonResult sendLoginCodeVoiceNew(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) { public JsonResult sendLoginCodeVoiceNew(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom,@RequestParam(required = false) String deviceId) {
LOGGER.info("快速登陆-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom); LOGGER.info("快速登陆-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2New(phoneNo); return sendVerificationCode2New(phoneNo,deviceId);
} }
/** /**
* 新版本验证码 * 新版本验证码
* @param phoneNo
* @return
*/ */
private JsonResult sendVerificationCode2New(String phoneNo) { private JsonResult sendVerificationCode2New(String phoneNo,String deviceId) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) { if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return JsonResult.buildErrorStateResult("手机号格式有误", null); return JsonResult.buildErrorStateResult("手机号格式有误", null);
} }
String verificationPhoneCountKey = Constants.REDIS_SMS_CODE_COUNT + phoneNo;
Long getPhoneVerificationCount = redisTemplate.opsForHash().increment(verificationPhoneCountKey,Constants.REDIS_SMS_CODE_COUNT , 1);
if (getPhoneVerificationCount > 20) {
return JsonResult.buildErrorStateResult("今天已获取20次短信验证码,请使用语音验证码或明天再试", null);
}
String verificationIPCountKey=getIp();
if(!StringUtils.isEmpty(verificationIPCountKey)){
Long getIPVerificationCount = redisTemplate.opsForHash().increment(verificationIPCountKey,Constants.REDIS_SMS_IP_COUNT , 1);
if (getIPVerificationCount > 5000) {
return JsonResult.buildErrorStateResult("您当前ip已经达到获取今天验证码上线", null);
}
}
if(!StringUtils.isEmpty(deviceId)){
String verificationDeviceCountKey = Constants.REDIS_SMS_DEVICE_COUNT + deviceId;
Long getDeviceVerificationCount = redisTemplate.opsForHash().increment(verificationDeviceCountKey,Constants.REDIS_SMS_DEVICE_COUNT , 1);
if (getDeviceVerificationCount > 20) {
return JsonResult.buildErrorStateResult("您当前ip已经达到获取今天验证码上线", null);
}
}
String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo; String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
long expire = redisTemplate.getExpire(key, TimeUnit.MINUTES); long expire = redisTemplate.getExpire(key, TimeUnit.MINUTES);
...@@ -233,17 +260,32 @@ public class SmsController { ...@@ -233,17 +260,32 @@ public class SmsController {
return JsonResult.buildErrorStateResult("发送失败", null); return JsonResult.buildErrorStateResult("发送失败", null);
} }
} }
/** /**
* 新版本语音验证码 * 新版本语音验证码
* @param phoneNo
* @return
*/ */
private JsonResult sendVerificationCode2VoiceNew(String phoneNo, String usage) { private JsonResult sendVerificationCode2VoiceNew(String phoneNo, String usage,String deviceId) {
String verificationCountKey = Constants.REDIS_VOICE_CODE_COUNT + phoneNo; String verificationCountKey = Constants.REDIS_VOICE_CODE_COUNT + phoneNo;
Long getVerificationCount = redisTemplate.opsForHash().increment(verificationCountKey, usage.toString(), 1); Long getVerificationCount = redisTemplate.opsForHash().increment(verificationCountKey, usage.toString(), 1);
if (getVerificationCount > 5) { if (getVerificationCount > 5) {
return JsonResult.buildErrorStateResult("今天已获取5次语音验证码,请使用短信验证码或明天再试", null); return JsonResult.buildErrorStateResult("今天已获取5次语音验证码,请使用短信验证码或明天再试", null);
} }
String verificationIPCountKey=getIp();
if(!StringUtils.isEmpty(verificationIPCountKey)){
Long getIPVerificationCount = redisTemplate.opsForHash().increment(verificationIPCountKey,Constants.REDIS_SMS_IP_COUNT , 1);
if (getIPVerificationCount > 5000) {
return JsonResult.buildErrorStateResult("您当前ip已经达到获取今天验证码上线", null);
}
}
if(!StringUtils.isEmpty(deviceId)){
String verificationDeviceCountKey = Constants.REDIS_SMS_DEVICE_COUNT + deviceId;
Long getDeviceVerificationCount = redisTemplate.opsForHash().increment(verificationDeviceCountKey,Constants.REDIS_SMS_DEVICE_COUNT , 1);
if (getDeviceVerificationCount > 20) {
return JsonResult.buildErrorStateResult("您当前ip已经达到获取今天验证码上线", null);
}
}
redisTemplate.expire(verificationCountKey, DateUtils.getSeconds(), TimeUnit.SECONDS); redisTemplate.expire(verificationCountKey, DateUtils.getSeconds(), TimeUnit.SECONDS);
if (!ValidationUtil.validatePhoneNo(phoneNo)) { if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return JsonResult.buildErrorStateResult("手机号格式有误", null); return JsonResult.buildErrorStateResult("手机号格式有误", null);
...@@ -265,4 +307,7 @@ public class SmsController { ...@@ -265,4 +307,7 @@ public class SmsController {
return JsonResult.buildErrorStateResult("发送失败", null); return JsonResult.buildErrorStateResult("发送失败", null);
} }
} }
} }
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