This commit is contained in:
+83
@@ -0,0 +1,83 @@
|
||||
package com.xiaowang.jayucloud.salon.core.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 协议同意校验拦截器:在身份解析之后、业务方法之前阻断未同意当前协议版本的已登录用户。
|
||||
* 未登录请求不在此校验;判定组件故障时放行并告警,避免协议缓存/数据库异常导致全站不可用。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AgreementAcceptanceInterceptor implements HandlerInterceptor {
|
||||
|
||||
public static final int AGREEMENT_VERSION_REQUIRED_CODE = 4510;
|
||||
|
||||
public static final String AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE = "AGREEMENT_VERSION_REQUIRED";
|
||||
|
||||
private final AgreementVersionCacheService agreementVersionCacheService;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
Object userIdAttribute = request.getAttribute("userId");
|
||||
if (!(userIdAttribute instanceof Number)) {
|
||||
return true;
|
||||
}
|
||||
Long userId = ((Number) userIdAttribute).longValue();
|
||||
try {
|
||||
Map<String, String> currentVersions = agreementVersionCacheService.currentVersions();
|
||||
Map<String, String> acceptedVersions = agreementVersionCacheService.acceptedVersions(userId);
|
||||
List<String> pendingTypes = new ArrayList<>();
|
||||
for (Map.Entry<String, String> entry : currentVersions.entrySet()) {
|
||||
if (!Objects.equals(entry.getValue(), acceptedVersions.get(entry.getKey()))) {
|
||||
pendingTypes.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
if (pendingTypes.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
writeAgreementRequired(response, currentVersions, pendingTypes);
|
||||
return false;
|
||||
} catch (Exception exception) {
|
||||
// 可用性优先:协议校验只是附加门禁,Redis/DB 故障时放行主业务,记录告警供监控排查。
|
||||
log.warn("协议同意校验失败,已放行请求 path={} userId={}", request.getRequestURI(), userId, exception);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeAgreementRequired(HttpServletResponse response,
|
||||
Map<String, String> currentVersions,
|
||||
List<String> pendingTypes) throws Exception {
|
||||
String versionText = currentVersions.values().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.joining("/"));
|
||||
String message = "用户协议与隐私政策已更新(当前版本 " + versionText + "),请阅读并同意后继续使用";
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("businessCode", AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE);
|
||||
data.put("currentVersions", currentVersions);
|
||||
data.put("pendingTypes", pendingTypes);
|
||||
Result<Map<String, Object>> result = new Result<>(AGREEMENT_VERSION_REQUIRED_CODE, message, data);
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
response.getWriter().write(objectMapper.writeValueAsString(result));
|
||||
}
|
||||
}
|
||||
+91
-42
@@ -13,6 +13,86 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
*/
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
private static final String[] AUTH_FREE_PATHS = {
|
||||
"/user/login",
|
||||
"/user/register",
|
||||
"/user/check/**",
|
||||
"/user/refresh-token",
|
||||
"/user/send-verification-code",
|
||||
"/user/phone-login",
|
||||
"/user/wechat-mini/auto-login",
|
||||
"/user/wechat-mini/phone-login",
|
||||
"/user/wechat-mini/confirm-login",
|
||||
"/user/wechat-mini/status",
|
||||
"/user/wechat-mini/quick-login",
|
||||
"/integration/wechat/content-moderation/callback",
|
||||
"/user/workbench/register/**",
|
||||
"/user/workbench/shops/available",
|
||||
"/user/reset-password-by-phone",
|
||||
"/legal-agreement/current",
|
||||
"/legal-agreement/current/**",
|
||||
"/legal-agreement/pending",
|
||||
"/api/legal-agreement/current",
|
||||
"/api/legal-agreement/current/**",
|
||||
"/api/legal-agreement/pending",
|
||||
"/product/get/**",
|
||||
"/product/list/**",
|
||||
"/comment/list/product/**",
|
||||
"/api/comment/list/product/**",
|
||||
"/nail-artist/profile/**",
|
||||
"/nail-artist/*/availability",
|
||||
"/nail-artist/*/reviews",
|
||||
"/shop/get/**",
|
||||
"/shop/trust-profile/**",
|
||||
"/shop/list",
|
||||
"/shop/list/public",
|
||||
"/shop/list/simple",
|
||||
"/tag/list/all",
|
||||
"/tag/list/filter-options",
|
||||
"/file/get-signed-url/**",
|
||||
"/admin/auth/login",
|
||||
"/admin/auth/refresh",
|
||||
"/error",
|
||||
"/health/**"
|
||||
};
|
||||
|
||||
/**
|
||||
* 协议同意门禁额外放行:同意接口、协议阅读页、账号认证类操作、外部回调与健康检查。
|
||||
* 这些路径不校验协议版本,避免版本发布后把已登录用户或外部回调锁在门外。
|
||||
*/
|
||||
private static final String[] AGREEMENT_EXTRA_FREE_PATHS = {
|
||||
"/legal-agreement/accept",
|
||||
"/api/legal-agreement/accept",
|
||||
"/legal-agreement/admin/**",
|
||||
"/api/legal-agreement/admin/**",
|
||||
"/user/logout",
|
||||
"/user/info",
|
||||
"/user/agreement-consent/**",
|
||||
"/user/switch-shop",
|
||||
"/user/relation/me",
|
||||
"/user/invite-code/resolve",
|
||||
"/user/bind-phone",
|
||||
"/user/unbind-phone",
|
||||
"/user/unbind-phone/**",
|
||||
"/user/wechat-mini/bind-phone",
|
||||
"/user/bind-email",
|
||||
"/user/password",
|
||||
"/user/phone",
|
||||
"/user/send-current-password-code",
|
||||
"/user/reset-password/**",
|
||||
"/user/upload-avatar/**",
|
||||
"/user/upload-profile-image/**",
|
||||
"/user/deactivate",
|
||||
"/legal/**",
|
||||
"/integration/**",
|
||||
"/api/integration/**",
|
||||
"/actuator/**",
|
||||
"/static/**",
|
||||
"/assets/**",
|
||||
"/index.html",
|
||||
"/favicon.ico"
|
||||
};
|
||||
|
||||
/**
|
||||
* Purpose: authInterceptor supports WebMvcConfig.java by holding or executing the auth interceptor business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
@@ -23,6 +103,10 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor;
|
||||
/**
|
||||
* Purpose: agreementAcceptanceInterceptor 在鉴权之后校验协议同意状态。
|
||||
*/
|
||||
private final AgreementAcceptanceInterceptor agreementAcceptanceInterceptor;
|
||||
|
||||
@Override
|
||||
/**
|
||||
@@ -37,47 +121,12 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
registry.addInterceptor(authInterceptor)
|
||||
.addPathPatterns("/**")
|
||||
.order(0)
|
||||
.excludePathPatterns(
|
||||
"/user/login",
|
||||
"/user/register",
|
||||
"/user/check/**",
|
||||
"/user/refresh-token",
|
||||
"/user/send-verification-code",
|
||||
"/user/phone-login",
|
||||
"/user/wechat-mini/auto-login",
|
||||
"/user/wechat-mini/phone-login",
|
||||
"/user/wechat-mini/confirm-login",
|
||||
"/user/wechat-mini/status",
|
||||
"/user/wechat-mini/quick-login",
|
||||
"/integration/wechat/content-moderation/callback",
|
||||
"/user/workbench/register/**",
|
||||
"/user/workbench/shops/available",
|
||||
"/user/reset-password-by-phone",
|
||||
"/legal-agreement/current",
|
||||
"/legal-agreement/current/**",
|
||||
"/legal-agreement/pending",
|
||||
"/api/legal-agreement/current",
|
||||
"/api/legal-agreement/current/**",
|
||||
"/api/legal-agreement/pending",
|
||||
"/product/get/**",
|
||||
"/product/list/**",
|
||||
"/comment/list/product/**",
|
||||
"/api/comment/list/product/**",
|
||||
"/nail-artist/profile/**",
|
||||
"/nail-artist/*/availability",
|
||||
"/nail-artist/*/reviews",
|
||||
"/shop/get/**",
|
||||
"/shop/trust-profile/**",
|
||||
"/shop/list",
|
||||
"/shop/list/public",
|
||||
"/shop/list/simple",
|
||||
"/tag/list/all",
|
||||
"/tag/list/filter-options",
|
||||
"/file/get-signed-url/**",
|
||||
"/admin/auth/login",
|
||||
"/admin/auth/refresh",
|
||||
"/error",
|
||||
"/health/**"
|
||||
);
|
||||
.excludePathPatterns(AUTH_FREE_PATHS);
|
||||
|
||||
registry.addInterceptor(agreementAcceptanceInterceptor)
|
||||
.addPathPatterns("/**")
|
||||
.order(1)
|
||||
.excludePathPatterns(AUTH_FREE_PATHS)
|
||||
.excludePathPatterns(AGREEMENT_EXTRA_FREE_PATHS);
|
||||
}
|
||||
}
|
||||
|
||||
+6
@@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.salon.core.common.Result;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.dto.LegalAgreementDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
|
||||
@@ -48,6 +49,10 @@ public class LegalAgreementController {
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private final RequestThrottleService requestThrottleService;
|
||||
/**
|
||||
* Purpose: agreementVersionCacheService 在同意成功后清除该用户的协议缓存。
|
||||
*/
|
||||
private final AgreementVersionCacheService agreementVersionCacheService;
|
||||
|
||||
@GetMapping("/current")
|
||||
/**
|
||||
@@ -87,6 +92,7 @@ public class LegalAgreementController {
|
||||
@RequestParam(required = false) String clientType) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
legalAgreementService.acceptCurrentAgreements(userId, clientType, request);
|
||||
agreementVersionCacheService.evictUser(userId);
|
||||
return Result.success(legalAgreementService.getPendingAgreements(userId));
|
||||
}
|
||||
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.system.support;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 协议版本缓存:当前发布版本缓存 4 分钟,用户已同意版本缓存 10 分钟。
|
||||
* 版本发布走 SQL 迁移,没有代码钩子,依赖短 TTL 自然收敛;accept 成功时主动清除该用户缓存。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AgreementVersionCacheService {
|
||||
|
||||
private static final String CURRENT_VERSIONS_KEY = "jayucloud:agreement:current-versions:v1";
|
||||
|
||||
private static final String USER_VERSIONS_KEY_PREFIX = "jayucloud:agreement:user-versions:";
|
||||
|
||||
private static final Duration CURRENT_VERSIONS_TTL = Duration.ofMinutes(4);
|
||||
|
||||
private static final Duration USER_VERSIONS_TTL = Duration.ofMinutes(10);
|
||||
|
||||
private static final TypeReference<Map<String, String>> STRING_MAP_TYPE = new TypeReference<Map<String, String>>() {
|
||||
};
|
||||
|
||||
private final LegalAgreementService legalAgreementService;
|
||||
|
||||
private final UserAgreementConsentMapper consentMapper;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
public Map<String, String> currentVersions() {
|
||||
Map<String, String> cached = readCache(CURRENT_VERSIONS_KEY);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
Map<String, String> loaded = legalAgreementService.getPendingAgreements(null).getCurrentVersions();
|
||||
writeCache(CURRENT_VERSIONS_KEY, loaded, CURRENT_VERSIONS_TTL);
|
||||
return loaded == null ? Collections.emptyMap() : loaded;
|
||||
}
|
||||
|
||||
public Map<String, String> acceptedVersions(Long userId) {
|
||||
if (userId == null) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
String key = userVersionsKey(userId);
|
||||
Map<String, String> cached = readCache(key);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
Map<String, String> loaded = consentMapper.selectList(new LambdaQueryWrapper<UserAgreementConsentDO>()
|
||||
.eq(UserAgreementConsentDO::getUserId, userId))
|
||||
.stream()
|
||||
.collect(Collectors.toMap(
|
||||
UserAgreementConsentDO::getAgreementType,
|
||||
UserAgreementConsentDO::getVersion,
|
||||
(left, right) -> right,
|
||||
LinkedHashMap::new));
|
||||
writeCache(key, loaded, USER_VERSIONS_TTL);
|
||||
return loaded;
|
||||
}
|
||||
|
||||
public void evictUser(Long userId) {
|
||||
if (userId == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
stringRedisTemplate.delete(userVersionsKey(userId));
|
||||
} catch (Exception exception) {
|
||||
log.warn("清除协议同意缓存失败 userId={}", userId, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String userVersionsKey(Long userId) {
|
||||
return USER_VERSIONS_KEY_PREFIX + userId;
|
||||
}
|
||||
|
||||
private Map<String, String> readCache(String key) {
|
||||
try {
|
||||
String json = stringRedisTemplate.opsForValue().get(key);
|
||||
if (!StringUtils.hasText(json)) {
|
||||
return null;
|
||||
}
|
||||
return objectMapper.readValue(json, STRING_MAP_TYPE);
|
||||
} catch (Exception exception) {
|
||||
log.warn("读取协议版本缓存失败,回退数据库 key={}", key, exception);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeCache(String key, Map<String, String> value, Duration ttl) {
|
||||
try {
|
||||
stringRedisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(value), ttl);
|
||||
} catch (Exception exception) {
|
||||
log.warn("写入协议版本缓存失败 key={}", key, exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.xiaowang.jayucloud.salon.core.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AgreementAcceptanceInterceptorTest {
|
||||
|
||||
@Mock private AgreementVersionCacheService agreementVersionCacheService;
|
||||
|
||||
private AgreementAcceptanceInterceptor interceptor;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
interceptor = new AgreementAcceptanceInterceptor(agreementVersionCacheService, objectMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsUnauthenticatedRequest() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
assertTrue(interceptor.preHandle(request, response, new Object()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsWhenAcceptedVersionsMatchCurrent() throws Exception {
|
||||
Map<String, String> versions = currentVersions();
|
||||
when(agreementVersionCacheService.currentVersions()).thenReturn(versions);
|
||||
when(agreementVersionCacheService.acceptedVersions(9L)).thenReturn(new LinkedHashMap<>(versions));
|
||||
|
||||
assertTrue(interceptor.preHandle(authenticatedRequest(9L), new MockHttpServletResponse(), new Object()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsWithBusinessCodeWhenVersionPending() throws Exception {
|
||||
Map<String, String> versions = currentVersions();
|
||||
Map<String, String> accepted = new LinkedHashMap<>();
|
||||
accepted.put("USER_TERMS", "2026.11.04");
|
||||
when(agreementVersionCacheService.currentVersions()).thenReturn(versions);
|
||||
when(agreementVersionCacheService.acceptedVersions(9L)).thenReturn(accepted);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
assertFalse(interceptor.preHandle(authenticatedRequest(9L), response, new Object()));
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
JsonNode body = objectMapper.readTree(response.getContentAsString());
|
||||
assertEquals(AgreementAcceptanceInterceptor.AGREEMENT_VERSION_REQUIRED_CODE, body.get("code").asInt());
|
||||
assertEquals("2026.11.04-R2", body.get("data").get("currentVersions").get("USER_TERMS").asText());
|
||||
assertEquals("USER_TERMS", body.get("data").get("pendingTypes").get(0).asText());
|
||||
assertEquals(AgreementAcceptanceInterceptor.AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE,
|
||||
body.get("data").get("businessCode").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsOpenWhenGuardComponentThrows() throws Exception {
|
||||
when(agreementVersionCacheService.currentVersions()).thenThrow(new IllegalStateException("redis down"));
|
||||
|
||||
assertTrue(interceptor.preHandle(authenticatedRequest(9L), new MockHttpServletResponse(), new Object()));
|
||||
}
|
||||
|
||||
private MockHttpServletRequest authenticatedRequest(Long userId) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setAttribute("userId", userId);
|
||||
return request;
|
||||
}
|
||||
|
||||
private Map<String, String> currentVersions() {
|
||||
Map<String, String> versions = new LinkedHashMap<>();
|
||||
versions.put("USER_TERMS", "2026.11.04-R2");
|
||||
versions.put("PRIVACY_POLICY", "2026.11.04-R2");
|
||||
return versions;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user