guard.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import router from './index';
  2. import { kuky_Authorization } from '../base/storage';
  3. import { firstPage, accessFlatRoutes } from '../utils/permission';
  4. /** 免验证白名单 */
  5. const whiteList = ['/login', '/reg', '/noPer'];
  6. // 导入所需的模块
  7. router.beforeEach((to, from, next) => {
  8. const isAuthorized = kuky_Authorization.get(); // 获取用户授权状态
  9. const isLoginPage = to.path === '/login'; // 判断目标路径是否为登录页
  10. const firstLogin = from.path === '/login'; // 判断当前路径是否为登录页
  11. const isInWhiteList = whiteList.includes(to.path); // 检查目标路径是否在白名单中
  12. const hasAccess = accessFlatRoutes.some((route) => route.path == to.path);
  13. // 用户已授权的情况
  14. if (isAuthorized) {
  15. if (firstLogin || isLoginPage) {
  16. next(); // 如果是第一次登录,直接进入首页
  17. } else if (!hasAccess && !isInWhiteList) {
  18. // 如果用户无访问权限且不在白名单中
  19. next({ path: '/noPer' }); // 重定向到无权限页面
  20. } else {
  21. next(); // 其他情况,正常访问
  22. }
  23. } else {
  24. // 用户未授权的情况
  25. if (isInWhiteList) {
  26. // 如果目标路径在免登录白名单中
  27. next(); // 允许进入
  28. } else {
  29. next('/login'); // 否则重定向到登录页面
  30. }
  31. }
  32. });