useAutoLogin.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import QueryString from 'qs';
  2. import { useUserStore } from '/@/store/modules/user';
  3. import { RouteLocationNormalized } from 'vue-router';
  4. import { useMessage } from '../web/useMessage';
  5. import { AUTO_LOGIN_URL_QUERY } from '/@/router/constant';
  6. import { AxiosError } from 'axios';
  7. /** 自动登录功能的Hook,该Hook是为了部署在同一局域网内的多套系统之间能够无缝切换 */
  8. export function useAutoLogin() {
  9. /** 启用自动登录功能来跳转新的页面 */
  10. function open(url: string, target?: string) {
  11. const userStore = useUserStore();
  12. const qs = QueryString.stringify({
  13. [AUTO_LOGIN_URL_QUERY.key]: AUTO_LOGIN_URL_QUERY.val,
  14. username: userStore.getUserInfo.username,
  15. workNo: userStore.getUserInfo.workNo,
  16. });
  17. window.open(`${url}?${qs}`, target);
  18. }
  19. /** 用在路由守卫里,执行自动登录的逻辑,如果存在符合自动登录标准的query则执行自动登录,返回是否自动登录 */
  20. async function doAutoLogin(route: RouteLocationNormalized): Promise<void> {
  21. if (!route.query) return;
  22. // 这部分在外部的路由守卫里写过了
  23. // if (route.query[AUTO_LOGIN_URL_QUERY.key] !== AUTO_LOGIN_URL_QUERY.val) return;
  24. const { username, workNo } = route.query;
  25. if (!username || !workNo) return;
  26. const params = {
  27. username: username as string,
  28. workNo: workNo as string,
  29. checkKey: new Date().getTime(),
  30. };
  31. const userStore = useUserStore();
  32. try {
  33. await userStore.autoLogin({
  34. ...params,
  35. goHome: false,
  36. });
  37. return;
  38. } catch (e) {
  39. const message = useMessage().createMessage;
  40. message.error((e as AxiosError).message);
  41. throw e;
  42. }
  43. }
  44. return {
  45. /** 启用单点登录功能来跳转新的页面,参数与window.open一致,但需要注意url需要指向登录页 */
  46. open,
  47. /** 用在跳转到的页面上,执行单点登录的逻辑 */
  48. doAutoLogin,
  49. };
  50. }