|
|
@@ -28,6 +28,7 @@ import org.springframework.beans.BeanUtils;
|
|
|
import org.springframework.beans.BeansException;
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.data.redis.core.RedisTemplate;
|
|
|
+import org.springframework.data.redis.core.ValueOperations;
|
|
|
import org.springframework.http.HttpStatus;
|
|
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
|
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
|
|
@@ -56,6 +57,8 @@ public class UserServiceImpl implements UserService {
|
|
|
|
|
|
private final EmailService emailService = new EmailService();
|
|
|
|
|
|
+ private static final long SEND_INTERVAL = 60; // 允许再次发送的时间间隔,单位秒
|
|
|
+
|
|
|
private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
|
|
|
|
|
@Autowired
|
|
|
@@ -127,12 +130,23 @@ public class UserServiceImpl implements UserService {
|
|
|
|
|
|
@Override
|
|
|
public void sendVerifyCode(String officialEmail) {
|
|
|
+ ValueOperations<String, Object> ops = redisTemplate.opsForValue();
|
|
|
+ String intervalKey = "requestInterval:" + officialEmail;
|
|
|
+
|
|
|
+ // 检查是否已经发送过验证码并且时间间隔未过
|
|
|
+ if (ops.get(intervalKey) != null) {
|
|
|
+ throw new MyException(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase()+":"+"需等待"+SEND_INTERVAL+"秒才能再次发送验证码");
|
|
|
+ }
|
|
|
+
|
|
|
// 生成验证码
|
|
|
String code = UUID.randomUUID().toString().substring(0, 6);
|
|
|
// 存储验证码到Redis,设置5分钟过期
|
|
|
int timeout = 5;
|
|
|
final String key = "verifyCode:" + officialEmail;
|
|
|
+ // 存储验证码到Redis并设置过期时间
|
|
|
redisTemplate.opsForValue().set(key, code, timeout, TimeUnit.MINUTES);
|
|
|
+ // 设置请求间隔标记,防止频繁请求
|
|
|
+ redisTemplate.opsForValue().set(intervalKey, "requested", SEND_INTERVAL, TimeUnit.SECONDS);
|
|
|
|
|
|
emailService.sendVerifyCodeEmail(officialEmail, code, timeout);
|
|
|
}
|