Showing
5 changed files
with
258 additions
and
23 deletions
This diff is collapsed. Click to expand it.
| ... | @@ -7,6 +7,7 @@ | ... | @@ -7,6 +7,7 @@ |
| 7 | * @Description: | 7 | * @Description: |
| 8 | */ | 8 | */ |
| 9 | import { onMounted, onUnmounted } from 'vue' | 9 | import { onMounted, onUnmounted } from 'vue' |
| 10 | +export { useAuthRedirect } from './useAuthRedirect.js' | ||
| 10 | 11 | ||
| 11 | /** | 12 | /** |
| 12 | * 添加和清除 DOM 事件监听器 | 13 | * 添加和清除 DOM 事件监听器 | ... | ... |
src/composables/useAuthRedirect.js
0 → 100644
| 1 | +/* | ||
| 2 | + * @Date: 2026-05-29 00:00:00 | ||
| 3 | + * @Description: 授权跳转辅助逻辑 | ||
| 4 | + */ | ||
| 5 | +import { useRoute } from 'vue-router'; | ||
| 6 | + | ||
| 7 | +// 授权返回后的首轮路由检查只需要跳过一次,避免刚拿到 openid 又被周期选择打断 | ||
| 8 | +const SKIP_CYCLE_CHECK_FOR_AUTH_KEY = 'skip_cycle_check_for_auth'; | ||
| 9 | +// 只记录“这一轮刚发起过授权”的短期状态,供授权返回后修正浏览器后退行为 | ||
| 10 | +const AUTH_RETURN_GUARD_KEY = 'data-table-auth-return-guard'; | ||
| 11 | +// 只保留很短时间,避免授权链路中断后残留旧标记 | ||
| 12 | +const AUTH_RETURN_GUARD_TTL = 10 * 60 * 1000; | ||
| 13 | + | ||
| 14 | +const toStringQueryValue = (value) => (typeof value === 'string' ? value : ''); | ||
| 15 | + | ||
| 16 | +const getQueryValueFromString = (search, key) => { | ||
| 17 | + if (!search) return ''; | ||
| 18 | + const params = new URLSearchParams(search.startsWith('?') ? search : `?${search}`); | ||
| 19 | + return params.get(key) || ''; | ||
| 20 | +}; | ||
| 21 | + | ||
| 22 | +const safeDecodeURIComponent = (value) => { | ||
| 23 | + try { | ||
| 24 | + return decodeURIComponent(value); | ||
| 25 | + } catch (error) { | ||
| 26 | + return value; | ||
| 27 | + } | ||
| 28 | +}; | ||
| 29 | + | ||
| 30 | +/** | ||
| 31 | + * 消耗一次“跳过首次周期检查”的标记。 | ||
| 32 | + * 命中后会立即清理,确保它只影响授权返回的这一轮路由。 | ||
| 33 | + * @returns {boolean} 是否需要跳过一次周期检查 | ||
| 34 | + */ | ||
| 35 | +export const consumeSkipCycleCheckForAuth = () => { | ||
| 36 | + const shouldSkip = sessionStorage.getItem(SKIP_CYCLE_CHECK_FOR_AUTH_KEY) === 'true'; | ||
| 37 | + if (shouldSkip) { | ||
| 38 | + sessionStorage.removeItem(SKIP_CYCLE_CHECK_FOR_AUTH_KEY); | ||
| 39 | + } | ||
| 40 | + return shouldSkip; | ||
| 41 | +}; | ||
| 42 | + | ||
| 43 | +const clearAuthReturnGuard = () => { | ||
| 44 | + sessionStorage.removeItem(AUTH_RETURN_GUARD_KEY); | ||
| 45 | +}; | ||
| 46 | + | ||
| 47 | +const readAuthReturnGuard = () => { | ||
| 48 | + try { | ||
| 49 | + const state = JSON.parse(sessionStorage.getItem(AUTH_RETURN_GUARD_KEY) || '{}'); | ||
| 50 | + if (!state?.createdAt || Date.now() - state.createdAt > AUTH_RETURN_GUARD_TTL) { | ||
| 51 | + clearAuthReturnGuard(); | ||
| 52 | + return null; | ||
| 53 | + } | ||
| 54 | + return state; | ||
| 55 | + } catch (error) { | ||
| 56 | + clearAuthReturnGuard(); | ||
| 57 | + return null; | ||
| 58 | + } | ||
| 59 | +}; | ||
| 60 | + | ||
| 61 | +/** | ||
| 62 | + * 统一管理授权页与业务页之间共用的跳转能力。 | ||
| 63 | + * 这里不保存“授权成功”长期标记,避免后端授权失效后前端还拿旧状态误判。 | ||
| 64 | + * @param {import('vue-router').RouteLocationNormalizedLoaded} route 当前路由实例 | ||
| 65 | + * @returns {{ | ||
| 66 | + * getQueryValue: (key: string) => string, | ||
| 67 | + * getCurrentTargetHash: () => string, | ||
| 68 | + * getAuthTargetHash: () => string, | ||
| 69 | + * buildOpenIdAuthUrl: (code: string, targetHash?: string) => string, | ||
| 70 | + * redirectToOpenIdAuth: (code: string, targetHash?: string) => void, | ||
| 71 | + * savePendingAuthReturnGuard: (code: string, targetHash?: string) => void, | ||
| 72 | + * consumePendingAuthReturnGuard: (code: string, targetHash?: string) => { historyLength: number } | null, | ||
| 73 | + * installAuthBackHistoryGuard: () => void, | ||
| 74 | + * markSkipCycleCheckForAuth: () => void, | ||
| 75 | + * consumeSkipCycleCheckForAuth: () => boolean | ||
| 76 | + * }} | ||
| 77 | + */ | ||
| 78 | +export function useAuthRedirect(route = useRoute()) { | ||
| 79 | + const getQueryValue = (key) => { | ||
| 80 | + const routeValue = toStringQueryValue(route.query[key]); | ||
| 81 | + if (routeValue) return routeValue; | ||
| 82 | + | ||
| 83 | + // 兼容两类入口: | ||
| 84 | + // 1. hash 路由标准参数:#/path?code=xxx | ||
| 85 | + // 2. 老入口或外部重定向参数:index.html?code=xxx#/path | ||
| 86 | + const searchValue = getQueryValueFromString(location.search, key); | ||
| 87 | + if (searchValue) return searchValue; | ||
| 88 | + | ||
| 89 | + const hash = location.hash || ''; | ||
| 90 | + const hashQueryIndex = hash.indexOf('?'); | ||
| 91 | + if (hashQueryIndex >= 0) { | ||
| 92 | + const hashSearch = hash.slice(hashQueryIndex + 1); | ||
| 93 | + return getQueryValueFromString(hashSearch, key); | ||
| 94 | + } | ||
| 95 | + | ||
| 96 | + return ''; | ||
| 97 | + }; | ||
| 98 | + | ||
| 99 | + // 当前表单页在 hash 模式下的完整路由,授权成功后要回到这里 | ||
| 100 | + const getCurrentTargetHash = () => `${location.search}${location.hash || `#${route.fullPath}`}`; | ||
| 101 | + | ||
| 102 | + // 优先读 target,新链路;兼容 href,避免老链接直接失效 | ||
| 103 | + const getAuthTargetHash = () => { | ||
| 104 | + const rawTarget = getQueryValue('target') || getQueryValue('href'); | ||
| 105 | + return rawTarget ? safeDecodeURIComponent(rawTarget) : ''; | ||
| 106 | + }; | ||
| 107 | + | ||
| 108 | + /** | ||
| 109 | + * 统一拼接 openid 授权链接。 | ||
| 110 | + * 新链路会在业务页里直接 replace 到这个地址,避免先进入站内 auth 页留下额外历史记录。 | ||
| 111 | + * @param {string} code 表单 code | ||
| 112 | + * @param {string} targetHash 授权成功后需要回到的 hash 路由 | ||
| 113 | + * @returns {string} 可直接跳转的授权地址 | ||
| 114 | + */ | ||
| 115 | + const buildOpenIdAuthUrl = (code, targetHash = getCurrentTargetHash()) => { | ||
| 116 | + const rawUrl = encodeURIComponent(`${location.origin}${location.pathname}${targetHash}`); | ||
| 117 | + const shortUrl = `/srv/?f=custom_form&a=openid&res=${rawUrl}&form_code=${code}`; | ||
| 118 | + | ||
| 119 | + // 开发环境继续复用旧的 openid 注入方式,避免影响本地调试体验 | ||
| 120 | + if (import.meta.env.DEV) { | ||
| 121 | + return `${shortUrl}&openid=${import.meta.env.VITE_OPENID}`; | ||
| 122 | + } | ||
| 123 | + | ||
| 124 | + return shortUrl; | ||
| 125 | + }; | ||
| 126 | + | ||
| 127 | + /** | ||
| 128 | + * 直接跳到后端 openid 授权地址。 | ||
| 129 | + * 使用 location.replace 是为了把“当前未授权页”替换掉,避免浏览器后退时再落回授权中转页。 | ||
| 130 | + * @param {string} code 表单 code | ||
| 131 | + * @param {string} targetHash 授权成功后需要回到的 hash 路由 | ||
| 132 | + */ | ||
| 133 | + const redirectToOpenIdAuth = (code, targetHash = getCurrentTargetHash()) => { | ||
| 134 | + window.location.replace(buildOpenIdAuthUrl(code, targetHash)); | ||
| 135 | + }; | ||
| 136 | + | ||
| 137 | + /** | ||
| 138 | + * 记录一次待返回的授权流程。 | ||
| 139 | + * 这里只保存当前目标页和发起前的历史长度,返回后会立刻消费掉,不作为长期登录态判断。 | ||
| 140 | + * @param {string} code 表单 code | ||
| 141 | + * @param {string} targetHash 授权成功后需要回到的 hash 路由 | ||
| 142 | + */ | ||
| 143 | + const savePendingAuthReturnGuard = (code, targetHash = getCurrentTargetHash()) => { | ||
| 144 | + sessionStorage.setItem( | ||
| 145 | + AUTH_RETURN_GUARD_KEY, | ||
| 146 | + JSON.stringify({ | ||
| 147 | + code, | ||
| 148 | + targetHash, | ||
| 149 | + historyLength: window.history.length, | ||
| 150 | + createdAt: Date.now(), | ||
| 151 | + }), | ||
| 152 | + ); | ||
| 153 | + }; | ||
| 154 | + | ||
| 155 | + /** | ||
| 156 | + * 消费一次授权返回标记。 | ||
| 157 | + * 只有当前页面和发起授权时记录的目标页一致,才认为这是同一轮授权返回。 | ||
| 158 | + * @param {string} code 表单 code | ||
| 159 | + * @param {string} targetHash 当前页面 hash | ||
| 160 | + * @returns {{ historyLength: number } | null} 命中的返回信息 | ||
| 161 | + */ | ||
| 162 | + const consumePendingAuthReturnGuard = (code, targetHash = getCurrentTargetHash()) => { | ||
| 163 | + const state = readAuthReturnGuard(); | ||
| 164 | + if (!state) return null; | ||
| 165 | + | ||
| 166 | + const matched = state.code === code && state.targetHash === targetHash; | ||
| 167 | + clearAuthReturnGuard(); | ||
| 168 | + | ||
| 169 | + if (!matched) { | ||
| 170 | + return null; | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + return { | ||
| 174 | + historyLength: Number(state.historyLength) || 0, | ||
| 175 | + }; | ||
| 176 | + }; | ||
| 177 | + | ||
| 178 | + /** | ||
| 179 | + * 在授权成功回到表单后,临时插入一个“同地址跳板”。 | ||
| 180 | + * 这样用户第一次点浏览器后退时,会先回到这个跳板,然后我们再一次性跳过授权地址回到真正的上一页。 | ||
| 181 | + */ | ||
| 182 | + const installAuthBackHistoryGuard = () => { | ||
| 183 | + const guardKey = `auth-back-guard:${Date.now()}`; | ||
| 184 | + const currentState = window.history.state || {}; | ||
| 185 | + | ||
| 186 | + // 当前记录标成“跳板底座” | ||
| 187 | + window.history.replaceState( | ||
| 188 | + { | ||
| 189 | + ...currentState, | ||
| 190 | + __authBackGuardBase: guardKey, | ||
| 191 | + }, | ||
| 192 | + '', | ||
| 193 | + location.href, | ||
| 194 | + ); | ||
| 195 | + | ||
| 196 | + // 再压入一个相同地址的“顶层占位”,让第一次后退先落到上面的底座状态 | ||
| 197 | + window.history.pushState( | ||
| 198 | + { | ||
| 199 | + ...currentState, | ||
| 200 | + __authBackGuardTop: guardKey, | ||
| 201 | + }, | ||
| 202 | + '', | ||
| 203 | + location.href, | ||
| 204 | + ); | ||
| 205 | + | ||
| 206 | + const handlePopState = (event) => { | ||
| 207 | + if (event.state?.__authBackGuardBase !== guardKey) { | ||
| 208 | + return; | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + window.removeEventListener('popstate', handlePopState); | ||
| 212 | + // 当前位置已经从顶层占位退回到底座了,再退两层即可跨过授权地址回到真实上一页 | ||
| 213 | + window.history.go(-2); | ||
| 214 | + }; | ||
| 215 | + | ||
| 216 | + window.addEventListener('popstate', handlePopState); | ||
| 217 | + }; | ||
| 218 | + | ||
| 219 | + /** | ||
| 220 | + * 标记这次授权流程已经进入外部跳转阶段。 | ||
| 221 | + * 这个标记只用于让路由守卫在授权返回时跳过一次周期检查。 | ||
| 222 | + */ | ||
| 223 | + const markSkipCycleCheckForAuth = () => { | ||
| 224 | + sessionStorage.setItem(SKIP_CYCLE_CHECK_FOR_AUTH_KEY, 'true'); | ||
| 225 | + }; | ||
| 226 | + | ||
| 227 | + return { | ||
| 228 | + getQueryValue, | ||
| 229 | + getCurrentTargetHash, | ||
| 230 | + getAuthTargetHash, | ||
| 231 | + buildOpenIdAuthUrl, | ||
| 232 | + redirectToOpenIdAuth, | ||
| 233 | + savePendingAuthReturnGuard, | ||
| 234 | + consumePendingAuthReturnGuard, | ||
| 235 | + installAuthBackHistoryGuard, | ||
| 236 | + markSkipCycleCheckForAuth, | ||
| 237 | + consumeSkipCycleCheckForAuth, | ||
| 238 | + }; | ||
| 239 | +} |
| ... | @@ -13,6 +13,7 @@ import { Loading } from "vant"; | ... | @@ -13,6 +13,7 @@ import { Loading } from "vant"; |
| 13 | import Cookies from 'js-cookie'; | 13 | import Cookies from 'js-cookie'; |
| 14 | import { showUnfinishedFormDialog, resetDialogState } from '@/utils/dialogControl.js'; | 14 | import { showUnfinishedFormDialog, resetDialogState } from '@/utils/dialogControl.js'; |
| 15 | import { getCycleListAPI } from '@/api/cycle'; | 15 | import { getCycleListAPI } from '@/api/cycle'; |
| 16 | +import { consumeSkipCycleCheckForAuth } from '@/composables/useAuthRedirect.js'; | ||
| 16 | 17 | ||
| 17 | // TAG: 路由配置表 | 18 | // TAG: 路由配置表 |
| 18 | /** | 19 | /** |
| ... | @@ -145,13 +146,8 @@ router.beforeEach((to, from, next) => { | ... | @@ -145,13 +146,8 @@ router.beforeEach((to, from, next) => { |
| 145 | return; | 146 | return; |
| 146 | } | 147 | } |
| 147 | 148 | ||
| 148 | - // 检查是否从授权页面返回,如果是首次访问且可能需要授权,则跳过周期检查 | 149 | + // 授权成功回到业务页后的第一轮路由里,跳过一次周期检查,避免刚拿到 openid 又被打断 |
| 149 | - const isFromAuth = from.path === '/auth'; | 150 | + if (consumeSkipCycleCheckForAuth()) { |
| 150 | - const skipCycleCheck = sessionStorage.getItem('skip_cycle_check_for_auth'); | ||
| 151 | - | ||
| 152 | - // 如果不是从授权页面返回,且设置了跳过标识,则先清除标识并跳过周期检查 | ||
| 153 | - if (!isFromAuth && skipCycleCheck === 'true') { | ||
| 154 | - sessionStorage.removeItem('skip_cycle_check_for_auth'); | ||
| 155 | // 直接执行表单检查逻辑,跳过周期检查 | 151 | // 直接执行表单检查逻辑,跳过周期检查 |
| 156 | if (to.query.page_type === 'add' || to.query.page_type === undefined) { | 152 | if (to.query.page_type === 'add' || to.query.page_type === undefined) { |
| 157 | const existingCookie = Cookies.get(to.query.code); | 153 | const existingCookie = Cookies.get(to.query.code); | ... | ... |
| ... | @@ -11,24 +11,23 @@ | ... | @@ -11,24 +11,23 @@ |
| 11 | 11 | ||
| 12 | <script setup> | 12 | <script setup> |
| 13 | import { onMounted } from 'vue' | 13 | import { onMounted } from 'vue' |
| 14 | -import { useRoute } from 'vue-router' | 14 | +import { useAuthRedirect } from '@/composables' |
| 15 | 15 | ||
| 16 | -const $route = useRoute(); | 16 | +const { |
| 17 | + getAuthTargetHash, | ||
| 18 | + getQueryValue, | ||
| 19 | + redirectToOpenIdAuth, | ||
| 20 | + savePendingAuthReturnGuard, | ||
| 21 | + markSkipCycleCheckForAuth, | ||
| 22 | +} = useAuthRedirect(); | ||
| 17 | 23 | ||
| 18 | onMounted(() => { | 24 | onMounted(() => { |
| 19 | - // php需要先跳转链接获取openid | 25 | + const code = getQueryValue('code'); |
| 20 | - /** | 26 | + const targetHash = getAuthTargetHash(); |
| 21 | - * encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。 | 27 | + // 兼容老的 /auth 入口时,也补上同一套一次性回退保护和周期检查跳过标记 |
| 22 | - * 该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。 | 28 | + savePendingAuthReturnGuard(code, targetHash || '#/'); |
| 23 | - * 其他字符(比如 :;/?:@&=+$,# 这些用于分隔 URI 组件的标点符号),都是由一个或多个十六进制的转义序列替换的。 | 29 | + markSkipCycleCheckForAuth(); |
| 24 | - */ | 30 | + // 兼容老的 /auth 入口:统一交给 composable 计算并 replace 到后端授权地址 |
| 25 | - let raw_url = encodeURIComponent(location.origin + location.pathname + $route.query.href); // 未授权的地址 | 31 | + redirectToOpenIdAuth(code, targetHash || '#/'); |
| 26 | - // TAG: 开发环境测试数据 | ||
| 27 | - const short_url = `/srv/?f=custom_form&a=openid&res=${raw_url}&form_code=${$route.query.code}`; | ||
| 28 | - // 使用 replace 方法替代 href,避免在浏览器历史中留下记录 | ||
| 29 | - // 这样用户点击后退按钮时不会回到授权页面 | ||
| 30 | - window.location.replace(import.meta.env.DEV | ||
| 31 | - ? `${short_url}&openid=${import.meta.env.VITE_OPENID}` | ||
| 32 | - : `${short_url}`); | ||
| 33 | }) | 32 | }) |
| 34 | </script> | 33 | </script> | ... | ... |
-
Please register or login to post a comment