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));
|
||||||
|
}
|
||||||
|
}
|
||||||
+75
-26
@@ -13,31 +13,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
|||||||
*/
|
*/
|
||||||
public class WebMvcConfig implements WebMvcConfigurer {
|
public class WebMvcConfig implements WebMvcConfigurer {
|
||||||
|
|
||||||
/**
|
private static final String[] AUTH_FREE_PATHS = {
|
||||||
* 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.
|
|
||||||
*/
|
|
||||||
private final AuthInterceptor authInterceptor;
|
|
||||||
/**
|
|
||||||
* Purpose: slowRequestLoggingInterceptor supports WebMvcConfig.java by holding or executing the slow request logging interceptor business role.
|
|
||||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
|
||||||
*/
|
|
||||||
private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
/**
|
|
||||||
* Purpose: addInterceptors supports WebMvcConfig.java by holding or executing the add interceptors business role.
|
|
||||||
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
|
||||||
*/
|
|
||||||
public void addInterceptors(InterceptorRegistry registry) {
|
|
||||||
registry.addInterceptor(slowRequestLoggingInterceptor)
|
|
||||||
.addPathPatterns("/**")
|
|
||||||
.order(-100);
|
|
||||||
|
|
||||||
registry.addInterceptor(authInterceptor)
|
|
||||||
.addPathPatterns("/**")
|
|
||||||
.order(0)
|
|
||||||
.excludePathPatterns(
|
|
||||||
"/user/login",
|
"/user/login",
|
||||||
"/user/register",
|
"/user/register",
|
||||||
"/user/check/**",
|
"/user/check/**",
|
||||||
@@ -78,6 +54,79 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
|||||||
"/admin/auth/refresh",
|
"/admin/auth/refresh",
|
||||||
"/error",
|
"/error",
|
||||||
"/health/**"
|
"/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.
|
||||||
|
*/
|
||||||
|
private final AuthInterceptor authInterceptor;
|
||||||
|
/**
|
||||||
|
* Purpose: slowRequestLoggingInterceptor supports WebMvcConfig.java by holding or executing the slow request logging interceptor business role.
|
||||||
|
* 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
|
||||||
|
/**
|
||||||
|
* Purpose: addInterceptors supports WebMvcConfig.java by holding or executing the add interceptors business role.
|
||||||
|
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
|
||||||
|
*/
|
||||||
|
public void addInterceptors(InterceptorRegistry registry) {
|
||||||
|
registry.addInterceptor(slowRequestLoggingInterceptor)
|
||||||
|
.addPathPatterns("/**")
|
||||||
|
.order(-100);
|
||||||
|
|
||||||
|
registry.addInterceptor(authInterceptor)
|
||||||
|
.addPathPatterns("/**")
|
||||||
|
.order(0)
|
||||||
|
.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.system.dto.LegalAgreementDTO;
|
||||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
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.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.service.SecurityAuditLogService;
|
||||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||||
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
|
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.
|
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||||
*/
|
*/
|
||||||
private final RequestThrottleService requestThrottleService;
|
private final RequestThrottleService requestThrottleService;
|
||||||
|
/**
|
||||||
|
* Purpose: agreementVersionCacheService 在同意成功后清除该用户的协议缓存。
|
||||||
|
*/
|
||||||
|
private final AgreementVersionCacheService agreementVersionCacheService;
|
||||||
|
|
||||||
@GetMapping("/current")
|
@GetMapping("/current")
|
||||||
/**
|
/**
|
||||||
@@ -87,6 +92,7 @@ public class LegalAgreementController {
|
|||||||
@RequestParam(required = false) String clientType) {
|
@RequestParam(required = false) String clientType) {
|
||||||
Long userId = (Long) request.getAttribute("userId");
|
Long userId = (Long) request.getAttribute("userId");
|
||||||
legalAgreementService.acceptCurrentAgreements(userId, clientType, request);
|
legalAgreementService.acceptCurrentAgreements(userId, clientType, request);
|
||||||
|
agreementVersionCacheService.evictUser(userId);
|
||||||
return Result.success(legalAgreementService.getPendingAgreements(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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ import type { IdType } from '@/utils/id'
|
|||||||
import { clearAdminSessionStorage } from '@/utils/admin-session'
|
import { clearAdminSessionStorage } from '@/utils/admin-session'
|
||||||
import { attachRequestSignature } from '@/utils/request-signature'
|
import { attachRequestSignature } from '@/utils/request-signature'
|
||||||
import { isApiAuthFreePath } from './auth-free-paths'
|
import { isApiAuthFreePath } from './auth-free-paths'
|
||||||
import { isAgreementPending } from '../utils/agreement-gate'
|
import { AGREEMENT_REQUIRED_EVENT, isAgreementPending, setAgreementPending } from '../utils/agreement-gate'
|
||||||
import {
|
import {
|
||||||
getApiResponseMessage,
|
getApiResponseMessage,
|
||||||
isPermissionErrorMessage,
|
isPermissionErrorMessage,
|
||||||
@@ -89,6 +89,12 @@ const isAdminScopedUrl = (url?: string) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const AGREEMENT_GATE_ALLOWLIST = ['/legal-agreement/', '/admin/auth/', '/user/logout', '/user/info']
|
const AGREEMENT_GATE_ALLOWLIST = ['/legal-agreement/', '/admin/auth/', '/user/logout', '/user/info']
|
||||||
|
/**
|
||||||
|
* 服务端协议同意拦截返回的业务码。收到后前端锁定业务请求并引导用户去阅读/同意最新版协议。
|
||||||
|
*/
|
||||||
|
const AGREEMENT_VERSION_REQUIRED_CODE = 4510
|
||||||
|
const AGREEMENT_REQUIRED_DEDUPE_MS = 5000
|
||||||
|
let lastAgreementRequiredTime = 0
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Purpose: getStoredRefreshToken supports index.ts by holding or executing the get stored refresh token page or API role.
|
* Purpose: getStoredRefreshToken supports index.ts by holding or executing the get stored refresh token page or API role.
|
||||||
@@ -154,6 +160,26 @@ const showError = (msg: string) => {
|
|||||||
message.error(msg)
|
message.error(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理服务端 4510(未同意最新协议):
|
||||||
|
* 锁定后续业务请求、广播事件让后台布局弹出既有的同意弹层,并提示用户。
|
||||||
|
* 非后台场景没有弹层,直接新开协议阅读页,引导用户阅读后重新登录同意。
|
||||||
|
*/
|
||||||
|
const handleAgreementRequired = (res: any, isAdminRequest: boolean) => {
|
||||||
|
setAgreementPending(true)
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.dispatchEvent(new CustomEvent(AGREEMENT_REQUIRED_EVENT, { detail: res?.data || {} }))
|
||||||
|
}
|
||||||
|
if (Date.now() - lastAgreementRequiredTime < AGREEMENT_REQUIRED_DEDUPE_MS) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lastAgreementRequiredTime = Date.now()
|
||||||
|
showError(normalizeApiErrorMessage(res?.message || '用户协议与隐私政策已更新,请阅读并同意后继续使用'))
|
||||||
|
if (!isAdminRequest && typeof window !== 'undefined') {
|
||||||
|
window.open('/legal/user-terms.html', '_blank', 'noopener')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const resetSystemFailureWindow = () => {
|
const resetSystemFailureWindow = () => {
|
||||||
systemFailureTimes = []
|
systemFailureTimes = []
|
||||||
}
|
}
|
||||||
@@ -285,6 +311,11 @@ api.interceptors.response.use(
|
|||||||
response => {
|
response => {
|
||||||
resetSystemFailureWindow()
|
resetSystemFailureWindow()
|
||||||
const res = response.data
|
const res = response.data
|
||||||
|
if (Number(res?.code) === AGREEMENT_VERSION_REQUIRED_CODE) {
|
||||||
|
const errorMsg = normalizeApiErrorMessage(res?.message || '用户协议与隐私政策已更新,请阅读并同意后继续使用')
|
||||||
|
handleAgreementRequired(res, isAdminScopedUrl(response.config?.url))
|
||||||
|
return Promise.reject(new Error(errorMsg))
|
||||||
|
}
|
||||||
if (res.code !== 200) {
|
if (res.code !== 200) {
|
||||||
const errorMsg = normalizeApiErrorMessage(res.message || '请求失败')
|
const errorMsg = normalizeApiErrorMessage(res.message || '请求失败')
|
||||||
if (!isPermissionErrorMessage(errorMsg)) {
|
if (!isPermissionErrorMessage(errorMsg)) {
|
||||||
|
|||||||
@@ -4,6 +4,11 @@
|
|||||||
*/
|
*/
|
||||||
let agreementPending = false
|
let agreementPending = false
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 服务端返回 4510 时广播的事件名,页面层(如后台布局)监听后重新检查协议状态并展示同意弹层。
|
||||||
|
*/
|
||||||
|
export const AGREEMENT_REQUIRED_EVENT = 'jayucloud:agreement-required'
|
||||||
|
|
||||||
export const setAgreementPending = (value: boolean) => {
|
export const setAgreementPending = (value: boolean) => {
|
||||||
agreementPending = value
|
agreementPending = value
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -93,7 +93,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, ref, watch } from 'vue'
|
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import { message, Modal } from 'ant-design-vue'
|
import { message, Modal } from 'ant-design-vue'
|
||||||
import { DownOutlined, HomeOutlined, LogoutOutlined, MenuFoldOutlined, MenuOutlined, MenuUnfoldOutlined, SafetyCertificateOutlined, TeamOutlined, ToolOutlined, UserOutlined } from '@ant-design/icons-vue'
|
import { DownOutlined, HomeOutlined, LogoutOutlined, MenuFoldOutlined, MenuOutlined, MenuUnfoldOutlined, SafetyCertificateOutlined, TeamOutlined, ToolOutlined, UserOutlined } from '@ant-design/icons-vue'
|
||||||
@@ -104,7 +104,7 @@ import { completeAdminLogout } from '@/utils/admin-logout'
|
|||||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||||
import { useAdminViewport } from '@/composables/useAdminViewport'
|
import { useAdminViewport } from '@/composables/useAdminViewport'
|
||||||
import { legalAgreementApi, type AgreementPending } from '@/api/auth'
|
import { legalAgreementApi, type AgreementPending } from '@/api/auth'
|
||||||
import { setAgreementPending } from '@/utils/agreement-gate'
|
import { AGREEMENT_REQUIRED_EVENT, setAgreementPending } from '@/utils/agreement-gate'
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
@@ -157,10 +157,18 @@ const acceptAgreements = async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
watch(() => route.path, path => { selectedKeys.value = [path] }, { immediate: true })
|
watch(() => route.path, path => { selectedKeys.value = [path] }, { immediate: true })
|
||||||
|
/**
|
||||||
|
* 服务端返回 4510 时由请求层广播该事件,这里复用既有弹层逻辑重新检查协议状态。
|
||||||
|
*/
|
||||||
|
const handleAgreementRequired = () => { checkAgreementGate() }
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
try { userInfo.value = JSON.parse(localStorage.getItem('adminUserInfo') || 'null') } catch { userInfo.value = null }
|
try { userInfo.value = JSON.parse(localStorage.getItem('adminUserInfo') || 'null') } catch { userInfo.value = null }
|
||||||
|
window.addEventListener(AGREEMENT_REQUIRED_EVENT, handleAgreementRequired)
|
||||||
checkAgreementGate()
|
checkAgreementGate()
|
||||||
})
|
})
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
window.removeEventListener(AGREEMENT_REQUIRED_EVENT, handleAgreementRequired)
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -7,6 +7,12 @@ const HEADER_NONCE = 'X-Nonce'
|
|||||||
const HEADER_SIGNATURE = 'X-Signature'
|
const HEADER_SIGNATURE = 'X-Signature'
|
||||||
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
|
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 服务端协议同意拦截返回的业务码:登录用户未同意最新版协议时返回 4510。
|
||||||
|
*/
|
||||||
|
const AGREEMENT_VERSION_REQUIRED_CODE = 4510
|
||||||
|
let agreementPrompting = false
|
||||||
|
|
||||||
function buildUrl(url, params) {
|
function buildUrl(url, params) {
|
||||||
const sourceParams = params || {}
|
const sourceParams = params || {}
|
||||||
const baseUrl = sourceParams.__baseUrl ? sourceParams.__baseUrl : API_DOMAIN
|
const baseUrl = sourceParams.__baseUrl ? sourceParams.__baseUrl : API_DOMAIN
|
||||||
@@ -65,6 +71,37 @@ function handleUnauthorized(response, url) {
|
|||||||
return normalizeError(message, response)
|
return normalizeError(message, response)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理 4510:提示协议已更新并跳转登录页重新阅读同意。
|
||||||
|
* 登录页已有协议勾选与弹层,重新登录时会带上最新版本同意,避免重复弹窗用 agreementPrompting 去重。
|
||||||
|
*/
|
||||||
|
function handleAgreementVersionRequired(response, url) {
|
||||||
|
const message = resolveResponseMessage(response, '用户协议与隐私政策已更新,请阅读并同意后继续使用')
|
||||||
|
if (isAuthFreePath(url)) {
|
||||||
|
return normalizeError(message, response)
|
||||||
|
}
|
||||||
|
if (!agreementPrompting) {
|
||||||
|
agreementPrompting = true
|
||||||
|
clearRuntimeSession()
|
||||||
|
wx.showModal({
|
||||||
|
title: '协议版本已更新',
|
||||||
|
content: message,
|
||||||
|
showCancel: false,
|
||||||
|
confirmText: '去同意',
|
||||||
|
success() {
|
||||||
|
agreementPrompting = false
|
||||||
|
wx.reLaunch({
|
||||||
|
url: '/pages/login/index'
|
||||||
|
})
|
||||||
|
},
|
||||||
|
fail() {
|
||||||
|
agreementPrompting = false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return normalizeError(message, response)
|
||||||
|
}
|
||||||
|
|
||||||
function extractPath(value) {
|
function extractPath(value) {
|
||||||
const target = String(value || '')
|
const target = String(value || '')
|
||||||
if (!target) {
|
if (!target) {
|
||||||
@@ -174,6 +211,10 @@ function request(options) {
|
|||||||
resolve(payload.data)
|
resolve(payload.data)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (Number(payload.code) === AGREEMENT_VERSION_REQUIRED_CODE) {
|
||||||
|
reject(handleAgreementVersionRequired({ data: payload }, options.url))
|
||||||
|
return
|
||||||
|
}
|
||||||
if (Number(payload.code) === 401) {
|
if (Number(payload.code) === 401) {
|
||||||
reject(handleUnauthorized({ data: payload }, options.url))
|
reject(handleUnauthorized({ data: payload }, options.url))
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ const storage = {}
|
|||||||
const requests = []
|
const requests = []
|
||||||
const navigations = []
|
const navigations = []
|
||||||
const scheduled = []
|
const scheduled = []
|
||||||
|
const modals = []
|
||||||
let clearedSessions = 0
|
let clearedSessions = 0
|
||||||
let globalData = { wechatLoginState: { status: 'SUCCESS', accessToken: 'expired-token' } }
|
let globalData = { wechatLoginState: { status: 'SUCCESS', accessToken: 'expired-token' } }
|
||||||
|
|
||||||
@@ -15,6 +16,7 @@ global.wx = {
|
|||||||
removeStorageSync: key => { delete storage[key] },
|
removeStorageSync: key => { delete storage[key] },
|
||||||
request: options => requests.push(options),
|
request: options => requests.push(options),
|
||||||
showToast: () => {},
|
showToast: () => {},
|
||||||
|
showModal: options => modals.push(options),
|
||||||
reLaunch: options => navigations.push(options.url)
|
reLaunch: options => navigations.push(options.url)
|
||||||
}
|
}
|
||||||
global.getApp = () => ({
|
global.getApp = () => ({
|
||||||
@@ -45,6 +47,18 @@ async function rejectWithUnauthorized(options) {
|
|||||||
return pending
|
return pending
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function rejectWithAgreementRequired(options, message) {
|
||||||
|
const pending = request(options).then(
|
||||||
|
() => { throw new Error('Expected request to reject') },
|
||||||
|
error => error
|
||||||
|
)
|
||||||
|
requests[requests.length - 1].success({
|
||||||
|
statusCode: 200,
|
||||||
|
data: { code: 4510, message }
|
||||||
|
})
|
||||||
|
return pending
|
||||||
|
}
|
||||||
|
|
||||||
async function run() {
|
async function run() {
|
||||||
auth.setSession({ accessToken: 'expired-token' }, true)
|
auth.setSession({ accessToken: 'expired-token' }, true)
|
||||||
|
|
||||||
@@ -70,6 +84,21 @@ async function run() {
|
|||||||
assert.strictEqual(scheduled.length, 1)
|
assert.strictEqual(scheduled.length, 1)
|
||||||
scheduled.shift()()
|
scheduled.shift()()
|
||||||
assert.deepStrictEqual(navigations, ['/pages/login/index', '/pages/login/index'])
|
assert.deepStrictEqual(navigations, ['/pages/login/index', '/pages/login/index'])
|
||||||
|
|
||||||
|
const agreementMessage = '用户协议与隐私政策已更新(当前版本 2026.11.04-R2),请阅读并同意后继续使用'
|
||||||
|
auth.setSession({ accessToken: 'agreement-token' }, true)
|
||||||
|
const agreementError = await rejectWithAgreementRequired({ url: '/manager/calendar' }, agreementMessage)
|
||||||
|
assert.strictEqual(agreementError.message, agreementMessage)
|
||||||
|
assert.strictEqual(modals.length, 1)
|
||||||
|
assert.strictEqual(clearedSessions, 3)
|
||||||
|
assert.strictEqual(globalData.wechatLoginState, null)
|
||||||
|
|
||||||
|
const duplicatedError = await rejectWithAgreementRequired({ url: '/manager/customers' }, agreementMessage)
|
||||||
|
assert.strictEqual(duplicatedError.message, agreementMessage)
|
||||||
|
assert.strictEqual(modals.length, 1)
|
||||||
|
|
||||||
|
modals[0].success()
|
||||||
|
assert.deepStrictEqual(navigations, ['/pages/login/index', '/pages/login/index', '/pages/login/index'])
|
||||||
}
|
}
|
||||||
|
|
||||||
run().catch(error => {
|
run().catch(error => {
|
||||||
|
|||||||
Reference in New Issue
Block a user