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

+5
View File
@@ -25,5 +25,10 @@
<groupId>com.fruitshorts</groupId>
<artifactId>fruitshorts-module-system</artifactId>
</dependency>
<!-- 离线 IP → 国家解析,xdb 数据在 src/main/resources/ip2region 下 -->
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
</dependency>
</dependencies>
</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.AppUserSessionMapper;
import com.fruitshorts.user.enums.AppUserStatus;
import com.fruitshorts.user.enums.CountryProfile;
import com.fruitshorts.user.enums.CredentialType;
import com.fruitshorts.user.enums.OtpScene;
import com.fruitshorts.user.vo.AppUserRespVO;
@@ -66,6 +67,7 @@ public class AppAuthService {
private final ConfigService configService;
private final GoogleIdTokenVerifier googleVerifier;
private final ApplicationEventPublisher eventPublisher;
private final IpRegionService ipRegionService;
/** 后台 sys_config 缺失或非法时使用;小于等于 0 表示不限制。 */
@Value("${fruitshorts.auth.register-max-per-ip-per-day:5}")
@@ -178,6 +180,7 @@ public class AppAuthService {
user.setLastLoginAt(LocalDateTime.now());
user.setLastLoginIp(AppIdentifier.nullSafe(clientIp));
syncCountryByIp(user, clientIp);
appUserMapper.updateById(user);
touchDevice(user.getId(), req.getDeviceId(), req.getPlatform(), req.getDeviceModel());
@@ -194,7 +197,7 @@ public class AppAuthService {
* 再落一条 GOOGLE 凭证用于下次直接登录;已有邮箱账号时只补 GOOGLE 凭证,不重复建号。
*/
@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);
String email = requireEmail(googleUser);
AppUserCredential googleCredential = findCredential(CredentialType.GOOGLE.name(), email);
@@ -203,7 +206,7 @@ public class AppAuthService {
if (googleCredential == null) {
AppUserCredential emailCredential = findCredential(CredentialType.EMAIL.name(), email);
if (emailCredential == null) {
AppUser user = createGoogleUser(googleUser);
AppUser user = createGoogleUser(googleUser, clientIp);
insertCredential(user.getId(), CredentialType.EMAIL.name(), email, "");
userId = user.getId();
newUser = true;
@@ -219,10 +222,11 @@ public class AppAuthService {
googleCredential.setLastUsedAt(LocalDateTime.now());
credentialMapper.updateById(googleCredential);
user.setLastLoginAt(LocalDateTime.now());
user.setLastLoginIp("");
user.setLastLoginIp(AppIdentifier.nullSafe(clientIp));
syncCountryByIp(user, clientIp);
appUserMapper.updateById(user);
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);
requestInteractionMerge(user.getId(), deviceId);
return resp;
@@ -238,7 +242,7 @@ public class AppAuthService {
}
/** 创建 Google 用户:邮箱已验证,昵称与头像直接取 Google 返回。 */
private AppUser createGoogleUser(GoogleUser googleUser) {
private AppUser createGoogleUser(GoogleUser googleUser, String clientIp) {
AppUser user = new AppUser();
user.setUid(hasher.newUid());
String nickname = StringUtils.hasText(googleUser.name())
@@ -246,11 +250,13 @@ public class AppAuthService {
user.setNickname(nickname);
user.setAvatarUrl(AppIdentifier.nullSafe(googleUser.picture()));
user.setGender("");
user.setCountryCode("ID");
user.setRegionCode("ID");
user.setLanguage("id-ID");
user.setTimezone("Asia/Jakarta");
user.setCurrency("IDR");
String country = resolveCountry(clientIp, "");
CountryProfile profile = CountryProfile.of(country);
user.setCountryCode(country);
user.setRegionCode(country);
user.setLanguage(profile.language());
user.setTimezone(profile.timezone());
user.setCurrency(profile.currency());
user.setStatus(AppUserStatus.NORMAL);
user.setRegisterSource("APP");
user.setRegisterChannel("");
@@ -527,12 +533,13 @@ public class AppAuthService {
: "User" + user.getUid().substring(1, 7));
user.setAvatarUrl("");
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.setRegionCode(country);
user.setLanguage("id-ID");
user.setTimezone("Asia/Jakarta");
user.setCurrency("IDR");
user.setLanguage(profile.language());
user.setTimezone(profile.timezone());
user.setCurrency(profile.currency());
user.setStatus(AppUserStatus.NORMAL);
user.setRegisterSource("APP");
user.setRegisterChannel("");
@@ -549,6 +556,49 @@ public class AppAuthService {
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) {
AppUserConsent consent = new AppUserConsent();
consent.setUserId(userId);
@@ -2,6 +2,7 @@
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.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@@ -30,6 +31,7 @@ import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
@@ -52,33 +54,36 @@ public class AppUserAdminService {
req.getPageIndex() == null || req.getPageIndex() < 1 ? 1 : req.getPageIndex(),
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())) {
// uid / 昵称 直接查;手机号与邮箱要先在凭证表命中 userId
List<Long> matchedUserIds = userIdsByCredential(req.getKeyword());
result = appUserMapper.selectPage(page, Wrappers.<AppUser>lambdaQuery()
.and(wrapper -> {
wrapper.like(AppUser::getUid, req.getKeyword())
.or().like(AppUser::getNickname, req.getKeyword());
if (!matchedUserIds.isEmpty()) {
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.and(nested -> {
nested.like(AppUser::getUid, req.getKeyword())
.or().like(AppUser::getNickname, req.getKeyword());
if (!matchedUserIds.isEmpty()) {
nested.or().in(AppUser::getId, matchedUserIds);
}
});
}
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());
fillLatestSystem(list);
return new PageResult<>(result.getTotal(), list);
@@ -164,7 +169,7 @@ public class AppUserAdminService {
return vo;
}
/** 用最近一次未吊销会话上的系统信息,供后台用户列表展示。 */
/** 用最近一次会话上的系统信息,供后台用户列表展示;排序需与平台筛选一致。 */
private void fillLatestSystem(List<AppUserAdminRespVO> list) {
if (list.isEmpty()) {
return;
@@ -180,7 +185,6 @@ public class AppUserAdminService {
}
List<AppUserSession> sessions = sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery()
.in(AppUserSession::getUserId, ids)
.isNull(AppUserSession::getRevokedAt)
.orderByDesc(AppUserSession::getLastActiveAt)
.orderByDesc(AppUserSession::getId));
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 countryCode;
private String registerSource;
/** 客户端平台筛选:ANDROID / IOS / WEB,留空不限制;按最近一次会话的平台判定 */
private String platform;
private Integer pageIndex = 1;
private Integer pageSize = 10;
}
@@ -25,6 +25,7 @@ public class RegisterReqVO {
private String password;
private String nickname;
/** 客户端上报的设备区域(ISO-2),仅在服务端 IP 解析失败时作为兜底 */
private String countryCode;
private String deviceId;
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。