ruoyi-plus-soybean/src/store/modules/auth/index.ts

95 lines
2.4 KiB
TypeScript
Raw Normal View History

2023-12-14 21:45:29 +08:00
import { computed, reactive, ref } from 'vue';
import { defineStore } from 'pinia';
2023-11-17 08:45:00 +08:00
import { useLoading } from '@sa/hooks';
import { SetupStoreId } from '@/enum';
import { useRouterPush } from '@/hooks/common/router';
2023-12-14 21:45:29 +08:00
import { fetchGetUserInfo, fetchLogin } from '@/service/api';
2023-11-17 08:45:00 +08:00
import { localStg } from '@/utils/storage';
import { $t } from '@/locales';
2023-12-14 21:45:29 +08:00
import { useRouteStore } from '../route';
import { clearAuthStorage, getToken, getUserInfo } from './shared';
2023-11-17 08:45:00 +08:00
export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
const routeStore = useRouteStore();
const { route, toLogin, redirectFromLogin } = useRouterPush(false);
const { loading: loginLoading, startLoading, endLoading } = useLoading();
const token = ref(getToken());
const userInfo: Api.Auth.UserInfo = reactive(getUserInfo());
2023-12-14 21:45:29 +08:00
/** Is login */
2023-11-17 08:45:00 +08:00
const isLogin = computed(() => Boolean(token.value));
2023-12-14 21:45:29 +08:00
/** Reset auth store */
2023-11-17 08:45:00 +08:00
async function resetStore() {
const authStore = useAuthStore();
clearAuthStorage();
authStore.$reset();
if (!route.value.meta.constant) {
await toLogin();
}
2023-11-17 08:45:00 +08:00
routeStore.resetStore();
}
2023-11-17 08:45:00 +08:00
/**
2023-12-14 21:45:29 +08:00
* Login
*
* @param userName User name
* @param password Password
2023-11-17 08:45:00 +08:00
*/
async function login(userName: string, password: string) {
startLoading();
2023-11-17 08:45:00 +08:00
try {
const { data: loginToken } = await fetchLogin(userName, password);
await loginByToken(loginToken);
await routeStore.initAuthRoute();
await redirectFromLogin();
if (routeStore.isInitAuthRoute) {
window.$notification?.success({
title: $t('page.login.common.loginSuccess'),
content: $t('page.login.common.welcomeBack', { userName: userInfo.userName }),
duration: 4500
2023-11-17 08:45:00 +08:00
});
}
2023-11-17 08:45:00 +08:00
} catch {
resetStore();
} finally {
endLoading();
}
}
2023-11-17 08:45:00 +08:00
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('refreshToken', loginToken.refreshToken);
const { data: info } = await fetchGetUserInfo();
// 2. store user info
localStg.set('userInfo', info);
// 3. update auth route
token.value = loginToken.token;
Object.assign(userInfo, info);
}
return {
token,
userInfo,
isLogin,
loginLoading,
resetStore,
login
};
});