Files
cpms_operation_platform/src/hooks/useAuth.ts
T

72 lines
1.9 KiB
TypeScript
Raw Normal View History

2026-07-14 10:31:17 +08:00
// src/hooks/useAuth.ts
import { useState } from './useState';
import { useEffect } from './useEffect';
2026-07-23 11:27:33 +08:00
import { useMenuStore } from '@/stores/menuStore';
import { usePermissionStore } from '@/stores/permissionStore';
import { useTabsStore } from '@/stores/tabsStore';
import { clearAuthDataCache } from '@/api/menu';
2026-07-23 15:00:19 +08:00
import router from '@/router';
2026-07-14 10:31:17 +08:00
const TOKEN_KEY = 'MY_APP_AUTH_TOKEN';
function createAuth() {
const [token, setToken] = useState<string | null>(window.localStorage.getItem(TOKEN_KEY));
useEffect(() => {
const newToken = token.value;
2026-07-14 10:31:17 +08:00
if (newToken) {
window.localStorage.setItem(TOKEN_KEY, newToken);
} else {
window.localStorage.removeItem(TOKEN_KEY);
}
}, [token]);
2026-07-14 10:31:17 +08:00
2026-07-23 11:27:33 +08:00
const isLoggedIn = () => !!token.value;
/**
* 登录:保存 token → 拉取菜单+权限 → 动态注册路由 → 跳转首页
*/
const login = async (newToken: string, targetPath?: string) => {
2026-07-14 10:31:17 +08:00
setToken(newToken);
2026-07-23 11:27:33 +08:00
const { loadMenu, homePath, isRoutePathAvailable } = useMenuStore();
2026-07-23 11:27:33 +08:00
const { loadPermissions } = usePermissionStore();
// 并行拉取菜单和权限
await Promise.all([loadMenu(), loadPermissions()]);
const nextPath =
targetPath && isRoutePathAvailable(targetPath) ? targetPath : homePath.value || '/404';
// 动态路由注册完成后,再跳转到有效目标页
router.push(nextPath);
2026-07-14 10:31:17 +08:00
};
2026-07-23 11:27:33 +08:00
/**
* 退出:清除 token → 清除菜单+权限 → 清除动态路由 → 跳转登录页
*/
2026-07-14 10:31:17 +08:00
const logout = () => {
setToken(null);
2026-07-23 11:27:33 +08:00
const { clearMenu } = useMenuStore();
const { clearPermissions } = usePermissionStore();
const { clearTabs } = useTabsStore();
2026-07-23 11:27:33 +08:00
clearTabs();
2026-07-23 11:27:33 +08:00
clearMenu();
clearPermissions();
clearAuthDataCache();
2026-07-23 11:27:33 +08:00
router.push('/login');
2026-07-14 10:31:17 +08:00
};
return {
token,
2026-07-23 11:27:33 +08:00
isLoggedIn,
2026-07-14 10:31:17 +08:00
login,
logout,
};
}
export const auth = createAuth();