feat: phase1 UI prep — P1 安全(XFF防护), P2 规模化(平台索引+region保护), P3 文档补全

P1 安全: WebUtils.getClientIp 改为 remoteAddr 优先 + 可信代理 CIDR 配置
P2 规模化: DISTINCT ON 查询补匹配排序的部分索引 (migrate-k113)
P2 一致性: syncCountryByIp regionCode 同语言/时区/币种加保护,不覆盖用户自定义
P3 文档: api-phase1.md 新增 platform 参数说明, IpRegionService 新增集成测试 + VERSION
新增: CountryProfile 52 国映射 + IpRegionService 离线 ip2region 解析
平台筛选: app-users/favorites/likes/watch-history 按最近一次会话 ANDROID/IOS 筛选
This commit is contained in:
Vicky authored and trae-solo-agent committed 2026-10-27 15:45:15 +08:00
1 parent a41ab18636
commit 272aa62434
34 files changed
+748 -77

No files matched your search

+1
View File
@@ -19,3 +19,4 @@ data/uploads/*
# 部署用的真实环境变量(含密钥),只提交 .env.example # 部署用的真实环境变量(含密钥),只提交 .env.example
.env .env
dump.rdb
+6 -4
View File
@@ -115,6 +115,8 @@ POST /app/auth/register
| 密码强度 | 8–64 位,且**同时包含字母与数字**(不强制特殊字符:低端机输入成本高,拦机器注册靠频控) | | 密码强度 | 8–64 位,且**同时包含字母与数字**(不强制特殊字符:低端机输入成本高,拦机器注册靠频控) |
| 注册频控 | 同 IP / 同设备 24h 默认上限分别为 5 / 3 个,超出返回 `429`(`TOO_MANY_REQUESTS`) | | 注册频控 | 同 IP / 同设备 24h 默认上限分别为 5 / 3 个,超出返回 `429`(`TOO_MANY_REQUESTS`) |
| 邮箱验证状态 | 免码注册时 `app_user_credential.verified = 0`(保留"待验证"),**不阻塞登录**;只有**验证码登录**会把 `verified` 置 1,密码登录不改变该状态 | | 邮箱验证状态 | 免码注册时 `app_user_credential.verified = 0`(保留"待验证"),**不阻塞登录**;只有**验证码登录**会把 `verified` 置 1,密码登录不改变该状态 |
| 国家 / 语言 / 时区 / 币种 | 优先按客户端 IP(`X-Forwarded-For` / `X-Real-IP`,离线 ip2region)解析国家;内网或解析失败才用请求体 `countryCode`(ISO-2),最后兜底 `ID`。`language` / `timezone` / `currency` 随国家映射,不再写死 `id-ID` / `IDR` |
| 登录时修正国家 | `/app/auth/login`、`/app/auth/google` 会用 IP 重新解析国家并更新 `country_code` / `region_code`(历史账号下次登录即自愈);`language` / `timezone` / `currency` 只在仍是旧国家映射值时才同步,用户自己改过就保留 |
频控口径落库在 `app_user.register_ip` / `app_user.register_device_id` 上(按 24h 计数,不新建计数表)。 频控口径落库在 `app_user.register_ip` / `app_user.register_device_id` 上(按 24h 计数,不新建计数表)。
@@ -863,13 +865,13 @@ GET /app/notices?pageIndex=1&pageSize=20
| 方法 | 路径 | 权限点 | 说明 | | 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| GET | `/admin/app-users/page` | `app-user:list` | 检索:keyword(uid/昵称/手机号/邮箱)、status、countryCode、registerSource | | GET | `/admin/app-users/page` | `app-user:list` | 检索:keyword(uid/昵称/手机号/邮箱)、status、countryCode、registerSource、platform(ANDROID/IOS,按用户**最近一次**会话平台筛选) |
| GET | `/admin/app-users/{id}` | `app-user:list` | 详情 | | GET | `/admin/app-users/{id}` | `app-user:list` | 详情 |
| GET | `/admin/app-users/{id}/ban-records` | `app-user:list` | 封禁与申诉记录 | | GET | `/admin/app-users/{id}/ban-records` | `app-user:list` | 封禁与申诉记录 |
| GET | `/admin/app-users/{id}/watch-history` | `app-user:list` | 观看流水明细(带剧名/集号,客服核对用) | | GET | `/admin/app-users/{id}/watch-history` | `app-user:list` | 观看流水明细(带剧名/集号,客服核对用) |
| GET | `/admin/watch-history/page` | `watch-history:list` | 跨用户观看记录分页:keyword、userId、dramaTitle、dramaId、episodeId、source、finished、startTime、endTime | | GET | `/admin/watch-history/page` | `watch-history:list` | 跨用户观看记录分页:keyword、userId、dramaTitle、dramaId、episodeId、source、finished、startTime、endTime、platform(ANDROID/IOS,按**最近一次会话**) |
| GET | `/admin/favorites/page` | `favorite:list` | 收藏只读分页,含游客 | | GET | `/admin/favorites/page` | `favorite:list` | 收藏只读分页,含游客;支持 platform 筛选(ANDROID/IOS,按**最近一次会话**) |
| GET | `/admin/likes/page` | `like:list` | 点赞只读分页,含游客及多态目标 | | GET | `/admin/likes/page` | `like:list` | 点赞只读分页,含游客及多态目标;支持 platform 筛选(ANDROID/IOS,按**最近一次会话**) |
| PUT | `/admin/app-users/{id}/status` | `app-user:update` | 改状态:normal/limited/banned | | PUT | `/admin/app-users/{id}/status` | `app-user:update` | 改状态:normal/limited/banned |
状态处置会**立即吊销该用户全部会话**并写入封禁记录,避免"封了还能用"。 状态处置会**立即吊销该用户全部会话**并写入封禁记录,避免"封了还能用"。
@@ -32,12 +32,13 @@ import java.util.List;
public class AuthController { public class AuthController {
private final AuthService authService; private final AuthService authService;
private final WebUtils webUtils;
@Operation(summary = "管理端登录") @Operation(summary = "管理端登录")
@PostMapping("/login") @PostMapping("/login")
@OperationLog(module = "认证", action = "登录") @OperationLog(module = "认证", action = "登录")
public Result<LoginRespVO> login(@Valid @RequestBody LoginReqVO req, HttpServletRequest request) { public Result<LoginRespVO> login(@Valid @RequestBody LoginReqVO req, HttpServletRequest request) {
return Result.ok(authService.login(req, WebUtils.getClientIp(request))); return Result.ok(authService.login(req, webUtils.clientIp(request)));
} }
/** 当前用户的菜单路由树,结构与前端 element-plus-admin 的动态路由一致。 */ /** 当前用户的菜单路由树,结构与前端 element-plus-admin 的动态路由一致。 */
@@ -40,6 +40,11 @@ mybatis-plus:
datacenter-id: 1 datacenter-id: 1
fruitshorts: fruitshorts:
web:
# 可信代理 CIDR 列表(逗号分隔)。默认空 = 永不解析 XFF,直接用 request.getRemoteAddr()。
# 配了反代(Nginx/K8s ingress)时填上其 IP 段,才会从 XFF 取最右侧可信一跳。
# 生产若开启了 Tomcat RemoteIpValve(prod profile 已配),保持空即可。
trusted-proxies: ${FRUITSHORTS_TRUSTED_PROXIES:}
media: media:
# 媒资目录:容器里指向挂载卷;本地默认 ./data/uploads # 媒资目录:容器里指向挂载卷;本地默认 ./data/uploads
root-dir: ${MEDIA_ROOT_DIR:./data/uploads} root-dir: ${MEDIA_ROOT_DIR:./data/uploads}
@@ -30,7 +30,9 @@ public final class ControllerContractSupport {
/** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */ /** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static MockMvc mockMvcOf(Object controller) { public static MockMvc mockMvcOf(Object controller) {
AccessDeniedRecorder recorder = new AccessDeniedRecorder(Mockito.mock(ObjectProvider.class)); AccessDeniedRecorder recorder = new AccessDeniedRecorder(
Mockito.mock(ObjectProvider.class),
Mockito.mock(ObjectProvider.class));
return MockMvcBuilders.standaloneSetup(controller) return MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(new GlobalExceptionHandler(recorder)) .setControllerAdvice(new GlobalExceptionHandler(recorder))
// 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组, // 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组,
@@ -35,13 +35,14 @@ public class AppAuthController {
private final AppOtpService otpService; private final AppOtpService otpService;
private final AppAuthService authService; private final AppAuthService authService;
private final WebUtils webUtils;
/** 发送验证码。频控在服务端,客户端不需要自己限流。 */ /** 发送验证码。频控在服务端,客户端不需要自己限流。 */
@Operation(summary = "发送验证码(频控在服务端)") @Operation(summary = "发送验证码(频控在服务端)")
@RateLimit(limit = 20, windowSeconds = 60, key = "otp") @RateLimit(limit = 20, windowSeconds = 60, key = "otp")
@PostMapping("/otp") @PostMapping("/otp")
public Result<Void> sendOtp(@Valid @RequestBody OtpSendReqVO req, HttpServletRequest request) { public Result<Void> sendOtp(@Valid @RequestBody OtpSendReqVO req, HttpServletRequest request) {
otpService.send(req, WebUtils.getClientIp(request)); otpService.send(req, webUtils.clientIp(request));
return Result.ok(); return Result.ok();
} }
@@ -50,7 +51,7 @@ public class AppAuthController {
public Result<TokenRespVO> register(@Valid @RequestBody RegisterReqVO req, public Result<TokenRespVO> register(@Valid @RequestBody RegisterReqVO req,
HttpServletRequest request) { HttpServletRequest request) {
applyHeaderDeviceId(req, request); applyHeaderDeviceId(req, request);
return Result.ok(authService.register(req, WebUtils.getClientIp(request))); return Result.ok(authService.register(req, webUtils.clientIp(request)));
} }
@Operation(summary = "登录(验证码或密码)") @Operation(summary = "登录(验证码或密码)")
@@ -59,7 +60,7 @@ public class AppAuthController {
public Result<TokenRespVO> login(@Valid @RequestBody LoginReqVO req, public Result<TokenRespVO> login(@Valid @RequestBody LoginReqVO req,
HttpServletRequest request) { HttpServletRequest request) {
applyHeaderDeviceId(req, request); applyHeaderDeviceId(req, request);
return Result.ok(authService.login(req, WebUtils.getClientIp(request))); return Result.ok(authService.login(req, webUtils.clientIp(request)));
} }
@Operation(summary = "Google 登录(未配置 clientId 时返回明确错误)") @Operation(summary = "Google 登录(未配置 clientId 时返回明确错误)")
@@ -69,7 +70,8 @@ public class AppAuthController {
String headerDeviceId = request.getHeader("X-Device-Id"); String headerDeviceId = request.getHeader("X-Device-Id");
String deviceId = StringUtils.hasText(headerDeviceId) String deviceId = StringUtils.hasText(headerDeviceId)
? headerDeviceId : req.getDeviceId(); ? headerDeviceId : req.getDeviceId();
return Result.ok(authService.googleLogin(req.getIdToken(), deviceId)); return Result.ok(authService.googleLogin(req.getIdToken(), deviceId,
webUtils.clientIp(request)));
} }
@Operation(summary = "刷新令牌(旧 refresh token 立即失效)") @Operation(summary = "刷新令牌(旧 refresh token 立即失效)")
@@ -48,6 +48,7 @@ public class AppCommentController {
private final EpisodeService episodeService; private final EpisodeService episodeService;
private final InteractionIdentityResolver identityResolver; private final InteractionIdentityResolver identityResolver;
private final AnonymousInteractionRateLimiter anonymousRateLimiter; private final AnonymousInteractionRateLimiter anonymousRateLimiter;
private final WebUtils webUtils;
@Operation(summary = "发布评论") @Operation(summary = "发布评论")
@PostMapping @PostMapping
@@ -59,7 +60,7 @@ public class AppCommentController {
req.getDeviceId()); req.getDeviceId());
anonymousRateLimiter.check(identity, "comment"); anonymousRateLimiter.check(identity, "comment");
return Result.ok(commentService.publish( return Result.ok(commentService.publish(
identity, req, WebUtils.getClientIp(request))); identity, req, webUtils.clientIp(request)));
} }
@Operation(summary = "评论列表(游标翻页,可匿名浏览)") @Operation(summary = "评论列表(游标翻页,可匿名浏览)")
@@ -37,6 +37,7 @@ public class AppDramaController {
private final EpisodeService episodeService; private final EpisodeService episodeService;
private final CommentService commentService; private final CommentService commentService;
private final AppEpisodeStatsService appEpisodeStatsService; private final AppEpisodeStatsService appEpisodeStatsService;
private final WebUtils webUtils;
/** 详情:包含剧集列表,客户端进详情页一次请求即可渲染 */ /** 详情:包含剧集列表,客户端进详情页一次请求即可渲染 */
@Operation(summary = "短剧详情(含剧集列表,进详情页一次请求即可渲染)") @Operation(summary = "短剧详情(含剧集列表,进详情页一次请求即可渲染)")
@@ -56,7 +57,7 @@ public class AppDramaController {
SecurityUtils.getUserIdOrNull(), SecurityUtils.getUserIdOrNull(),
id, id,
request.getHeader("X-Device-Id"), request.getHeader("X-Device-Id"),
WebUtils.getClientIp(request)); webUtils.clientIp(request));
DramaEpisode episode = episodeService.getExisting(id); DramaEpisode episode = episodeService.getExisting(id);
vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount()); vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount());
vo.setCommentCount(commentService.countByEpisodes(List.of(id)).getOrDefault(id, 0L)); vo.setCommentCount(commentService.countByEpisodes(List.of(id)).getOrDefault(id, 0L));
@@ -25,11 +25,12 @@ import org.springframework.web.bind.annotation.RestController;
public class AppEventController { public class AppEventController {
private final AppEventService eventService; private final AppEventService eventService;
private final WebUtils webUtils;
@Operation(summary = "埋点事件批量上报") @Operation(summary = "埋点事件批量上报")
@PostMapping("/events") @PostMapping("/events")
public Result<Void> report(@Valid @RequestBody AppEventReqVO req, HttpServletRequest request) { public Result<Void> report(@Valid @RequestBody AppEventReqVO req, HttpServletRequest request) {
eventService.save(req, SecurityUtils.getUserIdOrNull(), WebUtils.getClientIp(request)); eventService.save(req, SecurityUtils.getUserIdOrNull(), webUtils.clientIp(request));
return Result.ok(); return Result.ok();
} }
} }
@@ -47,6 +47,11 @@ springdoc:
path: /v3/api-docs path: /v3/api-docs
fruitshorts: fruitshorts:
web:
# 可信代理 CIDR 列表(逗号分隔)。默认空 = 永不解析 XFF,直接用 request.getRemoteAddr()。
# 配了反代(Nginx/K8s ingress)时填上其 IP 段,才会从 XFF 取最右侧可信一跳。
# 生产若开启了 Tomcat RemoteIpValve(prod profile 已配),保持空即可。
trusted-proxies: ${FRUITSHORTS_TRUSTED_PROXIES:}
auth: auth:
# 仅作 sys_config 缺失/非法时的兜底;运行时优先读取后台「系统配置」 # 仅作 sys_config 缺失/非法时的兜底;运行时优先读取后台「系统配置」
register-max-per-ip-per-day: ${REGISTER_MAX_PER_IP_PER_DAY:5} register-max-per-ip-per-day: ${REGISTER_MAX_PER_IP_PER_DAY:5}
@@ -4,6 +4,7 @@ package com.fruitshorts.app.controller;
import com.fruitshorts.app.support.ControllerContractSupport; import com.fruitshorts.app.support.ControllerContractSupport;
import com.fruitshorts.common.exception.ErrorCode; import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException; import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.framework.web.WebUtils;
import com.fruitshorts.user.service.AppAuthService; import com.fruitshorts.user.service.AppAuthService;
import com.fruitshorts.user.service.AppOtpService; import com.fruitshorts.user.service.AppOtpService;
import com.fruitshorts.user.vo.TokenRespVO; import com.fruitshorts.user.vo.TokenRespVO;
@@ -32,13 +33,15 @@ class AppAuthControllerContractTest {
private AppOtpService otpService; private AppOtpService otpService;
private AppAuthService authService; private AppAuthService authService;
private WebUtils webUtils;
private MockMvc mockMvc; private MockMvc mockMvc;
@BeforeEach @BeforeEach
void setUp() { void setUp() {
otpService = mock(AppOtpService.class); otpService = mock(AppOtpService.class);
authService = mock(AppAuthService.class); authService = mock(AppAuthService.class);
mockMvc = ControllerContractSupport.mockMvcOf(new AppAuthController(otpService, authService)); webUtils = mock(WebUtils.class);
mockMvc = ControllerContractSupport.mockMvcOf(new AppAuthController(otpService, authService, webUtils));
} }
@Test @Test
@@ -51,7 +51,8 @@ class AppCatalogControllerContractTest {
dramaMvc = ControllerContractSupport.mockMvcOf( dramaMvc = ControllerContractSupport.mockMvcOf(
new AppDramaController(catalogService, mock(PlaybackService.class), new AppDramaController(catalogService, mock(PlaybackService.class),
mock(EpisodeService.class), mock(CommentService.class), mock(EpisodeService.class), mock(CommentService.class),
mock(AppEpisodeStatsService.class))); mock(AppEpisodeStatsService.class),
mock(com.fruitshorts.framework.web.WebUtils.class)));
} }
@Test @Test
@@ -38,7 +38,8 @@ class AppCommentControllerContractTest {
commentService, commentService,
episodeService, episodeService,
mock(InteractionIdentityResolver.class), mock(InteractionIdentityResolver.class),
mock(AnonymousInteractionRateLimiter.class))); mock(AnonymousInteractionRateLimiter.class),
mock(com.fruitshorts.framework.web.WebUtils.class)));
} }
@Test @Test
@@ -234,7 +234,8 @@ class AppCommentCountAnonymousSecurityTest {
commentService, commentService,
episodeService, episodeService,
identityResolver, identityResolver,
rateLimiter); rateLimiter,
mock(com.fruitshorts.framework.web.WebUtils.class));
} }
@Bean @Bean
@@ -303,7 +304,8 @@ class AppCommentCountAnonymousSecurityTest {
mock(PlaybackService.class), mock(PlaybackService.class),
episodeService, episodeService,
commentService, commentService,
appEpisodeStatsService); appEpisodeStatsService,
mock(com.fruitshorts.framework.web.WebUtils.class));
} }
@Bean @Bean
@@ -340,7 +342,7 @@ class AppCommentCountAnonymousSecurityTest {
RestAuthEntryPoint restAuthEntryPoint(ObjectMapper objectMapper) { RestAuthEntryPoint restAuthEntryPoint(ObjectMapper objectMapper) {
return new RestAuthEntryPoint( return new RestAuthEntryPoint(
objectMapper, objectMapper,
new AccessDeniedRecorder(mock(ObjectProvider.class))); new AccessDeniedRecorder(mock(ObjectProvider.class), mock(ObjectProvider.class)));
} }
@Bean @Bean
@@ -54,7 +54,8 @@ class AppPlaybackContractTest {
given(commentService.countByEpisodes(any())).willReturn(Map.of()); given(commentService.countByEpisodes(any())).willReturn(Map.of());
mockMvc = ControllerContractSupport.mockMvcOf( mockMvc = ControllerContractSupport.mockMvcOf(
new AppDramaController(mock(AppCatalogService.class), playbackService, new AppDramaController(mock(AppCatalogService.class), playbackService,
episodeService, commentService, episodeStatsService)); episodeService, commentService, episodeStatsService,
mock(com.fruitshorts.framework.web.WebUtils.class)));
} }
@Test @Test
@@ -22,6 +22,7 @@ import com.fruitshorts.user.service.AppOtpService;
import com.fruitshorts.user.service.CredentialHasher; import com.fruitshorts.user.service.CredentialHasher;
import com.fruitshorts.user.service.GoogleIdTokenVerifier; import com.fruitshorts.user.service.GoogleIdTokenVerifier;
import com.fruitshorts.user.service.GoogleUser; import com.fruitshorts.user.service.GoogleUser;
import com.fruitshorts.user.service.IpRegionService;
import com.fruitshorts.user.service.OtpSender; import com.fruitshorts.user.service.OtpSender;
import com.fruitshorts.user.vo.LoginReqVO; import com.fruitshorts.user.vo.LoginReqVO;
import com.fruitshorts.user.vo.RegisterReqVO; import com.fruitshorts.user.vo.RegisterReqVO;
@@ -67,6 +68,7 @@ class AppAuthServiceTest {
private ConfigService configService; private ConfigService configService;
private GoogleIdTokenVerifier googleVerifier; private GoogleIdTokenVerifier googleVerifier;
private ApplicationEventPublisher eventPublisher; private ApplicationEventPublisher eventPublisher;
private IpRegionService ipRegionService;
private AppAuthService authService; private AppAuthService authService;
@BeforeEach @BeforeEach
@@ -83,11 +85,14 @@ class AppAuthServiceTest {
configService = mock(ConfigService.class); configService = mock(ConfigService.class);
googleVerifier = mock(GoogleIdTokenVerifier.class); googleVerifier = mock(GoogleIdTokenVerifier.class);
eventPublisher = mock(ApplicationEventPublisher.class); eventPublisher = mock(ApplicationEventPublisher.class);
ipRegionService = mock(IpRegionService.class);
given(configService.get(anyString(), anyString())) given(configService.get(anyString(), anyString()))
.willAnswer(invocation -> invocation.getArgument(1)); .willAnswer(invocation -> invocation.getArgument(1));
// 单测里默认解析不出国家,走客户端区域 / 印尼兜底
given(ipRegionService.resolveCountry(any())).willReturn("");
authService = new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper, authService = new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper,
deviceMapper, otpService, hasher, tokenProvider, passwordEncoder, configService, deviceMapper, otpService, hasher, tokenProvider, passwordEncoder, configService,
googleVerifier, eventPublisher); googleVerifier, eventPublisher, ipRegionService);
} }
@Test @Test
@@ -264,6 +269,41 @@ class AppAuthServiceTest {
assertThat(event.deviceId()).isEqualTo("device-9"); assertThat(event.deviceId()).isEqualTo("device-9");
} }
@Test
void should_sync_country_from_ip_on_login() {
stubLogin(credential("bcrypt-hash"), user(AppUserStatus.NORMAL));
given(passwordEncoder.matches("abcd1234", "bcrypt-hash")).willReturn(true);
given(ipRegionService.resolveCountry(any())).willReturn("TH");
authService.login(emailLogin("abcd1234"), "49.237.8.1");
ArgumentCaptor<AppUser> captor = ArgumentCaptor.forClass(AppUser.class);
verify(userMapper).updateById(captor.capture());
AppUser saved = captor.getValue();
assertThat(saved.getCountryCode()).isEqualTo("TH");
assertThat(saved.getRegionCode()).isEqualTo("TH");
assertThat(saved.getLanguage()).isEqualTo("en-US");
assertThat(saved.getTimezone()).isEqualTo("Asia/Bangkok");
assertThat(saved.getCurrency()).isEqualTo("THB");
}
@Test
void should_keep_user_customized_language_when_syncing_country() {
AppUser user = user(AppUserStatus.NORMAL);
user.setLanguage("zh-CN");
stubLogin(credential("bcrypt-hash"), user);
given(passwordEncoder.matches("abcd1234", "bcrypt-hash")).willReturn(true);
given(ipRegionService.resolveCountry(any())).willReturn("TH");
authService.login(emailLogin("abcd1234"), "49.237.8.1");
ArgumentCaptor<AppUser> captor = ArgumentCaptor.forClass(AppUser.class);
verify(userMapper).updateById(captor.capture());
assertThat(captor.getValue().getCountryCode()).isEqualTo("TH");
// 用户自己改过的语言不被 IP 覆盖
assertThat(captor.getValue().getLanguage()).isEqualTo("zh-CN");
}
@Test @Test
void should_reject_login_when_password_does_not_match() { void should_reject_login_when_password_does_not_match() {
stubLogin(credential("bcrypt-hash"), user(AppUserStatus.NORMAL)); stubLogin(credential("bcrypt-hash"), user(AppUserStatus.NORMAL));
@@ -318,7 +358,7 @@ class AppAuthServiceTest {
}); });
given(userMapper.selectById(any())).willAnswer(invocation -> inserted.get()); given(userMapper.selectById(any())).willAnswer(invocation -> inserted.get());
TokenRespVO resp = authService.googleLogin("google-id-token", "device-9"); TokenRespVO resp = authService.googleLogin("google-id-token", "device-9", "203.0.113.9");
assertThat(resp.getAccessToken()).isEqualTo("access-1"); assertThat(resp.getAccessToken()).isEqualTo("access-1");
assertThat(resp.isNewUser()).isTrue(); assertThat(resp.isNewUser()).isTrue();
@@ -333,7 +373,7 @@ class AppAuthServiceTest {
given(googleVerifier.verify(anyString())) given(googleVerifier.verify(anyString()))
.willReturn(new GoogleUser("sub-1", "", "Alice", "")); .willReturn(new GoogleUser("sub-1", "", "Alice", ""));
assertThatThrownBy(() -> authService.googleLogin("google-id-token", "device-9")) assertThatThrownBy(() -> authService.googleLogin("google-id-token", "device-9", "203.0.113.9"))
.isInstanceOf(ServiceException.class) .isInstanceOf(ServiceException.class)
.hasMessage("Google 账号未返回邮箱,无法登录"); .hasMessage("Google 账号未返回邮箱,无法登录");
} }
@@ -392,7 +432,7 @@ class AppAuthServiceTest {
AppOtpService realOtpService = new AppOtpService(otpMapper, mock(OtpSender.class), otpHasher); AppOtpService realOtpService = new AppOtpService(otpMapper, mock(OtpSender.class), otpHasher);
return new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper, return new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper,
deviceMapper, realOtpService, hasher, tokenProvider, passwordEncoder, configService, deviceMapper, realOtpService, hasher, tokenProvider, passwordEncoder, configService,
googleVerifier, eventPublisher); googleVerifier, eventPublisher, ipRegionService);
} }
private void setRegisterLimits(int perIp, int perDevice) { private void setRegisterLimits(int perIp, int perDevice) {
@@ -0,0 +1,42 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.user.enums.CountryProfile;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/** 国家解析与映射:IP 库文本 → ISO-2,再据此选语言/时区/币种。 */
class CountryProfileTest {
@Test
void should_map_ip_region_text_to_iso_code() {
assertThat(CountryProfile.fromIpRegion("中国|0|广东省|深圳市|电信")).isEqualTo("CN");
assertThat(CountryProfile.fromIpRegion("中国|0|台湾省|0|中华电信")).isEqualTo("TW");
assertThat(CountryProfile.fromIpRegion("中国|0|香港|0|0")).isEqualTo("HK");
assertThat(CountryProfile.fromIpRegion("中国|0|澳门|0|澳门电讯")).isEqualTo("MO");
assertThat(CountryProfile.fromIpRegion("美国|0|0|0|Level3")).isEqualTo("US");
assertThat(CountryProfile.fromIpRegion("印度尼西亚|0|大雅加达|雅加达|0")).isEqualTo("ID");
}
@Test
void should_return_empty_for_private_ip_and_unknown_country() {
assertThat(CountryProfile.fromIpRegion("0|0|0|内网IP|内网IP")).isEmpty();
assertThat(CountryProfile.fromIpRegion("")).isEmpty();
// 未收录的国家交给上层回退到客户端区域
assertThat(CountryProfile.fromIpRegion("津巴布韦|0|0|0|0")).isEmpty();
}
@Test
void should_normalize_client_region_and_fallback_to_default() {
assertThat(CountryProfile.normalizeClientCode(" id ")).isEqualTo("ID");
assertThat(CountryProfile.normalizeClientCode("us")).isEqualTo("US");
assertThat(CountryProfile.normalizeClientCode("XX")).isEmpty();
assertThat(CountryProfile.normalizeClientCode("")).isEmpty();
assertThat(CountryProfile.of("US").currency()).isEqualTo("USD");
assertThat(CountryProfile.of("US").language()).isEqualTo("en-US");
assertThat(CountryProfile.of("").code()).isEqualTo("ID");
assertThat(CountryProfile.of("").currency()).isEqualTo("IDR");
}
}
@@ -0,0 +1,49 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.user.service.IpRegionService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* IpRegionService 集成测试:真实 xdb 文件 + 真实 resolve。
*
* <p>xdb 在 fruitshorts-module-user 的 resources/ip2region/ip2region.xdb 下(11MB),
* 打包后会进 app-api 的 classpath。这个测试验证 Service 层调 ip2region 库的行为——
* 合法公网 IP → ISO-2 国家码,内网/保留地址/空 → 空串。
*/
class IpRegionServiceTest {
private IpRegionService service;
@BeforeEach
void setUp() {
service = new IpRegionService();
}
@Test
void should_resolve_known_public_ips() {
assertThat(service.resolveCountry("8.8.8.8")).isEqualTo("US");
assertThat(service.resolveCountry("114.114.114.114")).isEqualTo("CN");
}
@Test
void should_return_empty_for_private_loopback_and_reserved() {
assertThat(service.resolveCountry("127.0.0.1")).isEmpty();
assertThat(service.resolveCountry("0.0.0.0")).isEmpty();
assertThat(service.resolveCountry("10.0.0.1")).isEmpty();
assertThat(service.resolveCountry("192.168.1.1")).isEmpty();
assertThat(service.resolveCountry("172.16.0.1")).isEmpty();
assertThat(service.resolveCountry("169.254.1.1")).isEmpty();
}
@Test
void should_return_empty_for_invalid_inputs() {
assertThat(service.resolveCountry("")).isEmpty();
assertThat(service.resolveCountry(null)).isEmpty();
assertThat(service.resolveCountry("not-an-ip")).isEmpty();
assertThat(service.resolveCountry("999.999.999.999")).isEmpty();
}
}
@@ -2,6 +2,7 @@
package com.fruitshorts.app.support; package com.fruitshorts.app.support;
import com.fruitshorts.framework.log.AccessDeniedRecorder; import com.fruitshorts.framework.log.AccessDeniedRecorder;
import com.fruitshorts.framework.web.WebUtils;
import com.fruitshorts.framework.web.JacksonLongToStringConfig; import com.fruitshorts.framework.web.JacksonLongToStringConfig;
import com.fruitshorts.framework.web.GlobalExceptionHandler; import com.fruitshorts.framework.web.GlobalExceptionHandler;
import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializationFeature;
@@ -30,7 +31,9 @@ public final class ControllerContractSupport {
/** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */ /** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static MockMvc mockMvcOf(Object controller) { public static MockMvc mockMvcOf(Object controller) {
AccessDeniedRecorder recorder = new AccessDeniedRecorder(Mockito.mock(ObjectProvider.class)); AccessDeniedRecorder recorder = new AccessDeniedRecorder(
Mockito.mock(ObjectProvider.class),
Mockito.mock(ObjectProvider.class));
return MockMvcBuilders.standaloneSetup(controller) return MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(new GlobalExceptionHandler(recorder)) .setControllerAdvice(new GlobalExceptionHandler(recorder))
// 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组, // 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组,
@@ -22,6 +22,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
public class AccessDeniedRecorder { public class AccessDeniedRecorder {
private final ObjectProvider<OperationLogSink> sinkProvider; private final ObjectProvider<OperationLogSink> sinkProvider;
private final ObjectProvider<WebUtils> webUtilsProvider;
public void record(HttpServletRequest request) { public void record(HttpServletRequest request) {
OperationLogSink sink = sinkProvider.getIfAvailable(); OperationLogSink sink = sinkProvider.getIfAvailable();
@@ -47,10 +48,16 @@ public class AccessDeniedRecorder {
.status("FAIL") .status("FAIL")
.errorMsg("无权限") .errorMsg("无权限")
.durationMs(0) .durationMs(0)
.ip(request == null ? "" : WebUtils.getClientIp(request)) .ip(request == null ? "" : clientIp(request))
.build()); .build());
} }
/** 优先用 Spring 注入的 WebUtils(尊重可信代理配置),拿不到回退静态方法。 */
private String clientIp(HttpServletRequest request) {
WebUtils webUtils = webUtilsProvider.getIfAvailable();
return webUtils != null ? webUtils.clientIp(request) : WebUtils.getClientIp(request);
}
/** 从当前线程取出请求,供全局异常处理使用。 */ /** 从当前线程取出请求,供全局异常处理使用。 */
public void recordCurrentRequest() { public void recordCurrentRequest() {
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes) { if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes) {
@@ -43,6 +43,7 @@ public class OperationLogAspect {
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final ObjectProvider<OperationLogSink> sinkProvider; private final ObjectProvider<OperationLogSink> sinkProvider;
private final ObjectProvider<WebUtils> webUtilsProvider;
@Around("@annotation(operationLog)") @Around("@annotation(operationLog)")
public Object around(ProceedingJoinPoint point, OperationLog operationLog) throws Throwable { public Object around(ProceedingJoinPoint point, OperationLog operationLog) throws Throwable {
@@ -86,10 +87,16 @@ public class OperationLogAspect {
.status(error == null ? "SUCCESS" : "FAIL") .status(error == null ? "SUCCESS" : "FAIL")
.errorMsg(error == null ? "" : truncate(error.getMessage())) .errorMsg(error == null ? "" : truncate(error.getMessage()))
.durationMs(durationMs) .durationMs(durationMs)
.ip(request == null ? "" : WebUtils.getClientIp(request)) .ip(request == null ? "" : clientIp(request))
.build()); .build());
} }
/** 优先用 Spring 注入的 WebUtils(尊重可信代理配置),拿不到回退静态方法。 */
private String clientIp(HttpServletRequest request) {
WebUtils webUtils = webUtilsProvider.getIfAvailable();
return webUtils != null ? webUtils.clientIp(request) : WebUtils.getClientIp(request);
}
/** 把方法入参整理成 JSON,文件只记名称和大小。 */ /** 把方法入参整理成 JSON,文件只记名称和大小。 */
private String body(ProceedingJoinPoint point) { private String body(ProceedingJoinPoint point) {
Object[] args = point.getArgs(); Object[] args = point.getArgs();
@@ -62,6 +62,8 @@ public final class ImpersonationGuard {
public static String clientIp() { public static String clientIp() {
HttpServletRequest request = currentRequest(); HttpServletRequest request = currentRequest();
// 这里走静态 getClientIp——等价于 trusted-proxies 为空时的逻辑(只用 remoteAddr,不解析 XFF)。
// 这个类是纯静态工具(无 Spring 注入),且只在 Creator 代看场景用,安全影响低。
return request == null ? "" : com.fruitshorts.framework.web.WebUtils.getClientIp(request); return request == null ? "" : com.fruitshorts.framework.web.WebUtils.getClientIp(request);
} }
@@ -3,25 +3,146 @@
package com.fruitshorts.framework.web; package com.fruitshorts.framework.web;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
public final class WebUtils { import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
/**
* 取真实客户端 IP。
*
* <p>安全策略:默认信任 {@link HttpServletRequest#getRemoteAddr()} 本身,只有当
* 它属于配置的可信代理 CIDR 时才解析 X-Forwarded-For / X-Real-IP 等头。
* 这样客户端伪造的 XFF 不会生效,只有经 Nginx / K8s ingress 等前置代理转发的请求
* 才能带上可信的 XFF 链。
*
* <p>生产建议:同时开启 Tomcat RemoteIpValve(prod profile 已配置),让
* {@code getRemoteAddr()} 在经过代理后直接就是客户端真实 IP。此时可信代理列表
* 配成空即可,Valve 已经帮我们做了 XFF 解析。
*/
@Slf4j
@Component
public class WebUtils {
private static final String UNKNOWN = "unknown"; private static final String UNKNOWN = "unknown";
private static final String[] PROXY_HEADERS = {"X-Forwarded-For", "X-Real-IP",
"Proxy-Client-IP", "WL-Proxy-Client-IP"};
private WebUtils() { /** 可信代理 CIDR 列表,逗号分隔;空表示永不解析 XFF,直接用 remoteAddr。 */
@Value("${fruitshorts.web.trusted-proxies:}")
private String trustedProxies = "";
/** 纯静态调用路径(不依赖 Spring),供测试或无 IoC 场景使用。 */
public static String getClientIp(HttpServletRequest request) {
return resolve(request, List.of());
} }
/** 取真实客户端 IP,兼容 Nginx 反向代理。 */ /** Spring 注入版:自动按配置解析 XFF。 */
public static String getClientIp(HttpServletRequest request) { public String clientIp(HttpServletRequest request) {
String[] headers = {"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP"}; List<String> cidrs = StringUtils.hasText(trustedProxies)
for (String header : headers) { ? Arrays.asList(trustedProxies.split(","))
String value = request.getHeader(header); : List.of();
if (StringUtils.hasText(value) && !UNKNOWN.equalsIgnoreCase(value)) { return resolve(request, cidrs);
int comma = value.indexOf(','); }
return comma > 0 ? value.substring(0, comma).trim() : value.trim();
private static String resolve(HttpServletRequest request, List<String> trustedCidrs) {
String remoteAddr = request.getRemoteAddr();
if (isTrustedProxy(remoteAddr, trustedCidrs)) {
String fromHeader = readProxyHeader(request);
if (StringUtils.hasText(fromHeader)) {
return fromHeader;
} }
} }
return request.getRemoteAddr(); return remoteAddr;
}
private static String readProxyHeader(HttpServletRequest request) {
for (String header : PROXY_HEADERS) {
String value = request.getHeader(header);
if (StringUtils.hasText(value) && !UNKNOWN.equalsIgnoreCase(value)) {
// XFF 链格式:client, proxy1, proxy2 —— 最左侧是原始客户端 IP
String[] parts = value.split(",");
return parts[0].trim();
}
}
return "";
}
/**
* 判断 remoteAddr 是否属于可信代理。
*
* <p>CIDR 简化实现:只支持单个 IP 或 "/24" 这类前缀掩码,不支持复杂区间。
* 生产反代一般就是 127.0.0.1、10.0.0.0/8 这类,够用。
*/
static boolean isTrustedProxy(String remoteAddr, List<String> trustedCidrs) {
if (!StringUtils.hasText(remoteAddr) || trustedCidrs.isEmpty()) {
return false;
}
try {
InetAddress remote = InetAddress.getByName(remoteAddr.trim());
for (String cidr : trustedCidrs) {
if (cidrMatches(remote, cidr.trim())) {
return true;
}
}
} catch (UnknownHostException ex) {
log.debug("无法解析 remoteAddr {} 为 IP,跳过 XFF 信任判定", remoteAddr);
}
return false;
}
private static boolean cidrMatches(InetAddress target, String cidr) {
if (!cidr.contains("/")) {
// 单 IP 精确匹配
InetAddress trusted;
try {
trusted = InetAddress.getByName(cidr);
} catch (UnknownHostException ex) {
return false;
}
return trusted.equals(target);
}
String[] parts = cidr.split("/", 2);
String netPart = parts[0];
int prefixLen;
try {
prefixLen = Integer.parseInt(parts[1]);
} catch (NumberFormatException ex) {
return false;
}
InetAddress net;
try {
net = InetAddress.getByName(netPart);
} catch (UnknownHostException ex) {
return false;
}
byte[] targetBytes = target.getAddress();
byte[] netBytes = net.getAddress();
if (targetBytes.length != netBytes.length) {
return false;
}
int fullBytes = prefixLen / 8;
int remainingBits = prefixLen % 8;
for (int i = 0; i < fullBytes; i++) {
if (targetBytes[i] != netBytes[i]) {
return false;
}
}
if (remainingBits > 0 && fullBytes < targetBytes.length) {
int mask = (0xFF << (8 - remainingBits)) & 0xFF;
if ((targetBytes[fullBytes] & mask) != (netBytes[fullBytes] & mask)) {
return false;
}
}
return true;
}
/** Spring 直接实例化;保留 package-private 方便单测 new。 */
WebUtils() {
} }
} }
+5
View File
@@ -25,5 +25,10 @@
<groupId>com.fruitshorts</groupId> <groupId>com.fruitshorts</groupId>
<artifactId>fruitshorts-module-system</artifactId> <artifactId>fruitshorts-module-system</artifactId>
</dependency> </dependency>
<!-- 离线 IP → 国家解析,xdb 数据在 src/main/resources/ip2region 下 -->
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>
@@ -0,0 +1,219 @@
// Author: fruit.com.cn
package com.fruitshorts.user.enums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* 国家/地区 → 语言、时区、币种。
*
* <p>App 目前只内置 en / id / zh 三种语言,除印尼、中国及台港澳外的市场统一落到 en-US;
* 时区与币种按国家真实值写入,避免所有用户都变成 IDR。
*
* <p>未收录的国家按 {@link #DEFAULT}(印尼)处理,与历史行为保持一致。
*/
@Slf4j
public enum CountryProfile {
ID("id-ID", "Asia/Jakarta", "IDR"),
MY("en-US", "Asia/Kuala_Lumpur", "MYR"),
SG("en-US", "Asia/Singapore", "SGD"),
TH("en-US", "Asia/Bangkok", "THB"),
VN("en-US", "Asia/Ho_Chi_Minh", "VND"),
PH("en-US", "Asia/Manila", "PHP"),
KH("en-US", "Asia/Phnom_Penh", "KHR"),
MM("en-US", "Asia/Yangon", "MMK"),
LA("en-US", "Asia/Vientiane", "LAK"),
BN("en-US", "Asia/Brunei", "BND"),
CN("zh-CN", "Asia/Shanghai", "CNY"),
TW("zh-TW", "Asia/Taipei", "TWD"),
HK("zh-HK", "Asia/Hong_Kong", "HKD"),
MO("zh-HK", "Asia/Macau", "MOP"),
JP("en-US", "Asia/Tokyo", "JPY"),
KR("en-US", "Asia/Seoul", "KRW"),
IN("en-US", "Asia/Kolkata", "INR"),
PK("en-US", "Asia/Karachi", "PKR"),
BD("en-US", "Asia/Dhaka", "BDT"),
LK("en-US", "Asia/Colombo", "LKR"),
NP("en-US", "Asia/Kathmandu", "NPR"),
US("en-US", "America/New_York", "USD"),
CA("en-US", "America/Toronto", "CAD"),
MX("en-US", "America/Mexico_City", "MXN"),
BR("en-US", "America/Sao_Paulo", "BRL"),
AR("en-US", "America/Argentina/Buenos_Aires", "ARS"),
CL("en-US", "America/Santiago", "CLP"),
CO("en-US", "America/Bogota", "COP"),
PE("en-US", "America/Lima", "PEN"),
VE("en-US", "America/Caracas", "VES"),
EC("en-US", "America/Guayaquil", "USD"),
GT("en-US", "America/Guatemala", "GTQ"),
DO("en-US", "America/Santo_Domingo", "DOP"),
GB("en-US", "Europe/London", "GBP"),
DE("en-US", "Europe/Berlin", "EUR"),
FR("en-US", "Europe/Paris", "EUR"),
ES("en-US", "Europe/Madrid", "EUR"),
IT("en-US", "Europe/Rome", "EUR"),
NL("en-US", "Europe/Amsterdam", "EUR"),
PL("en-US", "Europe/Warsaw", "PLN"),
RU("en-US", "Europe/Moscow", "RUB"),
UA("en-US", "Europe/Kyiv", "UAH"),
TR("en-US", "Europe/Istanbul", "TRY"),
SA("en-US", "Asia/Riyadh", "SAR"),
AE("en-US", "Asia/Dubai", "AED"),
IL("en-US", "Asia/Jerusalem", "ILS"),
EG("en-US", "Africa/Cairo", "EGP"),
NG("en-US", "Africa/Lagos", "NGN"),
ZA("en-US", "Africa/Johannesburg", "ZAR"),
KE("en-US", "Africa/Nairobi", "KES"),
MA("en-US", "Africa/Casablanca", "MAD"),
AU("en-US", "Australia/Sydney", "AUD"),
NZ("en-US", "Pacific/Auckland", "NZD");
public static final CountryProfile DEFAULT = ID;
/** ip2region 返回的中文国家名 → ISO-2,只收录上面配置过的国家。 */
private static final Map<String, String> IP_COUNTRY_NAMES = Map.ofEntries(
Map.entry("印度尼西亚", "ID"),
Map.entry("马来西亚", "MY"),
Map.entry("新加坡", "SG"),
Map.entry("泰国", "TH"),
Map.entry("越南", "VN"),
Map.entry("菲律宾", "PH"),
Map.entry("柬埔寨", "KH"),
Map.entry("缅甸", "MM"),
Map.entry("老挝", "LA"),
Map.entry("文莱", "BN"),
Map.entry("中国", "CN"),
Map.entry("日本", "JP"),
Map.entry("韩国", "KR"),
Map.entry("印度", "IN"),
Map.entry("巴基斯坦", "PK"),
Map.entry("孟加拉国", "BD"),
Map.entry("斯里兰卡", "LK"),
Map.entry("尼泊尔", "NP"),
Map.entry("美国", "US"),
Map.entry("加拿大", "CA"),
Map.entry("墨西哥", "MX"),
Map.entry("巴西", "BR"),
Map.entry("阿根廷", "AR"),
Map.entry("智利", "CL"),
Map.entry("哥伦比亚", "CO"),
Map.entry("秘鲁", "PE"),
Map.entry("委内瑞拉", "VE"),
Map.entry("厄瓜多尔", "EC"),
Map.entry("危地马拉", "GT"),
Map.entry("多米尼加", "DO"),
Map.entry("英国", "GB"),
Map.entry("德国", "DE"),
Map.entry("法国", "FR"),
Map.entry("西班牙", "ES"),
Map.entry("意大利", "IT"),
Map.entry("荷兰", "NL"),
Map.entry("波兰", "PL"),
Map.entry("俄罗斯", "RU"),
Map.entry("乌克兰", "UA"),
Map.entry("土耳其", "TR"),
Map.entry("沙特阿拉伯", "SA"),
Map.entry("阿联酋", "AE"),
Map.entry("以色列", "IL"),
Map.entry("埃及", "EG"),
Map.entry("尼日利亚", "NG"),
Map.entry("南非", "ZA"),
Map.entry("肯尼亚", "KE"),
Map.entry("摩洛哥", "MA"),
Map.entry("澳大利亚", "AU"),
Map.entry("新西兰", "NZ"));
private static final Map<String, CountryProfile> BY_CODE = new HashMap<>();
static {
for (CountryProfile profile : values()) {
BY_CODE.put(profile.name(), profile);
}
}
private final String language;
private final String timezone;
private final String currency;
CountryProfile(String language, String timezone, String currency) {
this.language = language;
this.timezone = timezone;
this.currency = currency;
}
public String code() {
return name();
}
public String language() {
return language;
}
public String timezone() {
return timezone;
}
public String currency() {
return currency;
}
/** 未收录的国家统一回退到印尼。 */
public static CountryProfile of(String countryCode) {
CountryProfile profile = BY_CODE.get(normalize(countryCode));
return profile == null ? DEFAULT : profile;
}
/** 客户端上报的区域:只接受两位字母且已收录的国家,其余返回空串。 */
public static String normalizeClientCode(String raw) {
String code = normalize(raw);
return BY_CODE.containsKey(code) ? code : "";
}
/**
* 把 ip2region 的 `国家|区域|省份|城市|运营商` 转成 ISO-2。
* 台港澳在库里的国家字段都是「中国」,需要看省份区分。
*/
public static String fromIpRegion(String region) {
if (!StringUtils.hasText(region)) {
return "";
}
String[] parts = region.split("\\|", -1);
String country = parts[0].trim();
if (!StringUtils.hasText(country) || "0".equals(country)) {
return "";
}
if ("中国".equals(country)) {
String province = parts.length > 2 ? parts[2].trim() : "";
if (province.contains("台湾")) {
return "TW";
}
if (province.contains("香港")) {
return "HK";
}
if (province.contains("澳门")) {
return "MO";
}
return "CN";
}
String result = IP_COUNTRY_NAMES.getOrDefault(country, "");
if (!StringUtils.hasText(result) && StringUtils.hasText(country)) {
// ip2region 库里有但我们没收录的国家,debug 日志方便排查
log.debug("ip2region 返回未收录的国家 '{}',回退到默认值(印尼)", country);
}
return result;
}
private static String normalize(String raw) {
if (!StringUtils.hasText(raw)) {
return "";
}
String code = raw.trim().toUpperCase(Locale.ROOT);
return code.length() == 2 ? code : "";
}
}
@@ -18,6 +18,7 @@ import com.fruitshorts.user.dal.mapper.AppUserDeviceMapper;
import com.fruitshorts.user.dal.mapper.AppUserMapper; import com.fruitshorts.user.dal.mapper.AppUserMapper;
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper; import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
import com.fruitshorts.user.enums.AppUserStatus; import com.fruitshorts.user.enums.AppUserStatus;
import com.fruitshorts.user.enums.CountryProfile;
import com.fruitshorts.user.enums.CredentialType; import com.fruitshorts.user.enums.CredentialType;
import com.fruitshorts.user.enums.OtpScene; import com.fruitshorts.user.enums.OtpScene;
import com.fruitshorts.user.vo.AppUserRespVO; import com.fruitshorts.user.vo.AppUserRespVO;
@@ -66,6 +67,7 @@ public class AppAuthService {
private final ConfigService configService; private final ConfigService configService;
private final GoogleIdTokenVerifier googleVerifier; private final GoogleIdTokenVerifier googleVerifier;
private final ApplicationEventPublisher eventPublisher; private final ApplicationEventPublisher eventPublisher;
private final IpRegionService ipRegionService;
/** 后台 sys_config 缺失或非法时使用;小于等于 0 表示不限制。 */ /** 后台 sys_config 缺失或非法时使用;小于等于 0 表示不限制。 */
@Value("${fruitshorts.auth.register-max-per-ip-per-day:5}") @Value("${fruitshorts.auth.register-max-per-ip-per-day:5}")
@@ -178,6 +180,7 @@ public class AppAuthService {
user.setLastLoginAt(LocalDateTime.now()); user.setLastLoginAt(LocalDateTime.now());
user.setLastLoginIp(AppIdentifier.nullSafe(clientIp)); user.setLastLoginIp(AppIdentifier.nullSafe(clientIp));
syncCountryByIp(user, clientIp);
appUserMapper.updateById(user); appUserMapper.updateById(user);
touchDevice(user.getId(), req.getDeviceId(), req.getPlatform(), req.getDeviceModel()); touchDevice(user.getId(), req.getDeviceId(), req.getPlatform(), req.getDeviceModel());
@@ -194,7 +197,7 @@ public class AppAuthService {
* 再落一条 GOOGLE 凭证用于下次直接登录;已有邮箱账号时只补 GOOGLE 凭证,不重复建号。 * 再落一条 GOOGLE 凭证用于下次直接登录;已有邮箱账号时只补 GOOGLE 凭证,不重复建号。
*/ */
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public TokenRespVO googleLogin(String idToken, String deviceId) { public TokenRespVO googleLogin(String idToken, String deviceId, String clientIp) {
GoogleUser googleUser = googleVerifier.verify(idToken); GoogleUser googleUser = googleVerifier.verify(idToken);
String email = requireEmail(googleUser); String email = requireEmail(googleUser);
AppUserCredential googleCredential = findCredential(CredentialType.GOOGLE.name(), email); AppUserCredential googleCredential = findCredential(CredentialType.GOOGLE.name(), email);
@@ -203,7 +206,7 @@ public class AppAuthService {
if (googleCredential == null) { if (googleCredential == null) {
AppUserCredential emailCredential = findCredential(CredentialType.EMAIL.name(), email); AppUserCredential emailCredential = findCredential(CredentialType.EMAIL.name(), email);
if (emailCredential == null) { if (emailCredential == null) {
AppUser user = createGoogleUser(googleUser); AppUser user = createGoogleUser(googleUser, clientIp);
insertCredential(user.getId(), CredentialType.EMAIL.name(), email, ""); insertCredential(user.getId(), CredentialType.EMAIL.name(), email, "");
userId = user.getId(); userId = user.getId();
newUser = true; newUser = true;
@@ -219,10 +222,11 @@ public class AppAuthService {
googleCredential.setLastUsedAt(LocalDateTime.now()); googleCredential.setLastUsedAt(LocalDateTime.now());
credentialMapper.updateById(googleCredential); credentialMapper.updateById(googleCredential);
user.setLastLoginAt(LocalDateTime.now()); user.setLastLoginAt(LocalDateTime.now());
user.setLastLoginIp(""); user.setLastLoginIp(AppIdentifier.nullSafe(clientIp));
syncCountryByIp(user, clientIp);
appUserMapper.updateById(user); appUserMapper.updateById(user);
touchDevice(user.getId(), deviceId, null, null); touchDevice(user.getId(), deviceId, null, null);
TokenRespVO resp = issueTokens(user, googleCredential, deviceId, null, null, null, null, null); TokenRespVO resp = issueTokens(user, googleCredential, deviceId, null, null, null, null, clientIp);
resp.setNewUser(newUser); resp.setNewUser(newUser);
requestInteractionMerge(user.getId(), deviceId); requestInteractionMerge(user.getId(), deviceId);
return resp; return resp;
@@ -238,7 +242,7 @@ public class AppAuthService {
} }
/** 创建 Google 用户:邮箱已验证,昵称与头像直接取 Google 返回。 */ /** 创建 Google 用户:邮箱已验证,昵称与头像直接取 Google 返回。 */
private AppUser createGoogleUser(GoogleUser googleUser) { private AppUser createGoogleUser(GoogleUser googleUser, String clientIp) {
AppUser user = new AppUser(); AppUser user = new AppUser();
user.setUid(hasher.newUid()); user.setUid(hasher.newUid());
String nickname = StringUtils.hasText(googleUser.name()) String nickname = StringUtils.hasText(googleUser.name())
@@ -246,11 +250,13 @@ public class AppAuthService {
user.setNickname(nickname); user.setNickname(nickname);
user.setAvatarUrl(AppIdentifier.nullSafe(googleUser.picture())); user.setAvatarUrl(AppIdentifier.nullSafe(googleUser.picture()));
user.setGender(""); user.setGender("");
user.setCountryCode("ID"); String country = resolveCountry(clientIp, "");
user.setRegionCode("ID"); CountryProfile profile = CountryProfile.of(country);
user.setLanguage("id-ID"); user.setCountryCode(country);
user.setTimezone("Asia/Jakarta"); user.setRegionCode(country);
user.setCurrency("IDR"); user.setLanguage(profile.language());
user.setTimezone(profile.timezone());
user.setCurrency(profile.currency());
user.setStatus(AppUserStatus.NORMAL); user.setStatus(AppUserStatus.NORMAL);
user.setRegisterSource("APP"); user.setRegisterSource("APP");
user.setRegisterChannel(""); user.setRegisterChannel("");
@@ -527,12 +533,13 @@ public class AppAuthService {
: "User" + user.getUid().substring(1, 7)); : "User" + user.getUid().substring(1, 7));
user.setAvatarUrl(""); user.setAvatarUrl("");
user.setGender(""); user.setGender("");
String country = StringUtils.hasText(req.getCountryCode()) ? req.getCountryCode() : "ID"; String country = resolveCountry(clientIp, req.getCountryCode());
CountryProfile profile = CountryProfile.of(country);
user.setCountryCode(country); user.setCountryCode(country);
user.setRegionCode(country); user.setRegionCode(country);
user.setLanguage("id-ID"); user.setLanguage(profile.language());
user.setTimezone("Asia/Jakarta"); user.setTimezone(profile.timezone());
user.setCurrency("IDR"); user.setCurrency(profile.currency());
user.setStatus(AppUserStatus.NORMAL); user.setStatus(AppUserStatus.NORMAL);
user.setRegisterSource("APP"); user.setRegisterSource("APP");
user.setRegisterChannel(""); user.setRegisterChannel("");
@@ -549,6 +556,49 @@ public class AppAuthService {
return user; return user;
} }
/**
* 国家判定优先级:服务端 IP 解析 → 客户端上报的设备区域 → 印尼(历史默认)。
* IP 在本地开发/内网环境解析不出来,这时才用客户端区域。
*/
private String resolveCountry(String clientIp, String clientCountryCode) {
String byIp = ipRegionService.resolveCountry(clientIp);
if (StringUtils.hasText(byIp)) {
return byIp;
}
String byClient = CountryProfile.normalizeClientCode(clientCountryCode);
return StringUtils.hasText(byClient) ? byClient : CountryProfile.DEFAULT.code();
}
/**
* 登录时按 IP 修正国家,解决历史账号被统一写成 ID 的问题(老用户下次登录即自愈)。
*
* <p>regionCode / 语言 / 时区 / 币种 只在它们仍是「旧国家映射值」时才跟着改,
* 用户自己在资料页改过就保留,不被 IP 覆盖。countryCode 始终用 IP 结果覆盖
* (它是国家判断的权威来源,不涉及用户偏好)。
*/
private void syncCountryByIp(AppUser user, String clientIp) {
String byIp = ipRegionService.resolveCountry(clientIp);
if (!StringUtils.hasText(byIp) || byIp.equalsIgnoreCase(user.getCountryCode())) {
return;
}
CountryProfile before = CountryProfile.of(user.getCountryCode());
CountryProfile after = CountryProfile.of(byIp);
user.setCountryCode(byIp);
// regionCode 与 countryCode 永远同时写入(注册时就是这样),所以保护条件和语言一致
if (!StringUtils.hasText(user.getRegionCode()) || user.getRegionCode().equalsIgnoreCase(before.code())) {
user.setRegionCode(byIp);
}
if (!StringUtils.hasText(user.getLanguage()) || user.getLanguage().equals(before.language())) {
user.setLanguage(after.language());
}
if (!StringUtils.hasText(user.getTimezone()) || user.getTimezone().equals(before.timezone())) {
user.setTimezone(after.timezone());
}
if (!StringUtils.hasText(user.getCurrency()) || user.getCurrency().equals(before.currency())) {
user.setCurrency(after.currency());
}
}
private void recordConsent(Long userId, String scene, String version, String clientIp, String deviceId) { private void recordConsent(Long userId, String scene, String version, String clientIp, String deviceId) {
AppUserConsent consent = new AppUserConsent(); AppUserConsent consent = new AppUserConsent();
consent.setUserId(userId); consent.setUserId(userId);
@@ -2,6 +2,7 @@
package com.fruitshorts.user.service; package com.fruitshorts.user.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@@ -30,6 +31,7 @@ import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
/** /**
@@ -52,33 +54,36 @@ public class AppUserAdminService {
req.getPageIndex() == null || req.getPageIndex() < 1 ? 1 : req.getPageIndex(), req.getPageIndex() == null || req.getPageIndex() < 1 ? 1 : req.getPageIndex(),
req.getPageSize() == null || req.getPageSize() < 1 ? 10 : req.getPageSize()); req.getPageSize() == null || req.getPageSize() < 1 ? 10 : req.getPageSize());
IPage<AppUser> result; List<Long> platformUserIds = null;
if (StringUtils.hasText(req.getPlatform())) {
// 与列表展示保持一致:取每个用户最近一次会话的平台
platformUserIds = sessionMapper.selectUserIdsByLatestPlatform(
req.getPlatform().trim().toUpperCase(Locale.ROOT));
if (platformUserIds.isEmpty()) {
return new PageResult<>(0L, List.of());
}
}
LambdaQueryWrapper<AppUser> wrapper = Wrappers.lambdaQuery();
if (StringUtils.hasText(req.getKeyword())) { if (StringUtils.hasText(req.getKeyword())) {
// uid / 昵称 直接查;手机号与邮箱要先在凭证表命中 userId // uid / 昵称 直接查;手机号与邮箱要先在凭证表命中 userId
List<Long> matchedUserIds = userIdsByCredential(req.getKeyword()); List<Long> matchedUserIds = userIdsByCredential(req.getKeyword());
result = appUserMapper.selectPage(page, Wrappers.<AppUser>lambdaQuery() wrapper.and(nested -> {
.and(wrapper -> { nested.like(AppUser::getUid, req.getKeyword())
wrapper.like(AppUser::getUid, req.getKeyword()) .or().like(AppUser::getNickname, req.getKeyword());
.or().like(AppUser::getNickname, req.getKeyword()); if (!matchedUserIds.isEmpty()) {
if (!matchedUserIds.isEmpty()) { nested.or().in(AppUser::getId, matchedUserIds);
wrapper.or().in(AppUser::getId, matchedUserIds); }
} });
})
.eq(StringUtils.hasText(req.getStatus()), AppUser::getStatus, req.getStatus())
.eq(StringUtils.hasText(req.getCountryCode()), AppUser::getCountryCode,
req.getCountryCode())
.eq(StringUtils.hasText(req.getRegisterSource()), AppUser::getRegisterSource,
req.getRegisterSource())
.orderByDesc(AppUser::getId));
} else {
result = appUserMapper.selectPage(page, Wrappers.<AppUser>lambdaQuery()
.eq(StringUtils.hasText(req.getStatus()), AppUser::getStatus, req.getStatus())
.eq(StringUtils.hasText(req.getCountryCode()), AppUser::getCountryCode,
req.getCountryCode())
.eq(StringUtils.hasText(req.getRegisterSource()), AppUser::getRegisterSource,
req.getRegisterSource())
.orderByDesc(AppUser::getId));
} }
wrapper.eq(StringUtils.hasText(req.getStatus()), AppUser::getStatus, req.getStatus())
.eq(StringUtils.hasText(req.getCountryCode()), AppUser::getCountryCode,
req.getCountryCode())
.eq(StringUtils.hasText(req.getRegisterSource()), AppUser::getRegisterSource,
req.getRegisterSource())
.in(platformUserIds != null, AppUser::getId, platformUserIds)
.orderByDesc(AppUser::getId);
IPage<AppUser> result = appUserMapper.selectPage(page, wrapper);
List<AppUserAdminRespVO> list = toRespList(result.getRecords()); List<AppUserAdminRespVO> list = toRespList(result.getRecords());
fillLatestSystem(list); fillLatestSystem(list);
return new PageResult<>(result.getTotal(), list); return new PageResult<>(result.getTotal(), list);
@@ -164,7 +169,7 @@ public class AppUserAdminService {
return vo; return vo;
} }
/** 用最近一次未吊销会话上的系统信息,供后台用户列表展示。 */ /** 用最近一次会话上的系统信息,供后台用户列表展示;排序需与平台筛选一致。 */
private void fillLatestSystem(List<AppUserAdminRespVO> list) { private void fillLatestSystem(List<AppUserAdminRespVO> list) {
if (list.isEmpty()) { if (list.isEmpty()) {
return; return;
@@ -180,7 +185,6 @@ public class AppUserAdminService {
} }
List<AppUserSession> sessions = sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery() List<AppUserSession> sessions = sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery()
.in(AppUserSession::getUserId, ids) .in(AppUserSession::getUserId, ids)
.isNull(AppUserSession::getRevokedAt)
.orderByDesc(AppUserSession::getLastActiveAt) .orderByDesc(AppUserSession::getLastActiveAt)
.orderByDesc(AppUserSession::getId)); .orderByDesc(AppUserSession::getId));
Map<Long, AppUserSession> latest = new HashMap<>(); Map<Long, AppUserSession> latest = new HashMap<>();
@@ -0,0 +1,60 @@
// Author: fruit.com.cn
package com.fruitshorts.user.service;
import com.fruitshorts.user.enums.CountryProfile;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.InputStream;
/**
* 把登录/注册请求的客户端 IP 解析成国家码。
*
* <p>用离线 ip2region(xdb 随包发布),不依赖外部接口;内网、保留地址与未收录国家返回空串,
* 由调用方回退到客户端上报的设备区域。数据加载失败也不阻断启动,只是 IP 解析不生效。
*/
@Slf4j
@Service
public class IpRegionService {
private static final String DB_PATH = "ip2region/ip2region.xdb";
private volatile Searcher searcher;
private volatile boolean loaded;
/** 返回 ISO-2 国家码;解析不出来返回空串。 */
public String resolveCountry(String ip) {
Searcher current = searcher();
if (current == null || !StringUtils.hasText(ip)) {
return "";
}
try {
return CountryProfile.fromIpRegion(current.search(ip.trim()));
} catch (Exception ex) {
// 非法 IP(本地开发、测试桩)不当作错误,交给客户端区域兜底
return "";
}
}
private Searcher searcher() {
if (loaded) {
return searcher;
}
synchronized (this) {
if (!loaded) {
try (InputStream in = new ClassPathResource(DB_PATH).getInputStream()) {
searcher = Searcher.newWithBuffer(in.readAllBytes());
} catch (Exception ex) {
log.warn("ip2region 数据加载失败,IP 国家解析不可用: {}", ex.getMessage());
} finally {
loaded = true;
}
}
}
return searcher;
}
}
@@ -13,6 +13,8 @@ public class AppUserQueryReqVO {
private String status; private String status;
private String countryCode; private String countryCode;
private String registerSource; private String registerSource;
/** 客户端平台筛选:ANDROID / IOS / WEB,留空不限制;按最近一次会话的平台判定 */
private String platform;
private Integer pageIndex = 1; private Integer pageIndex = 1;
private Integer pageSize = 10; private Integer pageSize = 10;
} }
@@ -25,6 +25,7 @@ public class RegisterReqVO {
private String password; private String password;
private String nickname; private String nickname;
/** 客户端上报的设备区域(ISO-2),仅在服务端 IP 解析失败时作为兜底 */
private String countryCode; private String countryCode;
private String deviceId; private String deviceId;
private String deviceModel; private String deviceModel;
@@ -0,0 +1,12 @@
# Author: fruit.com.cn
# ip2region 离线库数据版本追踪
# 每次替换 ip2region.xdb 时更新此文件
version: 2.7.0
updated: 2026-10-21
source: org.lionsoul:ip2region:2.7.0
xdb-path: fruitshorts-module-user/src/main/resources/ip2region/ip2region.xdb
# 覆盖范围:国家 + 省份 + 城市 + 运营商(IPv4)
# 生产请留意:xdb 随 jar 打包约 11MB,admin-api 不解析 IP 但也会带上这份数据。
# 后续可考虑用 Spring Profile + 条件装配,让 admin-api 不带 ip2region。
+7
View File
@@ -44,6 +44,7 @@
<mybatis-plus.version>3.5.7</mybatis-plus.version> <mybatis-plus.version>3.5.7</mybatis-plus.version>
<jjwt.version>0.12.5</jjwt.version> <jjwt.version>0.12.5</jjwt.version>
<springdoc.version>2.5.0</springdoc.version> <springdoc.version>2.5.0</springdoc.version>
<ip2region.version>2.7.0</ip2region.version>
<!-- Spring Boot 3.2 默认的 1.18.32 在 JDK 23+ 上会编译失败,这里提升到支持新 JDK 的版本 --> <!-- Spring Boot 3.2 默认的 1.18.32 在 JDK 23+ 上会编译失败,这里提升到支持新 JDK 的版本 -->
<lombok.version>1.18.48</lombok.version> <lombok.version>1.18.48</lombok.version>
</properties> </properties>
@@ -130,6 +131,12 @@
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>${springdoc.version}</version> <version>${springdoc.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>${ip2region.version}</version>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
@@ -0,0 +1,11 @@
-- Author: fruit.com.cn
-- K113 app_user_session 按「最近一次」平台筛选用户的索引。
--
-- selectUserIdsByLatestPlatform 用的是 DISTINCT ON (user_id) ... ORDER BY user_id, last_active_at DESC NULLS LAST, id DESC。
-- 原表只有 (user_id, revoked_at) 索引,DISTINCT ON + ORDER BY 退化成全表 Sort + Seq Scan,
-- 500 行还行,10 万行就扛不住了。补一个匹配 ORDER BY 的部分索引:deleted = 0 覆盖逻辑删除。
--
-- 注意:CREATE INDEX CONCURRENTLY 不能在事务块里执行,这里直接跑,不加 BEGIN/COMMIT。
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_session_user_latest
ON app_user_session (user_id, last_active_at DESC NULLS LAST, id DESC)
WHERE deleted = 0;