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'; import { AxiosError } from 'axios'; import { tokenLogin, getUserInfo } from '/@/api/sys/user'; import { isArray } from '/@/utils/is'; import { RoleEnum } from '/@/enums/roleEnum'; /** 自动登录功能的Hook,该Hook是为了部署在同一局域网内的多套系统之间能够无缝切换 */ export function useAutoLogin() { const userStore = useUserStore(); /** 获取自动登录的url */ function getUrl(baseUrl: string, extraQuery: Record = {}) { const qs = QueryString.stringify({ [AUTO_LOGIN_URL_QUERY.key]: AUTO_LOGIN_URL_QUERY.val, realname: userStore.getUserInfo.realname, workNo: userStore.getUserInfo.workNo, ...extraQuery, }); return `${baseUrl}?${qs}`; } /** 启用自动登录功能来跳转新的页面 */ function open(url: string, target?: string) { window.open(getUrl(url), target); } /** 判断当前路由是否需要自动登录,本方法是同步方法,可以用于事先判断 */ function validateRoute(route: RouteLocationNormalized) { if (route.query && route.query[AUTO_LOGIN_URL_QUERY.key] === AUTO_LOGIN_URL_QUERY.val) { return true; } return false; } /** 根据路由是否携带token,判断是否走根据token获取人员信息的接口试下假登录 */ function tokenValidateRoute(route: RouteLocationNormalized) { if (route.query && Object.keys(route.query).length == 1 && route.query['token']) { return true; } return false; } /** * 用在路由守卫里,执行自动登录的逻辑,如果存在符合自动登录标准的query则执行自动登录,返回是否自动登录 * * 该方法需要修改query * */ async function doAutoLogin(route: RouteLocationNormalized): Promise { if (!validateRoute(route)) return; const { realname, workNo } = route.query; if (!realname || !workNo) return; const params = { username: realname as string, workNo: workNo as string, checkKey: new Date().getTime(), }; const userStore = useUserStore(); try { await userStore.autoLogin({ ...params, goHome: false, }); delete route.query[AUTO_LOGIN_URL_QUERY.key]; delete route.query['realname']; delete route.query['workNo']; return; } catch (e) { const message = useMessage().createMessage; message.error((e as AxiosError).message); throw e; } } // token 登录 async function doTokenLogin(token: string) { const res = await tokenLogin({ token }); userStore.setUserInfo(res['userInfo']); userStore.setAllDictItems(res['sysAllDictItems']); userStore.setToken(res['token']); } return { /** 启用单点登录功能来跳转新的页面,参数与window.open一致 */ open, /** 用在跳转到的页面上,执行单点登录的逻辑 */ doAutoLogin, /** 获取自动登录的url */ getUrl, /** 判断当前路由是否需要自动登录,本方法是同步方法,可以用于事先判断 */ validateRoute, tokenValidateRoute, doTokenLogin, }; }