Files
moc/src/store/modules/auth/index.ts
T
2026-08-31 17:16:37 +08:00

193 lines
4.7 KiB
TypeScript

import { computed, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { defineStore } from 'pinia';
import { useLoading } from '@sa/hooks';
import { fetchGetUserInfo, fetchLogin } from '@/service/api';
import { setAiUser } from '@/service/api/ai';
import { useRouterPush } from '@/hooks/common/router';
import { localStg } from '@/utils/storage';
import { SetupStoreId } from '@/enum';
import { useRouteStore } from '../route';
import { useTabStore } from '../tab';
import { clearAuthStorage, getToken } from './shared';
export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
const route = useRoute();
const authStore = useAuthStore();
const routeStore = useRouteStore();
const tabStore = useTabStore();
const { toLogin, redirectFromLogin } = useRouterPush(false);
const { loading: loginLoading, startLoading, endLoading } = useLoading();
const token = ref('');
const userInfo: Api.Auth.UserInfo = reactive({
userId: '',
username: '',
roles: [],
buttons: []
});
/** is super role in static route */
const isStaticSuper = computed(() => {
const { VITE_AUTH_ROUTE_MODE, VITE_STATIC_SUPER_ROLE } = import.meta.env;
return VITE_AUTH_ROUTE_MODE === 'static' && userInfo.roles.includes(VITE_STATIC_SUPER_ROLE);
});
/** Is login */
const isLogin = computed(() => Boolean(token.value));
/** Reset auth store */
async function resetStore() {
recordUserId();
clearAuthStorage();
authStore.$reset();
if (!route.meta.constant) {
await toLogin();
}
tabStore.cacheTabs();
routeStore.resetStore();
}
/** Record the user ID of the previous login session Used to compare with the current user ID on next login */
function recordUserId() {
if (!userInfo.userId) {
return;
}
// Store current user ID locally for next login comparison
localStg.set('lastLoginUserId', userInfo.userId);
}
/**
* Check if current login user is different from previous login user If different, clear all tabs
*
* @returns {boolean} Whether to clear all tabs
*/
function checkTabClear(): boolean {
if (!userInfo.userId) {
return false;
}
const lastLoginUserId = localStg.get('lastLoginUserId');
// Clear all tabs if current user is different from previous user
if (!lastLoginUserId || lastLoginUserId !== userInfo.userId) {
localStg.remove('globalTabs');
tabStore.clearTabs();
localStg.remove('lastLoginUserId');
return true;
}
localStg.remove('lastLoginUserId');
return false;
}
/**
* Login
*
* @param userName User name
* @param password Password
* @param [redirect=true] Whether to redirect after login. Default is `true`
*/
async function login(userName: string, password: string, redirect = true) {
startLoading();
const { data: loginToken, error } = await fetchLogin(userName, password);
if (!error) {
const pass = await loginByToken(loginToken);
if (pass) {
// Check if the tab needs to be cleared
const isClear = checkTabClear();
let needRedirect = redirect;
if (isClear) {
// If the tab needs to be cleared,it means we don't need to redirect.
needRedirect = false;
}
await redirectFromLogin(needRedirect);
window.$notification?.success({
title: '登录成功',
content: `欢迎回来,${userInfo.username} !`,
duration: 4500
});
}
} else {
resetStore();
}
endLoading();
}
async function loginByToken(loginToken: Api.Auth.LoginToken) {
// 1. stored in the localStorage, the later requests need it in headers
localStg.set('token', loginToken.token);
localStg.set('aiToken', loginToken.ai_token);
// 2. get user info
const pass = await getUserInfo();
if (pass) {
token.value = loginToken.token;
return true;
}
return false;
}
async function getUserInfo() {
const { data: info, error } = await fetchGetUserInfo();
if (!error) {
localStg.set('userInfo', info);
// update store
Object.assign(userInfo, info);
// 同步 AI 插件用户身份(exchange 换 ai_token 用)
setAiUser({
platform_user_id: String(info.userId),
align_key: info.username,
display_name: info.username
});
return true;
}
return false;
}
async function initUserInfo() {
const maybeToken = getToken();
if (maybeToken) {
token.value = maybeToken;
const pass = await getUserInfo();
if (!pass) {
resetStore();
}
}
}
return {
token,
userInfo,
isStaticSuper,
isLogin,
loginLoading,
resetStore,
login,
initUserInfo
};
});