guards.js 2.18 KB
/*
 * @Date: 2025-03-20 20:36:36
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-11-19 20:37:35
 * @FilePath: /mlaj/src/router/guards.js
 * @Description: 路由守卫逻辑
 */
import { getAuthInfoAPI } from '@/api/auth'
import { wxInfo } from "@/utils/tools"

// 需要登录才能访问的路由
export const authRequiredRoutes = [
  {
    path: '/profile',
    exact: false,
  },
  {
    path: '/checkout',
    exact: true,
  },
  {
    path: '/activities/[^/]+/signup',
    regex: true,
  },
  {
    path: '/checkin',
    exact: false,
  },
  {
    path: '/teacher',
    exact: false,
  },
]

// TAG: 微信授权检查
export const checkWxAuth = async () => {
  if (!import.meta.env.DEV && wxInfo().isWeiXin) {
    try {
      const { code, data } = await getAuthInfoAPI();
      if (code && !data.openid_has) {
        // 直接在这里处理授权跳转
        let raw_url = encodeURIComponent(location.href); // 未授权的地址
        const short_url = `/srv/?f=behalo&a=openid&res=${raw_url}`;
        location.href = short_url;

        return false;
      }
    } catch (error) {
      console.error('微信授权检查失败:', error)
    }
  }
  return true
}

// 检查用户是否已登录


// 登录权限检查
export const checkAuth = (to) => {
  const currentUser = JSON.parse(localStorage.getItem('currentUser'))

  // 检查当前路由是否需要认证
  // 方式一:白名单匹配(兼容旧逻辑)
  const needAuthByList = authRequiredRoutes.some((route) => {
    // 如果是正则匹配模式
    if (route.regex) {
      return new RegExp(`^${route.path}$`).test(to.path)
    }
    // 如果是精确匹配模式
    if (route.exact) {
      return to.path === route.path
    }
    // 默认前缀匹配模式
    return to.path.startsWith(route.path)
  })
  // 方式二:读取路由元信息 requiresAuth(推荐)
  const needAuthByMeta = to.matched.some(record => record.meta && record.meta.requiresAuth === true)
  const needAuth = needAuthByList || needAuthByMeta

  if (needAuth && !currentUser) {
    // 未登录时重定向到登录页面
    return { path: '/login', query: { redirect: to.fullPath } }
    // return { path: '/login' }
  }

  return true
}