useAutoLogin.ts 1.9 KB

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