feat(backend): 注册限流阈值改为可配置

This commit is contained in:
Zhou Weidong committed 2026-10-17 23:22:28 +08:00
1 parent 3403a521eb
commit 758eb69f55
5 files changed
+73 -11

No files matched your search

@@ -25,6 +25,7 @@ import com.fruitshorts.user.vo.TokenRespVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.util.ReflectionTestUtils;
import java.time.Duration;
import java.time.LocalDateTime;
@@ -164,6 +165,7 @@ class AppAuthServiceTest {
@Test
void should_reject_register_when_ip_reaches_the_daily_limit() {
setRegisterLimits(5, 3);
given(userMapper.selectCount(any())).willReturn(5L);
assertThatThrownBy(() -> authService.register(emailRegister("abcd1234", null), "203.0.113.8"))
@@ -173,6 +175,38 @@ class AppAuthServiceTest {
.hasMessageContaining("当前网络注册过于频繁");
}
@Test
void should_reject_register_when_device_reaches_the_daily_limit() {
setRegisterLimits(5, 3);
given(userMapper.selectCount(any())).willReturn(3L);
assertThatThrownBy(() -> authService.register(emailRegister("abcd1234", null), "203.0.113.8"))
.isInstanceOf(ServiceException.class)
.satisfies(ex -> assertThat(((ServiceException) ex).getCode())
.isEqualTo(ErrorCode.TOO_MANY_REQUESTS.getCode()))
.hasMessage("该设备注册过于频繁,请稍后再试");
}
@Test
void should_not_limit_by_ip_when_ip_limit_is_zero() {
stubHappyRegister();
setRegisterLimits(0, 3);
given(userMapper.selectCount(any())).willReturn(2L);
assertThat(authService.register(emailRegister("abcd1234", null), "203.0.113.8").getAccessToken())
.isEqualTo("access-1");
}
@Test
void should_not_limit_by_device_when_device_limit_is_zero() {
stubHappyRegister();
setRegisterLimits(5, 0);
given(userMapper.selectCount(any())).willReturn(4L);
assertThat(authService.register(emailRegister("abcd1234", null), "203.0.113.8").getAccessToken())
.isEqualTo("access-1");
}
@Test
void should_return_tokens_when_password_matches() {
stubLogin(credential("bcrypt-hash"), user(AppUserStatus.NORMAL));
@@ -268,6 +302,11 @@ class AppAuthServiceTest {
deviceMapper, realOtpService, hasher, tokenProvider, passwordEncoder);
}
private void setRegisterLimits(int perIp, int perDevice) {
ReflectionTestUtils.setField(authService, "maxRegisterPerIpPerDay", perIp);
ReflectionTestUtils.setField(authService, "maxRegisterPerDevicePerDay", perDevice);
}
private RegisterReqVO emailRegister(String password, String code) {
RegisterReqVO req = new RegisterReqVO();
req.setTargetType("EMAIL");