// 本来应该是后端做,出于工期考虑转到前端 import QueryString from 'qs'; import { useUserStore } from '/@/store/modules/user'; import { RouteLocationNormalized } from 'vue-router'; import { useMessage } from '../web/useMessage'; import { AUTO_LOGIN_URL_QUERY } from '/@/router/constant'; /** 自动登录功能的Hook,该Hook是为了部署在同一局域网内的多套系统之间能够无缝切换 */ export function useAutoLogin() { /** 启用自动登录功能来跳转新的页面 */ function open(url: string, redirect?: string, target?: string) { const userStore = useUserStore(); const qs = QueryString.stringify({ [AUTO_LOGIN_URL_QUERY.key]: AUTO_LOGIN_URL_QUERY.val, username: userStore.getUserInfo.username, workNo: userStore.getUserInfo.workNo, redirect, }); window.open(`${url}?${qs}`, target); } /** 用在路由守卫里,执行自动登录的逻辑,如果存在符合自动登录标准的query则执行自动登录,返回是否需要重定向 */ async function doAutoLogin(route: RouteLocationNormalized): Promise { const userStore = useUserStore(); if (!route.query) return false; if (route.query[AUTO_LOGIN_URL_QUERY.key] !== AUTO_LOGIN_URL_QUERY.val) return false; const { username, workNo } = route.query; if (!username || !workNo) return false; const params = { username: username as string, workNo: workNo as string, checkKey: new Date().getTime(), }; try { await userStore.autoLogin(params); return true; } catch (e: any) { const message = useMessage().createMessage; message.error(e.message); return false; } } return { /** 启用单点登录功能来跳转新的页面,参数与window.open一致,但需要注意url需要指向登录页 */ open, /** 用在跳转到的页面上,执行单点登录的逻辑 */ doAutoLogin, }; }