/** * 统一平台认证工具类 * 合并了 wechatUtil.ts, wechat.ts 和 auth-platform.ts 的功能 */ import type { RouteLocationNormalized } from 'vue-router' import { PLATFORM_ROUTE_MAP, PlatformType } from '@af-mobile-client-vue3/types/platform' import { detectEnvironment } from '@af-mobile-client-vue3/utils/environment' /** * 认证参数接口 */ export interface AuthParams { /** 授权码 */ code?: string /** 状态参数 */ state?: string /** 租户名称 */ tenantName?: string /** 平台类型 */ platformType?: PlatformType /** 错误信息 */ error?: string /** 错误描述 */ error_description?: string } /** * 微信回调参数接口(向后兼容) */ export interface WechatCallbackParams extends AuthParams { } /** * 外部用户检测结果接口 */ export interface ExternalUserResult { /** 是否为外部用户 */ isExternal: boolean /** 认证参数(仅当 isExternal 为 true 且有授权参数时存在) */ authParams?: { code?: string state?: string tenantName?: string platformType?: string platformUserId?: string } } /** * 统一的外部用户检测函数 * 这是系统中唯一的用户类型检测入口,仅在路由守卫中调用 * 集成了用户类型检测和认证参数解析功能 * * @param to 目标路由对象 * @returns 外部用户检测结果,包含是否为外部用户和认证参数 */ export function isExternalUser(to: RouteLocationNormalized): ExternalUserResult { console.log('[Platform Detection] 开始检测外部用户环境', { path: to.path, query: to.query }) // 第一层检测:URL参数检测(最高优先级)判断公众号登录逻辑 // 检查路由查询参数中是否有授权参数(code + state) const { code, state, appData } = to.query if (code && state) { // 解析认证参数 const authParams = { code: code as string, state: state as string, tenantName: state as string, platformUserId: code as string, platformType: PlatformType.WECHAT_OFFICIAL, } return { isExternal: true, authParams, } } // 第二层检测:User-Agent环境检测 // 检查浏览器环境是否为第三方平台 const env = detectEnvironment() // 微信小程序 if (env.isMiniprogram && appData) { const authParams = { platformType: PlatformType.WECHAT_MINI, appData, } // 暂未实现 后续需要增加登陆参数 return { isExternal: true, authParams, } } // 微信环境检测 if (env.isWechat) { console.log('[Platform Detection] 检测到微信环境,判定为外部用户(无授权参数)') return { isExternal: true, authParams: Object.assign(to.query, { platformType: PlatformType.WECHAT_OFFICIAL, tenantName: to.query.state as string || '', }), } } // 支付宝环境检测 if (env.isAlipayClient) { // 暂未实现 后续需要增加登陆参数 return { isExternal: true, authParams: { platformType: PlatformType.ALIPAY, }, } } // 钉钉环境检测 if (env.isDingTalk) { // 暂未实现 后续需要增加登陆参数 return { isExternal: true, authParams: { platformType: PlatformType.DINGTALK, }, } } // 第三层检测:路由前缀检测 // 检查路径是否以外部用户路由前缀开头 const platformPrefixes = Object.values(PLATFORM_ROUTE_MAP) const isExternalRoute = platformPrefixes.some(prefix => to.path.startsWith(prefix)) || to.path.startsWith('/ex/') if (isExternalRoute) { // 暂未实现 后续需要增加登陆参数 return { isExternal: true, authParams: Object.assign(to.query, { platformType: PlatformType.WECHAT_OFFICIAL, tenantName: to.query.state as string || '', }), } } // [Platform Detection] 未检测到外部用户环境,判定为内部用户 return { isExternal: false } } // 兼容性导出 - 保持向后兼容 export function isWechat(): boolean { const ua = navigator.userAgent.toLowerCase() return /micromessenger/i.test(ua) }