guards.js 1.92 KB
/*
 * @Date: 2025-03-20 20:36:36
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-03-26 08:04:21
 * @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,
  },
]

// 微信授权检查
export const checkWxAuth = async () => {
  if (!import.meta.env.DEV && wxInfo().isWeiXin) {
    try {
      const { code, data } = await getAuthInfoAPI();
      if (code && !data.openid_has) {
        // 直接在这里处理授权跳转
        const params = new URLSearchParams({
          f: 'behalo',
          a: 'openid',
          res: encodeURIComponent(location.origin + location.pathname + location.hash)
        });

        if (import.meta.env.DEV) {
          params.append('test_openid', import.meta.env.VITE_OPENID);
        }

        location.href = `/srv/?${params.toString()}`;
        return false;
      }
    } catch (error) {
      console.error('微信授权检查失败:', error)
    }
  }
  return true
}

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

  // 检查当前路由是否需要认证
  const needAuth = 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)
  })

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

  return true
}