permission.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router';
  2. import { routeName } from '@/router';
  3. import { useAuthStore } from '@/store';
  4. import { exeStrategyActions } from '@/utils';
  5. import { createDynamicRouteGuard } from './dynamic';
  6. /** 处理路由页面的权限 */
  7. export async function createPermissionGuard(
  8. to: RouteLocationNormalized,
  9. from: RouteLocationNormalized,
  10. next: NavigationGuardNext
  11. ) {
  12. // 动态路由
  13. const permission = await createDynamicRouteGuard(to, from, next);
  14. if (!permission) return;
  15. // 外链路由, 从新标签打开,返回上一个路由
  16. if (to.meta.href) {
  17. window.open(to.meta.href);
  18. next({ path: from.fullPath, replace: true, query: from.query });
  19. return;
  20. }
  21. const auth = useAuthStore();
  22. // const isLogin = Boolean(localStg.get('token'));
  23. const isLogin = Boolean(localStorage.getItem('token'));
  24. const permissions = to.meta.permissions || [];
  25. const needLogin = Boolean(to.meta?.requiresAuth) || Boolean(permissions.length);
  26. const hasPermission = !permissions.length || permissions.includes(auth.userInfo.userRole);
  27. const actions: Common.StrategyAction[] = [
  28. // 已登录状态跳转登录页,跳转至首页
  29. [
  30. isLogin && to.name === routeName('login'),
  31. () => {
  32. next({ name: routeName('root') });
  33. }
  34. ],
  35. // 不需要登录权限的页面直接通行
  36. [
  37. !needLogin,
  38. () => {
  39. next();
  40. }
  41. ],
  42. // 未登录状态进入需要登录权限的页面
  43. [
  44. !isLogin && needLogin,
  45. () => {
  46. const redirect = to.fullPath;
  47. next({ name: routeName('login'), query: { redirect } });
  48. }
  49. ],
  50. // 登录状态进入需要登录权限的页面,有权限直接通行
  51. [
  52. isLogin && needLogin && hasPermission,
  53. () => {
  54. next();
  55. }
  56. ],
  57. [
  58. // 登录状态进入需要登录权限的页面,无权限,重定向到无权限页面
  59. isLogin && needLogin && !hasPermission,
  60. () => {
  61. next({ name: routeName('403') });
  62. }
  63. ]
  64. ];
  65. exeStrategyActions(actions);
  66. }