1
Some checks failed
CI / Test (ubuntu-latest) (push) Has been cancelled
CI / Test (windows-latest) (push) Has been cancelled
CI / Lint (ubuntu-latest) (push) Has been cancelled
CI / Lint (windows-latest) (push) Has been cancelled
CI / Check (ubuntu-latest) (push) Has been cancelled
CI / Check (windows-latest) (push) Has been cancelled
CodeQL / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Website on push / Deploy Push Playground Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Docs Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Antd Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Element Ftp (push) Has been cancelled
Deploy Website on push / Deploy Push Naive Ftp (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
CI / CI OK (push) Has been cancelled
Deploy Website on push / Rerun on failure (push) Has been cancelled
Lock Threads / action (push) Has been cancelled
Issue Close Require / close-issues (push) Has been cancelled
Close stale issues / stale (push) Has been cancelled

This commit is contained in:
杨志
2025-12-05 13:39:40 +08:00
parent 21107f02fd
commit 51a72f1f0c
1239 changed files with 107262 additions and 1 deletions

View File

@@ -0,0 +1,151 @@
import type { Recordable, UserInfo } from '@vben/types';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';
import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';
import { getAccessCodesApi, getUserInfoApi, loginApi, logoutApi } from '#/api';
import { $t } from '#/locales';
export const useAuthStore = defineStore('auth', () => {
const accessStore = useAccessStore();
const userStore = useUserStore();
const router = useRouter();
const loginLoading = ref(false);
/**
* 异步处理登录操作
* Asynchronously handle the login process
* @param params 登录表单数据
*/
async function authLogin(
params: Recordable<any>,
onSuccess?: () => Promise<void> | void,
) {
// 异步处理用户登录操作并获取 accessToken
let userInfo: null | UserInfo = null;
try {
loginLoading.value = true;
const loginResult = await loginApi(params as { username: string; password: string });
// 登录成功(根据 API.mdcode 200 表示成功)
// 如果返回数据中有 accessToken则使用它否则使用 Session 认证
const accessToken = loginResult?.accessToken || loginResult?.token || 'session';
// 设置 accessTokenSession 认证时可以使用固定值)
accessStore.setAccessToken(accessToken);
// 获取用户信息并存储到 accessStore 中
try {
const [fetchUserInfoResult, accessCodesResult] = await Promise.allSettled([
fetchUserInfo(),
getAccessCodesApi().catch(() => []), // 如果接口不存在,返回空数组
]);
userInfo = fetchUserInfoResult.status === 'fulfilled'
? fetchUserInfoResult.value
: null;
if (userInfo) {
userStore.setUserInfo(userInfo);
}
if (accessCodesResult.status === 'fulfilled') {
accessStore.setAccessCodes(accessCodesResult.value);
} else {
accessStore.setAccessCodes([]);
}
// 重置路由检查状态,让路由守卫重新生成路由
accessStore.setIsAccessChecked(false);
if (accessStore.loginExpired) {
accessStore.setLoginExpired(false);
} else {
if (onSuccess) {
await onSuccess?.();
} else {
// 跳转到首页,让路由守卫处理路由生成和跳转
const homePath = userInfo?.homePath || '/dashboard/analytics';
await router.push(homePath);
}
}
if (userInfo?.realName) {
notification.success({
description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
duration: 3,
message: $t('authentication.loginSuccess'),
});
} else {
notification.success({
description: $t('authentication.loginSuccessDesc'),
duration: 3,
message: $t('authentication.loginSuccess'),
});
}
} catch (error) {
console.error('获取用户信息失败:', error);
// 重置路由检查状态
accessStore.setIsAccessChecked(false);
// 即使获取用户信息失败,也允许跳转
await router.push('/dashboard/analytics');
}
} catch (error) {
console.error('登录失败:', error);
throw error;
} finally {
loginLoading.value = false;
}
return {
userInfo,
};
}
async function logout(redirect: boolean = true) {
try {
await logoutApi();
} catch {
// 不做任何处理
}
resetAllStores();
accessStore.setLoginExpired(false);
// 回登录页带上当前路由地址
await router.replace({
path: LOGIN_PATH,
query: redirect
? {
redirect: encodeURIComponent(router.currentRoute.value.fullPath),
}
: {},
});
}
async function fetchUserInfo() {
let userInfo: null | UserInfo = null;
userInfo = await getUserInfoApi();
userStore.setUserInfo(userInfo);
return userInfo;
}
function $reset() {
loginLoading.value = false;
}
return {
$reset,
authLogin,
fetchUserInfo,
loginLoading,
logout,
};
});