import type { Recordable, UserInfo } from '@vben/types'; import { ref } from 'vue'; import { useRouter } from 'vue-router'; import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; import { useWatermark } from '@vben/hooks'; 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'; const { updateWatermark } = useWatermark(); 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 登录表单数据 * @param onSuccess */ async function authLogin( params: Recordable, onSuccess?: () => Promise | void, ) { // 异步处理用户登录操作并获取 token let userInfo: null | UserInfo = null; try { loginLoading.value = true; const { token } = await loginApi(params); // 如果成功获取到 token if (token) { accessStore.setAccessToken(token); // 获取用户信息并存储到 accessStore 中 const [fetchUserInfoResult, accessCodes] = await Promise.all([ fetchUserInfo(), getAccessCodesApi(), ]); userInfo = fetchUserInfoResult; userStore.setUserInfo(userInfo); accessStore.setAccessCodes(accessCodes); console.log(userInfo.home_path); console.log(DEFAULT_HOME_PATH); console.log(userInfo.home_path || DEFAULT_HOME_PATH, 'ssssssssssssssss'); console.log(userInfo.home_path || DEFAULT_HOME_PATH, 'ssssssssssssssss'); if (accessStore.loginExpired) { accessStore.setLoginExpired(false); } else { onSuccess ? await onSuccess?.() : await router.push(userInfo.home_path || DEFAULT_HOME_PATH); } if (userInfo?.nick_name) { // 这里修改水印内容 await updateWatermark({ contentType: 'multi-line-text', // 水印内容 content: `${userInfo?.nick_name}\r\n${userInfo?.phone}`, }); notification.success({ description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.nick_name}`, duration: 3, message: $t('authentication.loginSuccess'), }); } } } 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, }; });