This commit is contained in:
+14
@@ -36,6 +36,10 @@ public class AgreementAcceptanceInterceptor implements HandlerInterceptor {
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
// 后台管理端不参与协议版本校验:平台管理人员登录后台即视为已知悉协议,不产生同意记录、不弹更新提示。
|
||||
if (isAdminRequestPath(request.getRequestURI())) {
|
||||
return true;
|
||||
}
|
||||
Object userIdAttribute = request.getAttribute("userId");
|
||||
if (!(userIdAttribute instanceof Number)) {
|
||||
return true;
|
||||
@@ -62,6 +66,16 @@ public class AgreementAcceptanceInterceptor implements HandlerInterceptor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断请求是否属于后台管理端。
|
||||
* 网关会把 {@code /api/admin/**} 与 {@code /admin/api/**} 统一改写为 {@code /admin/**} 转发到 Core;
|
||||
* 另有部分管理端接口以业务前缀 + {@code /admin/**} 暴露(如 {@code /order/admin/**})。
|
||||
* 因此只要路径包含 {@code /admin/} 段即视为管理端请求,直接放行。
|
||||
*/
|
||||
private boolean isAdminRequestPath(String path) {
|
||||
return path != null && path.contains("/admin/");
|
||||
}
|
||||
|
||||
private void writeAgreementRequired(HttpServletResponse response,
|
||||
Map<String, String> currentVersions,
|
||||
List<String> pendingTypes) throws Exception {
|
||||
|
||||
+28
@@ -17,6 +17,7 @@ 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.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -76,6 +77,33 @@ class AgreementAcceptanceInterceptorTest {
|
||||
assertTrue(interceptor.preHandle(authenticatedRequest(9L), new MockHttpServletResponse(), new Object()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsAdminPathWithoutAgreementCheck() throws Exception {
|
||||
MockHttpServletRequest request = authenticatedRequest(9L);
|
||||
request.setRequestURI("/admin/dashboard/overview");
|
||||
|
||||
assertTrue(interceptor.preHandle(request, new MockHttpServletResponse(), new Object()));
|
||||
verifyNoInteractions(agreementVersionCacheService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsLegacyAdminApiPrefixWithoutAgreementCheck() throws Exception {
|
||||
MockHttpServletRequest request = authenticatedRequest(9L);
|
||||
request.setRequestURI("/admin/api/dashboard/overview");
|
||||
|
||||
assertTrue(interceptor.preHandle(request, new MockHttpServletResponse(), new Object()));
|
||||
verifyNoInteractions(agreementVersionCacheService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsBusinessPrefixedAdminPathWithoutAgreementCheck() throws Exception {
|
||||
MockHttpServletRequest request = authenticatedRequest(9L);
|
||||
request.setRequestURI("/order/admin/list");
|
||||
|
||||
assertTrue(interceptor.preHandle(request, new MockHttpServletResponse(), new Object()));
|
||||
verifyNoInteractions(agreementVersionCacheService);
|
||||
}
|
||||
|
||||
private MockHttpServletRequest authenticatedRequest(Long userId) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setAttribute("userId", userId);
|
||||
|
||||
@@ -162,10 +162,10 @@ const showError = (msg: string) => {
|
||||
|
||||
/**
|
||||
* 处理服务端 4510(未同意最新协议):
|
||||
* 锁定后续业务请求、广播事件让后台布局弹出既有的同意弹层,并提示用户。
|
||||
* 非后台场景没有弹层,直接新开协议阅读页,引导用户阅读后重新登录同意。
|
||||
* 仅用于用户端(小程序由独立实现处理,C 端页面走这里):锁定后续业务请求、提示用户并打开协议阅读页。
|
||||
* 后台管理端不做协议版本校验,不会进入该分支。
|
||||
*/
|
||||
const handleAgreementRequired = (res: any, isAdminRequest: boolean) => {
|
||||
const handleAgreementRequired = (res: any) => {
|
||||
setAgreementPending(true)
|
||||
if (typeof window !== 'undefined') {
|
||||
window.dispatchEvent(new CustomEvent(AGREEMENT_REQUIRED_EVENT, { detail: res?.data || {} }))
|
||||
@@ -175,7 +175,7 @@ const handleAgreementRequired = (res: any, isAdminRequest: boolean) => {
|
||||
}
|
||||
lastAgreementRequiredTime = Date.now()
|
||||
showError(normalizeApiErrorMessage(res?.message || '用户协议与隐私政策已更新,请阅读并同意后继续使用'))
|
||||
if (!isAdminRequest && typeof window !== 'undefined') {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.open('/legal/user-terms.html', '_blank', 'noopener')
|
||||
}
|
||||
}
|
||||
@@ -277,11 +277,12 @@ const handleTokenExpired = (isAdmin = false, failedToken: string | null = null)
|
||||
|
||||
api.interceptors.request.use(
|
||||
async config => {
|
||||
if (isAgreementPending() && !AGREEMENT_GATE_ALLOWLIST.some(path => config.url?.includes(path))) {
|
||||
const isAdminRequest = isAdminScopedUrl(config.url)
|
||||
// 后台管理端不做协议版本校验:既不进入未同意门禁,也不因门禁状态被拦截。
|
||||
if (!isAdminRequest && isAgreementPending() && !AGREEMENT_GATE_ALLOWLIST.some(path => config.url?.includes(path))) {
|
||||
return Promise.reject(new Error('请先阅读并同意最新版用户协议与隐私政策'))
|
||||
}
|
||||
|
||||
const isAdminRequest = isAdminScopedUrl(config.url)
|
||||
let token = isAdminRequest
|
||||
? (localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken'))
|
||||
: (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken'))
|
||||
@@ -313,7 +314,10 @@ api.interceptors.response.use(
|
||||
const res = response.data
|
||||
if (Number(res?.code) === AGREEMENT_VERSION_REQUIRED_CODE) {
|
||||
const errorMsg = normalizeApiErrorMessage(res?.message || '用户协议与隐私政策已更新,请阅读并同意后继续使用')
|
||||
handleAgreementRequired(res, isAdminScopedUrl(response.config?.url))
|
||||
// 后台管理端已由服务端放行,若历史服务端仍返回 4510,也不触发门禁/提示,避免后台被锁死。
|
||||
if (!isAdminScopedUrl(response.config?.url)) {
|
||||
handleAgreementRequired(res)
|
||||
}
|
||||
return Promise.reject(new Error(errorMsg))
|
||||
}
|
||||
if (res.code !== 200) {
|
||||
|
||||
@@ -70,30 +70,11 @@
|
||||
</a-button>
|
||||
</div>
|
||||
</a-drawer>
|
||||
|
||||
<a-modal
|
||||
v-model:open="agreementModalOpen"
|
||||
title="用户协议与隐私政策已更新"
|
||||
:closable="false"
|
||||
:maskClosable="false"
|
||||
:keyboard="false"
|
||||
:footer="null"
|
||||
>
|
||||
<div class="agreement-gate">
|
||||
<p>新版本{{ agreementVersionText ? `(${agreementVersionText})` : '' }}已发布,请阅读并同意后继续使用后台。</p>
|
||||
<p class="agreement-gate__links">
|
||||
<a href="/legal/user-terms.html" target="_blank" rel="noopener">查看用户协议</a>
|
||||
<span> · </span>
|
||||
<a href="/legal/privacy-policy.html" target="_blank" rel="noopener">查看隐私政策</a>
|
||||
</p>
|
||||
<a-button type="primary" block :loading="agreementAccepting" @click="acceptAgreements">同意并继续</a-button>
|
||||
</div>
|
||||
</a-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { message, Modal } from 'ant-design-vue'
|
||||
import { DownOutlined, HomeOutlined, LogoutOutlined, MenuFoldOutlined, MenuOutlined, MenuUnfoldOutlined, SafetyCertificateOutlined, TeamOutlined, ToolOutlined, UserOutlined } from '@ant-design/icons-vue'
|
||||
@@ -103,8 +84,6 @@ import { DEFAULT_AVATAR } from '@/constants'
|
||||
import { completeAdminLogout } from '@/utils/admin-logout'
|
||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||
import { useAdminViewport } from '@/composables/useAdminViewport'
|
||||
import { legalAgreementApi, type AgreementPending } from '@/api/auth'
|
||||
import { AGREEMENT_REQUIRED_EVENT, setAgreementPending } from '@/utils/agreement-gate'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
@@ -113,9 +92,6 @@ const collapsed = ref(false)
|
||||
const mobileDrawerOpen = ref(false)
|
||||
const selectedKeys = ref<string[]>([route.path])
|
||||
const userInfo = ref<any>(null)
|
||||
const agreementModalOpen = ref(false)
|
||||
const agreementAccepting = ref(false)
|
||||
const agreementVersionText = ref('')
|
||||
const iconMap: Record<AdminNavIconKey, Component> = { home: HomeOutlined, user: UserOutlined, shop: HomeOutlined, security: SafetyCertificateOutlined, tool: ToolOutlined, team: TeamOutlined, dashboard: HomeOutlined, gift: HomeOutlined, message: HomeOutlined, tag: HomeOutlined, shopping: HomeOutlined, calendar: HomeOutlined }
|
||||
const menuItems = adminNavigationItems.map(item => ({ key: item.path, label: item.label, icon: iconMap[item.iconKey] }))
|
||||
|
||||
@@ -123,51 +99,9 @@ const handleMenuClick = ({ key }: { key: string | number }) => router.push(Strin
|
||||
const openMobileMenu = ({ key }: { key: string | number }) => { mobileDrawerOpen.value = false; router.push(String(key)) }
|
||||
const handleLogout = () => Modal.confirm({ title: '确认退出登录', content: '退出后需要重新登录后台。', okText: '确认', cancelText: '取消', onOk: async () => { await runWithGlobalLoading(() => completeAdminLogout(router)); message.success('已退出登录') } })
|
||||
|
||||
const checkAgreementGate = async () => {
|
||||
try {
|
||||
const result = await legalAgreementApi.getPending() as unknown as AgreementPending
|
||||
if (result?.pending) {
|
||||
agreementVersionText.value = result.currentVersions?.USER_TERMS || ''
|
||||
setAgreementPending(true)
|
||||
agreementModalOpen.value = true
|
||||
} else {
|
||||
setAgreementPending(false)
|
||||
}
|
||||
} catch (error) {
|
||||
// 查询失败不阻塞后台使用,协议接口仍由服务端登录态校验保护
|
||||
}
|
||||
}
|
||||
|
||||
const acceptAgreements = async () => {
|
||||
if (agreementAccepting.value) return
|
||||
agreementAccepting.value = true
|
||||
try {
|
||||
const result = await legalAgreementApi.accept('WEB') as unknown as AgreementPending
|
||||
if (result?.pending === true) {
|
||||
throw new Error('协议同意状态未更新,请稍后重试')
|
||||
}
|
||||
setAgreementPending(false)
|
||||
agreementModalOpen.value = false
|
||||
message.success('已同意最新版协议')
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '同意协议失败')
|
||||
} finally {
|
||||
agreementAccepting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => route.path, path => { selectedKeys.value = [path] }, { immediate: true })
|
||||
/**
|
||||
* 服务端返回 4510 时由请求层广播该事件,这里复用既有弹层逻辑重新检查协议状态。
|
||||
*/
|
||||
const handleAgreementRequired = () => { checkAgreementGate() }
|
||||
onMounted(() => {
|
||||
try { userInfo.value = JSON.parse(localStorage.getItem('adminUserInfo') || 'null') } catch { userInfo.value = null }
|
||||
window.addEventListener(AGREEMENT_REQUIRED_EVENT, handleAgreementRequired)
|
||||
checkAgreementGate()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener(AGREEMENT_REQUIRED_EVENT, handleAgreementRequired)
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user