Commit 6211a75e by 章家宝

feat:短信发送需要加上校验

1 parent 2364dd9d
package com.glsx.usedcar.gsc;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.usedcar.util.GLRopApiUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
......@@ -9,6 +11,8 @@ import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import java.util.Objects;
@Slf4j
@Component
public class GscApiInvoker {
......@@ -58,9 +62,9 @@ public class GscApiInvoker {
* @param mobile
* @param context
*/
public void sendMsg(String mobile, String context) {
public boolean sendMsg(String mobile, String context) {
if (!StringUtils.hasText(mobile) || mobile.length()!= 11) {
return;
return false;
}
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(4);
// 短信接收人的手机号
......@@ -74,10 +78,13 @@ public class GscApiInvoker {
String postRes = null;
try {
postRes = GLRopApiUtils.postForSms("glsx.accounts.send.message", params, String.class, baseUrl, appkey, secret);
log.info(postRes);
JSONObject jsonObject = JSON.parseObject(postRes);
return Objects.equals(jsonObject.getString("code"), "0");
} catch (Exception e) {
log.error("发送短信失败:" + e.getMessage());
return false;
}
log.info(postRes);
}
}
......@@ -147,6 +147,10 @@ public class InspectionReportService {
InspectionRecord inspectionRecord = inspectionRecordRepository.findByTaskIdAndDeletedFlag(wo.getId(), DeleteFlag.NOT_DELETED.getCode())
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, "检测记录不存在,ID:" + wo.getId()));
String h5Url = String.format(inspectorConfig.getInspectionRecordH5Url(), inspectionRecord.getId());
// 查询该车是否绑定了报告,如果绑定了报告,则解绑,换最新的报告
inspectionReportRepository.findByBindStatusAndVehicleAndDeleteFlag(1, vehicle, DeleteFlag.NOT_DELETED.getCode())
.ifPresent(inspectionReport -> unbindInspectionReport(inspectionReport.getId(), operatorId, operatorName, platType));
// 2. 构建报告实体
InspectionReport report = InspectionReport.builder()
.reportNo(reportNo)
......@@ -154,7 +158,7 @@ public class InspectionReportService {
.vehicle(vehicle)
.workOrder(wo)
.inspectionRecord(inspectionRecord)
.bindStatus(2)
.bindStatus(1)
.h5Url(h5Url)
.deleteFlag(DeleteFlag.NOT_DELETED.getCode())
.build();
......
......@@ -591,6 +591,7 @@ public class InspectionWorkOrderService {
LocalDateTime now = LocalDateTime.now();
workOrder.setStatus(targetStatus);
// workOrder.setInspectionCompletedTime(now);
workOrder.setAuditStatus(InspectionWorkOrderAuditStatusEnum.WAIT_AUDIT.getCode());
workOrder.setUpdateBy(opName);
workOrder.setUpdateTime(now);
inspectionWorkOrderRepository.save(workOrder);
......
......@@ -10,111 +10,105 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.summerframework.core.enums.ErrorCodeEnum;
import org.summerframework.core.exception.BusinessCodeException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
/**
* 短信验证码工具类(含防刷逻辑)
* 短信验证码工具类(多维度频率限制:1分钟1次 / 1小时5次 / 24小时10次)
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class SmsCodeUtil {
private final RedisCacheUtil redisCacheUtil;
private final SystemConfigRedisCache systemConfigRedisCache;
private final MessageSource messageSource;
@Lazy
@Resource
private GscApiInvoker gscApiInvoker;
@Value("${sms.code-expire:300}") // 验证码有效期5分钟(秒)
// ====================== 固定时间窗口常量(你要的优化点) ======================
public static final int ONE_MINUTE_SECONDS = 60;
public static final int ONE_HOUR_SECONDS = 3600;
public static final int ONE_DAY_SECONDS = 86400;
// ====================== 发送频率限制(可配置,可变) ======================
@Value("${sms.limit.1min.count:1}")
private int limitOneMin;
@Value("${sms.limit.1hour.count:5}")
private int limitOneHour;
@Value("${sms.limit.24hour.count:10}")
private int limitOneDay;
// ====================== 验证码基础配置 ======================
@Value("${sms.code-expire:300}")
private int codeExpire;
@Value("${sms.code-length:6}") // 验证码长度
@Value("${sms.code-length:6}")
private int codeLength;
@Value("${sms.cool-down:60}") // 冷却期:60秒内禁止重复发送(秒)
private long coolDownSeconds;
@Value("${sms.time-window:300}") // 次数限流时间窗口:5分钟(秒)
private long timeWindowSeconds;
private final RedisCacheUtil redisCacheUtil;
private final SystemConfigRedisCache systemConfigRedisCache;
private final MessageSource messageSource;
@Value("${sms.max-count:3}") // 时间窗口内最大发送次数
private int maxSendCount;
@Lazy
@Resource
private GscApiInvoker gscApiInvoker;
/**
* 校验验证码发送频率(防刷核心方法)
* @param phone 手机号
* @throws RuntimeException 频率超限则抛出异常(前端捕获提示)
* 多维度频率校验
*/
public void checkSendFrequency(String phone) {
// 1. 构建Redis Key
String coolDownKey = "SMS_COOL_DOWN:" + phone;
String countKey = "SMS_SEND_COUNT:" + phone;
String key1min = "SMS:LIMIT:1MIN:" + phone;
String key1hour = "SMS:LIMIT:1HOUR:" + phone;
String key1day = "SMS:LIMIT:1DAY:" + phone;
// 2. 检查冷却期:60秒内是否已发送过
if (redisCacheUtil.existsKey(coolDownKey)) {
throw new RuntimeException("验证码发送过于频繁,请" + coolDownSeconds + "秒后再试");
}
// 校验
checkAndIncrement(key1min, limitOneMin, ONE_MINUTE_SECONDS, "1分钟内最多发送1次");
checkAndIncrement(key1hour, limitOneHour, ONE_HOUR_SECONDS, "1小时内最多发送5次");
checkAndIncrement(key1day, limitOneDay, ONE_DAY_SECONDS, "24小时内最多发送10次");
}
// 3. 检查时间窗口内发送次数(5分钟内最多3次)
Integer sendCount = redisCacheUtil.getCache(countKey, Integer.class);
if (sendCount != null && sendCount >= maxSendCount) {
throw new RuntimeException("验证码发送次数过多,请" + timeWindowSeconds / 60 + "分钟后再试");
/**
* 通用校验 + 自增
*/
private void checkAndIncrement(String key, int max, int expireSeconds, String msg) {
Integer count = redisCacheUtil.getCache(key, Integer.class);
if (count != null && count >= max) {
throw new RuntimeException(msg);
}
// 4. 次数累加(首次发送则设为1,否则+1)
int newCount = sendCount == null ? 1 : sendCount + 1;
redisCacheUtil.setCacheWithExpire(countKey, newCount, timeWindowSeconds, TimeUnit.SECONDS);
redisCacheUtil.setCacheWithExpire(key, count == null ? 1 : count + 1, expireSeconds, TimeUnit.SECONDS);
}
/**
* 生成并存储验证码(需先调用checkSendFrequency校验频率)
* @param phone 手机号
* @return 生成的验证码
* 生成并发送验证码
*/
public String generateAndSaveCode(String phone) {
// 1. 生成6位数字验证码
String code = RandomUtil.randomNumbers(codeLength);
// 2. 存储验证码(5分钟过期)
String codeKey = "SMS_CODE:" + phone;
redisCacheUtil.setCacheWithExpire(codeKey, code, codeExpire, TimeUnit.SECONDS);
// 3. 设置冷却期(60秒过期)
String coolDownKey = "SMS_COOL_DOWN:" + phone;
redisCacheUtil.setCacheWithExpire(coolDownKey, System.currentTimeMillis(), coolDownSeconds, TimeUnit.SECONDS);
Object[] args = {code, codeExpire / 60};
String message = messageSource.getMessage("Inspector.Login.SMSCODE", args, Locale.CHINESE);
// String msg = "【广联赛讯】您正在登录检测系统账号,验证码:%s,%s分钟内有效。如非本人操作,请忽略此短信。";
// String template = systemConfigRedisCache.getConfigValueAsString(SystemConfigKeyEnum.INSPECTOR_NOTICE_TEMPLATE_SMS_CODE.getKey(), msg);
// gscApiInvoker.sendMsg(phone, String.format(template, code, codeExpire / 60));
gscApiInvoker.sendMsg(phone, message);
// 4. 发送短信
log.info("向手机号{}发送验证码:{}(冷却期{}秒,5分钟内已发送{}次)",
phone, code, coolDownSeconds,
redisCacheUtil.getCache("SMS_SEND_COUNT:" + phone, Integer.class));
redisCacheUtil.setCacheWithExpire("SMS:CODE:" + phone, code, codeExpire, TimeUnit.SECONDS);
String message = messageSource.getMessage("Inspector.Login.SMSCODE", new Object[]{code, codeExpire / 60}, Locale.CHINESE);
boolean sendResult = gscApiInvoker.sendMsg(phone, message);
if (!sendResult) {
throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, "发送短信失败");
}
log.info("手机号{}发送验证码成功:{}", phone, code);
return code;
}
/**
* 验证验证码是否正确
* @param phone 手机号
* @param code 前端提交的验证码
* @return 是否正确
* 验证验证码
*/
public boolean validateCode(String phone, String code) {
String codeKey = "SMS_CODE:" + phone;
String redisCode = redisCacheUtil.getCache(codeKey, String.class);
if (redisCode == null) {
log.warn("手机号{}验证码已过期,{}", phone, code);
String realCode = redisCacheUtil.getCache("SMS:CODE:" + phone, String.class);
if (realCode == null) {
log.warn("手机号{}验证码已过期", phone);
return false;
}
// 验证通过后删除验证码(防止重复使用)
boolean isValid = redisCode.equals(code);
if (isValid) {
redisCacheUtil.deleteCache(codeKey);
boolean ok = realCode.equals(code);
if (ok) {
redisCacheUtil.deleteCache("SMS:CODE:" + phone);
}
return isValid;
return ok;
}
}
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!