1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
| @Service public class AuthServiceImpl implements AuthService { @Autowired private EmailServiceImpl emailService;
@Autowired private AliyunSmsServiceImpl aliyunSmsService;
@Autowired UserMapper userMapper;
@Autowired private RedisCache redisCache;
@Override public ResponseResult sendEmailLoginCode(SendCodeDto dto) { return sendVerificationCode(dto.getEmail(), "email", "login", true); }
@Override public ResponseResult sendPhoneLoginCode(SendCodeDto dto) { return sendVerificationCode(dto.getPhone(), "phone", "login", true); }
@Override public ResponseResult sendEmailRegisterCode(SendCodeDto dto) { return sendVerificationCode(dto.getEmail(), "email", "register", false); }
@Override public ResponseResult sendPhoneRegisterCode(SendCodeDto dto) { return sendVerificationCode(dto.getPhone(), "phone", "register", false); }
@Override public ResponseResult sendEmailForgotPasswordCode(SendCodeDto dto) { return sendVerificationCode(dto.getEmail(), "email", "forgot", true); }
private ResponseResult sendVerificationCode(String account, String type, String scene, boolean needAccountExists) { ResponseResult validateResult = validateAccount(account, type); if (validateResult != null) { return validateResult; }
ResponseResult accountCheckResult = checkAccountForScene(account, type, scene, needAccountExists); if (accountCheckResult != null) { return accountCheckResult; }
String clientIp = getClientIp(); ResponseResult ipCheckResult = checkIpLimit(clientIp, type); if (ipCheckResult != null) { return ipCheckResult; }
String sendTimeKey = String.format("%s:send:time:%s:%s", scene, type, account); String lastSendTime = redisCache.getCacheObject(sendTimeKey); if (StringUtils.hasText(lastSendTime)) { return ResponseResult.errorResult(AppHttpCodeEnum.SMS_SEND_FREQUENTLY, "验证码发送过于频繁,请1分钟后再试"); }
String code = generateCode(); String redisKey = String.format("%s:code:%s:%s", scene, type, account); redisCache.setCacheObject(redisKey, code, 5, TimeUnit.MINUTES);
redisCache.setCacheObject(sendTimeKey, String.valueOf(System.currentTimeMillis()), 1, TimeUnit.MINUTES);
recordIpSendCount(clientIp, type);
try { if ("email".equals(type)) { switch (scene) { case "login": emailService.sendVerificationCodeByLogin(account, code); break; case "register": emailService.sendVerificationCodeByRegister(account, code); break; case "forgot": emailService.sendVerificationCodeByForgotPassword(account, code); break; default: emailService.sendVerificationCodeByLogin(account, code); } } else { aliyunSmsService.sendVerificationCode(account, code); } System.out.println(String.format("发送%s验证码到%s: %s, 验证码: %s, IP: %s", scene, type.equals("email") ? "邮箱" : "手机", account, code, clientIp)); } catch (Exception e) { System.err.println(String.format("%s发送失败: %s", type.equals("email") ? "邮件" : "短信", e.getMessage())); redisCache.deleteObject(redisKey); redisCache.deleteObject(sendTimeKey); return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "验证码发送失败,请稍后重试"); }
return ResponseResult.okResult("验证码已发送,5分钟内有效"); }
private ResponseResult validateAccount(String account, String type) { if (!StringUtils.hasText(account)) { if ("email".equals(type)) { return ResponseResult.errorResult(AppHttpCodeEnum.EMAIL_NOT_NULL); } else { return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, "手机号不能为空"); } }
if ("phone".equals(type) && !account.matches("^1[3-9]\\d{9}$")) { return ResponseResult.errorResult(AppHttpCodeEnum.PHONE_FORMAT_ERROR); }
return null; }
private ResponseResult checkAccountForScene(String account, String type, String scene, boolean needAccountExists) { LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); if ("email".equals(type)) { queryWrapper.eq(User::getEmail, account); } else { queryWrapper.eq(User::getPhone, account); } User user = userMapper.selectOne(queryWrapper); String accountTypeName = type.equals("email") ? "邮箱" : "手机号"; if (needAccountExists) { if (user == null) { return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, String.format("该%s未注册", accountTypeName)); } } else { if (user != null) { return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR, String.format("该%s已被注册", accountTypeName)); } } return null; }
private String generateCode() { Random random = new Random(); int code = random.nextInt(900000) + 100000; return String.valueOf(code); }
private String getClientIp() { try { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes != null) { HttpServletRequest request = attributes.getRequest(); return IpUtils.getIpAddr(request); } } catch (Exception e) { System.err.println("获取客户端IP失败: " + e.getMessage()); } return "unknown"; }
private ResponseResult checkIpLimit(String ip, String type) { String minuteKey = "login:ip:limit:minute:" + type + ":" + ip; Integer minuteCount = redisCache.getCacheObject(minuteKey); if (minuteCount != null && minuteCount >= 5) { return ResponseResult.errorResult(AppHttpCodeEnum.IP_REQUEST_LIMIT, "您的操作过于频繁,请1分钟后再试"); }
String hourKey = "login:ip:limit:hour:" + type + ":" + ip; Integer hourCount = redisCache.getCacheObject(hourKey); if (hourCount != null && hourCount >= 20) { return ResponseResult.errorResult(AppHttpCodeEnum.IP_REQUEST_LIMIT, "您今日发送次数过多,请1小时后再试"); }
String dayKey = "login:ip:limit:day:" + type + ":" + ip; Integer dayCount = redisCache.getCacheObject(dayKey); if (dayCount != null && dayCount >= 50) { System.err.println("检测到异常发送行为 - IP: " + ip + ", 类型: " + type + ", 24小时内发送次数: " + dayCount); return ResponseResult.errorResult(AppHttpCodeEnum.IP_REQUEST_LIMIT, "系统检测到异常行为,请24小时后再试或联系管理员"); }
return null; }
private void recordIpSendCount(String ip, String type) { String minuteKey = "login:ip:limit:minute:" + type + ":" + ip; Integer minuteCount = redisCache.getCacheObject(minuteKey); redisCache.setCacheObject(minuteKey, minuteCount == null ? 1 : minuteCount + 1, 1, TimeUnit.MINUTES);
String hourKey = "login:ip:limit:hour:" + type + ":" + ip; Integer hourCount = redisCache.getCacheObject(hourKey); redisCache.setCacheObject(hourKey, hourCount == null ? 1 : hourCount + 1, 1, TimeUnit.HOURS);
String dayKey = "login:ip:limit:day:" + type + ":" + ip; Integer dayCount = redisCache.getCacheObject(dayKey); redisCache.setCacheObject(dayKey, dayCount == null ? 1 : dayCount + 1, 1, TimeUnit.DAYS);
if (dayCount != null && dayCount >= 30) { System.err.println("警告:检测到可能的异常发送行为 - IP: " + ip + ", 类型: " + type + ", 24小时内发送次数: " + (dayCount + 1)); } } }
|