hookehuyr

refactor(router): 将checkAuth函数改为异步并添加用户信息请求逻辑

将checkAuth函数从同步改为异步,并添加了请求用户信息接口的逻辑,以便在成功获取用户信息时更新本地存储。这样可以更好地处理用户登录状态的检查。
/*
* @Date: 2025-03-20 20:36:36
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-03-26 09:55:40
* @LastEditTime: 2025-03-26 10:07:48
* @FilePath: /mlaj/src/router/guards.js
* @Description: 路由守卫逻辑
*/
import { getAuthInfoAPI } from '@/api/auth'
import { getUserInfoAPI } from '@/api/users'
import { wxInfo } from "@/utils/tools"
import { wxInfo } from '@/utils/tools'
// 需要登录才能访问的路由
export const authRequiredRoutes = [
......@@ -29,21 +29,23 @@ export const authRequiredRoutes = [
export const checkWxAuth = async () => {
if (!import.meta.env.DEV && wxInfo().isWeiXin) {
try {
const { code, data } = await getAuthInfoAPI();
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)
});
res: encodeURIComponent(
location.origin + location.pathname + location.hash,
),
})
if (import.meta.env.DEV) {
params.append('test_openid', import.meta.env.VITE_OPENID);
params.append('test_openid', import.meta.env.VITE_OPENID)
}
location.href = `/srv/?${params.toString()}`;
return false;
location.href = `/srv/?${params.toString()}`
return false
}
} catch (error) {
console.error('微信授权检查失败:', error)
......@@ -53,20 +55,18 @@ export const checkWxAuth = async () => {
}
// 登录权限检查
export const checkAuth = (to) => {
// TODO: 模拟测试接口
// export const checkAuth = async (to) => {
// try {
// // 先请求用户信息接口
// const { code, data } = await getUserInfoAPI();
// if (code) {
// // 如果成功获取用户信息,更新currentUser并允许访问
// localStorage.setItem('currentUser', JSON.stringify(data));
// return true;
// }
// } catch (error) {
// console.error('获取用户信息失败:', error);
// }
export const checkAuth = async (to) => {
try {
// 先请求用户信息接口
const { code, data } = await getUserInfoAPI()
if (code) {
// 如果成功获取用户信息,更新currentUser并允许访问
localStorage.setItem('currentUser', JSON.stringify(data))
return true
}
} catch (error) {
console.error('获取用户信息失败:', error)
}
// 如果接口请求失败或返回401,继续原有的本地存储判断逻辑
const currentUser = JSON.parse(localStorage.getItem('currentUser'))
......