Commit 6211a75e by 章家宝

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

1 parent 2364dd9d
package com.glsx.usedcar.gsc; package com.glsx.usedcar.gsc;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.usedcar.util.GLRopApiUtils; import com.glsx.usedcar.util.GLRopApiUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
...@@ -9,6 +11,8 @@ import org.springframework.util.LinkedMultiValueMap; ...@@ -9,6 +11,8 @@ import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.util.Objects;
@Slf4j @Slf4j
@Component @Component
public class GscApiInvoker { public class GscApiInvoker {
...@@ -58,9 +62,9 @@ public class GscApiInvoker { ...@@ -58,9 +62,9 @@ public class GscApiInvoker {
* @param mobile * @param mobile
* @param context * @param context
*/ */
public void sendMsg(String mobile, String context) { public boolean sendMsg(String mobile, String context) {
if (!StringUtils.hasText(mobile) || mobile.length()!= 11) { if (!StringUtils.hasText(mobile) || mobile.length()!= 11) {
return; return false;
} }
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(4); MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(4);
// 短信接收人的手机号 // 短信接收人的手机号
...@@ -74,10 +78,13 @@ public class GscApiInvoker { ...@@ -74,10 +78,13 @@ public class GscApiInvoker {
String postRes = null; String postRes = null;
try { try {
postRes = GLRopApiUtils.postForSms("glsx.accounts.send.message", params, String.class, baseUrl, appkey, secret); 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) { } catch (Exception e) {
log.error("发送短信失败:" + e.getMessage()); log.error("发送短信失败:" + e.getMessage());
return false;
} }
log.info(postRes);
} }
} }
...@@ -147,6 +147,10 @@ public class InspectionReportService { ...@@ -147,6 +147,10 @@ public class InspectionReportService {
InspectionRecord inspectionRecord = inspectionRecordRepository.findByTaskIdAndDeletedFlag(wo.getId(), DeleteFlag.NOT_DELETED.getCode()) InspectionRecord inspectionRecord = inspectionRecordRepository.findByTaskIdAndDeletedFlag(wo.getId(), DeleteFlag.NOT_DELETED.getCode())
.orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, "检测记录不存在,ID:" + wo.getId())); .orElseThrow(() -> new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, "检测记录不存在,ID:" + wo.getId()));
String h5Url = String.format(inspectorConfig.getInspectionRecordH5Url(), inspectionRecord.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. 构建报告实体 // 2. 构建报告实体
InspectionReport report = InspectionReport.builder() InspectionReport report = InspectionReport.builder()
.reportNo(reportNo) .reportNo(reportNo)
...@@ -154,7 +158,7 @@ public class InspectionReportService { ...@@ -154,7 +158,7 @@ public class InspectionReportService {
.vehicle(vehicle) .vehicle(vehicle)
.workOrder(wo) .workOrder(wo)
.inspectionRecord(inspectionRecord) .inspectionRecord(inspectionRecord)
.bindStatus(2) .bindStatus(1)
.h5Url(h5Url) .h5Url(h5Url)
.deleteFlag(DeleteFlag.NOT_DELETED.getCode()) .deleteFlag(DeleteFlag.NOT_DELETED.getCode())
.build(); .build();
......
...@@ -591,6 +591,7 @@ public class InspectionWorkOrderService { ...@@ -591,6 +591,7 @@ public class InspectionWorkOrderService {
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
workOrder.setStatus(targetStatus); workOrder.setStatus(targetStatus);
// workOrder.setInspectionCompletedTime(now); // workOrder.setInspectionCompletedTime(now);
workOrder.setAuditStatus(InspectionWorkOrderAuditStatusEnum.WAIT_AUDIT.getCode());
workOrder.setUpdateBy(opName); workOrder.setUpdateBy(opName);
workOrder.setUpdateTime(now); workOrder.setUpdateTime(now);
inspectionWorkOrderRepository.save(workOrder); inspectionWorkOrderRepository.save(workOrder);
......
...@@ -10,111 +10,105 @@ import org.springframework.beans.factory.annotation.Value; ...@@ -10,111 +10,105 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.summerframework.core.enums.ErrorCodeEnum;
import org.summerframework.core.exception.BusinessCodeException;
import java.util.Locale; import java.util.Locale;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* 短信验证码工具类(含防刷逻辑) * 短信验证码工具类(多维度频率限制:1分钟1次 / 1小时5次 / 24小时10次)
*/ */
@Slf4j @Slf4j
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
public class SmsCodeUtil { 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; private int codeExpire;
@Value("${sms.code-length:6}") // 验证码长度 @Value("${sms.code-length:6}")
private int codeLength; private int codeLength;
@Value("${sms.cool-down:60}") // 冷却期:60秒内禁止重复发送(秒) private final RedisCacheUtil redisCacheUtil;
private long coolDownSeconds; private final SystemConfigRedisCache systemConfigRedisCache;
private final MessageSource messageSource;
@Value("${sms.time-window:300}") // 次数限流时间窗口:5分钟(秒)
private long timeWindowSeconds;
@Value("${sms.max-count:3}") // 时间窗口内最大发送次数 @Lazy
private int maxSendCount; @Resource
private GscApiInvoker gscApiInvoker;
/** /**
* 校验验证码发送频率(防刷核心方法) * 多维度频率校验
* @param phone 手机号
* @throws RuntimeException 频率超限则抛出异常(前端捕获提示)
*/ */
public void checkSendFrequency(String phone) { public void checkSendFrequency(String phone) {
// 1. 构建Redis Key String key1min = "SMS:LIMIT:1MIN:" + phone;
String coolDownKey = "SMS_COOL_DOWN:" + phone; String key1hour = "SMS:LIMIT:1HOUR:" + phone;
String countKey = "SMS_SEND_COUNT:" + phone; String key1day = "SMS:LIMIT:1DAY:" + phone;
// 2. 检查冷却期:60秒内是否已发送过 // 校验
if (redisCacheUtil.existsKey(coolDownKey)) { checkAndIncrement(key1min, limitOneMin, ONE_MINUTE_SECONDS, "1分钟内最多发送1次");
throw new RuntimeException("验证码发送过于频繁,请" + coolDownSeconds + "秒后再试"); 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);
} }
redisCacheUtil.setCacheWithExpire(key, count == null ? 1 : count + 1, expireSeconds, TimeUnit.SECONDS);
// 4. 次数累加(首次发送则设为1,否则+1)
int newCount = sendCount == null ? 1 : sendCount + 1;
redisCacheUtil.setCacheWithExpire(countKey, newCount, timeWindowSeconds, TimeUnit.SECONDS);
} }
/** /**
* 生成并存储验证码(需先调用checkSendFrequency校验频率) * 生成并发送验证码
* @param phone 手机号
* @return 生成的验证码
*/ */
public String generateAndSaveCode(String phone) { public String generateAndSaveCode(String phone) {
// 1. 生成6位数字验证码
String code = RandomUtil.randomNumbers(codeLength); String code = RandomUtil.randomNumbers(codeLength);
// 2. 存储验证码(5分钟过期) redisCacheUtil.setCacheWithExpire("SMS:CODE:" + phone, code, codeExpire, TimeUnit.SECONDS);
String codeKey = "SMS_CODE:" + phone;
redisCacheUtil.setCacheWithExpire(codeKey, code, codeExpire, TimeUnit.SECONDS); String message = messageSource.getMessage("Inspector.Login.SMSCODE", new Object[]{code, codeExpire / 60}, Locale.CHINESE);
boolean sendResult = gscApiInvoker.sendMsg(phone, message);
// 3. 设置冷却期(60秒过期) if (!sendResult) {
String coolDownKey = "SMS_COOL_DOWN:" + phone; throw new BusinessCodeException(ErrorCodeEnum.COMMON_ERROR, "发送短信失败");
redisCacheUtil.setCacheWithExpire(coolDownKey, System.currentTimeMillis(), coolDownSeconds, TimeUnit.SECONDS); }
Object[] args = {code, codeExpire / 60};
String message = messageSource.getMessage("Inspector.Login.SMSCODE", args, Locale.CHINESE); log.info("手机号{}发送验证码成功:{}", phone, code);
// 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));
return code; return code;
} }
/** /**
* 验证验证码是否正确 * 验证验证码
* @param phone 手机号
* @param code 前端提交的验证码
* @return 是否正确
*/ */
public boolean validateCode(String phone, String code) { public boolean validateCode(String phone, String code) {
String codeKey = "SMS_CODE:" + phone; String realCode = redisCacheUtil.getCache("SMS:CODE:" + phone, String.class);
String redisCode = redisCacheUtil.getCache(codeKey, String.class); if (realCode == null) {
if (redisCode == null) { log.warn("手机号{}验证码已过期", phone);
log.warn("手机号{}验证码已过期,{}", phone, code);
return false; return false;
} }
// 验证通过后删除验证码(防止重复使用) boolean ok = realCode.equals(code);
boolean isValid = redisCode.equals(code); if (ok) {
if (isValid) { redisCacheUtil.deleteCache("SMS:CODE:" + phone);
redisCacheUtil.deleteCache(codeKey);
} }
return isValid; return ok;
} }
} }
\ No newline at end of file \ 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!