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

97 lines
2.4 KiB
TypeScript
Raw Normal View History

2023-11-17 08:45:00 +08:00
import { ref, reactive, computed } 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';
import { fetchLogin, fetchGetUserInfo } from '@/service/api';
import { localStg } from '@/utils/storage';
import { useRouteStore } from '../route';
2023-11-17 08:45:00 +08:00
import { getToken, getUserInfo, clearAuthStorage } from './shared';
import { $t } from '@/locales';
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());
/**
* is login
*/
const isLogin = computed(() => Boolean(token.value));
/**
* reset auth store
*/
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
/**
* login
* @param userName user name
* @param password password
*/
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 })
});
}
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
};
});