permission.ts 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { to as tos} from 'await-to-js';
  2. import router from './router';
  3. import NProgress from 'nprogress';
  4. import 'nprogress/nprogress.css';
  5. import {getToken} from '@/utils/auth';
  6. import {isHttp} from '@/utils/validate';
  7. import {isRelogin} from '@/utils/request';
  8. import useUserStore from '@/store/modules/user';
  9. import useSettingsStore from '@/store/modules/settings';
  10. import usePermissionStore from '@/store/modules/permission';
  11. import useAppStore from '@/store/modules/app';
  12. import { useNoticeStore } from '@/store/modules/notice'
  13. import {LoginData} from "@/api/types";
  14. import { resolveModuleByPath } from '@/enums/ModuleEnum';
  15. NProgress.configure({ showSpinner: false });
  16. import { setToken } from '@/utils/auth';
  17. import { ElMessage } from 'element-plus';
  18. const whiteList = ['/login', '/register', '/social-callback'];
  19. router.beforeEach(async (to, from, next) => {
  20. NProgress.start();
  21. // 同步顶部模块激活态:以路由 meta.module 为准;没有则按 path 反查
  22. const moduleFromMeta = (to.meta as any)?.module;
  23. const moduleKey = moduleFromMeta || resolveModuleByPath(to.path);
  24. if (moduleKey) {
  25. useAppStore().setActiveModule(moduleKey);
  26. }
  27. // https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww5323bd8ab4394132&redirect_uri=https%3A%2F%2Fsales.test.storlead.com%2Findex&response_type=code&scope=snsapi_base&agentid=1000033&state=fromQYwx#wechat_redirect
  28. if(to.query.code && to.query.state === 'fromQYwx') {
  29. const userStore = useUserStore();
  30. const loginForm = ref<LoginData>({
  31. wxCode: to.query.code as string
  32. });
  33. const res = await tos(userStore.loginWx(loginForm.value));
  34. // if(err){
  35. // ElMessage.error('授权登录失败,请用账号密码登录');
  36. // next({path: '/login'});
  37. // return
  38. // }
  39. let param = {}
  40. Object.keys(to.query).forEach(item=>{
  41. if(item!=="code"){
  42. param[item] = to.query[item]
  43. }
  44. })
  45. let path = to.path + "?" + Object.keys(param).map(item=>item+"="+param[item]).join("&")
  46. next(path)
  47. return
  48. }
  49. // /sys/auth/login
  50. if (getToken()) {
  51. to.meta.title && useSettingsStore().setTitle(to.meta.title as string);
  52. /* has token*/
  53. if (to.path === '/login') {
  54. next({path: '/home'});
  55. NProgress.done();
  56. } else if (whiteList.indexOf(to.path) !== -1) {
  57. next()
  58. } else {
  59. next();
  60. }
  61. } else {
  62. // 没有token
  63. if (whiteList.indexOf(to.path) !== -1) {
  64. // 在免登录白名单,直接进入
  65. next();
  66. } else {
  67. next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
  68. NProgress.done();
  69. }
  70. }
  71. });
  72. router.afterEach(() => {
  73. NProgress.done();
  74. });