useAutoLogin.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. /** 获取自动登录的url */
  10. function getUrl(baseUrl: string, extraQuery: Record<string, string> = {}) {
  11. const userStore = useUserStore();
  12. const qs = QueryString.stringify({
  13. [AUTO_LOGIN_URL_QUERY.key]: AUTO_LOGIN_URL_QUERY.val,
  14. realname: userStore.getUserInfo.realname,
  15. workNo: userStore.getUserInfo.workNo,
  16. ...extraQuery,
  17. });
  18. return `${baseUrl}?${qs}`;
  19. }
  20. /** 启用自动登录功能来跳转新的页面 */
  21. function open(url: string, target?: string) {
  22. window.open(getUrl(url), target);
  23. }
  24. /** 判断当前路由是否需要自动登录,本方法是同步方法,可以用于事先判断 */
  25. function validateRoute(route: RouteLocationNormalized) {
  26. if (route.query && route.query[AUTO_LOGIN_URL_QUERY.key] === AUTO_LOGIN_URL_QUERY.val) {
  27. return true;
  28. }
  29. return false;
  30. }
  31. /** 用在路由守卫里,执行自动登录的逻辑,如果存在符合自动登录标准的query则执行自动登录,返回是否自动登录 */
  32. async function doAutoLogin(route: RouteLocationNormalized): Promise<void> {
  33. if (!validateRoute(route)) return;
  34. const { realname, workNo } = route.query;
  35. if (!realname || !workNo) return;
  36. const params = {
  37. username: realname as string,
  38. workNo: workNo as string,
  39. checkKey: new Date().getTime(),
  40. };
  41. const userStore = useUserStore();
  42. try {
  43. await userStore.autoLogin({
  44. ...params,
  45. goHome: false,
  46. });
  47. delete route.query[AUTO_LOGIN_URL_QUERY.key];
  48. delete route.query['username'];
  49. delete route.query['workNo'];
  50. return;
  51. } catch (e) {
  52. const message = useMessage().createMessage;
  53. message.error((e as AxiosError).message);
  54. throw e;
  55. }
  56. }
  57. return {
  58. /** 启用单点登录功能来跳转新的页面,参数与window.open一致 */
  59. open,
  60. /** 用在跳转到的页面上,执行单点登录的逻辑 */
  61. doAutoLogin,
  62. /** 获取自动登录的url */
  63. getUrl,
  64. /** 判断当前路由是否需要自动登录,本方法是同步方法,可以用于事先判断 */
  65. validateRoute,
  66. };
  67. }