2
0
Files
fe.wfc.user/src/store/modules/auth/index.ts
2025-01-17 16:20:10 +08:00

192 lines
4.8 KiB
TypeScript

import { computed, reactive, ref } from 'vue';
import { defineStore } from 'pinia';
import { useLoading } from '@sa/hooks';
import { SetupStoreId } from '@/enum';
import { useRouterPush } from '@/hooks/common/router';
import { localStg } from '@/utils/storage';
import { $t } from '@/locales';
import { useRouteStore } from '../route';
import { clearAuthStorage, emptyInfo, getToken } from './shared';
import { doCheckUserRepeat, sendCaptcha, fetchDashboardData } from '@/service/api/auth';
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(emptyInfo);
const permissions = computed(() => userInfo.permissions);
/** Dashboard data */
const dashboardData = ref<Api.Dashboard.GaugeData | null>(null);
watch(
() => token.value,
async value => {
if (value && !userInfo.user && !route.value.path.includes('login')) {
refreshUserInfo();
}
},
{
immediate: true
}
);
/** Is login */
const isLogin = computed(() => Boolean(token.value));
/**
* Reset auth store
*
* @param isMe [isMe=false] Whether to reset the store by yourself. Default is `false`
*/
async function resetStore(isMe = false) {
if (isMe) {
doDeleteLogout();
}
const authStore = useAuthStore();
authStore.$reset();
clearAuthStorage();
if (!route.value.meta.constant) {
await toLogin();
}
routeStore.resetStore();
}
/**
* Login
*
* @param username User name
* @param password Password
* @param [redirect=true] Whether to redirect after login. Default is `true`
*/
async function login(
params: { loginForm: Api.Auth.LoginBody; onError?: () => void; onSuccess?: () => void },
redirect = true
) {
const { loginForm, onError, onSuccess } = params;
startLoading();
const { data: loginToken, error } = await fetchLogin(loginForm);
console.log(loginToken) //lai
if (!error) {
const pass = await loginByToken(loginToken);
onSuccess && onSuccess();
if (pass) {
await routeStore.initAuthRoute();
if (redirect) {
await redirectFromLogin();
}
if (routeStore.isInitAuthRoute) {
$notification?.success({
message: $t('page.login.common.loginSuccess'),
description: $t('page.login.common.welcomeBack', { username: userInfo?.user?.nickName })
});
}
}
} else {
onError && onError();
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.access_token);
localStg.set('refreshToken', loginToken.refreshToken);
token.value = loginToken.access_token;
const isSuccess = await refreshUserInfo();
return isSuccess;
}
//查询用户信息
async function refreshUserInfo() {
const { data: info, error } = await doGetUserInfo();
if (!error) {
Object.assign(userInfo, info);
return true;
}
return false;
}
/**修改用户信息**/
async function updateUserProfile(info: Api.Auth.ChangeInfoBody) {
try {
await doChangeUserInfo(info);
return true;
} catch (error) {
console.error('Failed to update user profile:', error);
return false;
}
}
/**
* 检查用户信息是否已存在
*/
async function checkUserRepeat(checkForm: Api.Auth.CheckBody) {
const { data, error } = await doCheckUserRepeat(checkForm);
return { exists: data, error };
}
/**
* Register new user
*/
async function register(registerForm: Api.Auth.RegisterBody) {
startLoading();
const { error } = await fetchRegister(registerForm);
if (!error) {
$message?.success($t('page.login.common.registerSuccess'));
// 注册成功后跳转到登录页
await toLogin();
}
endLoading();
return !error;
}
//二维码
async function captcha(email: string) {
if (!email) {
return null;
}
const { data, error } = await sendCaptcha({ email }); // 这里调用后端接口发送验证码
return { data, error };
}
/** Fetch dashboard data */
async function getDashboardData() {
const { data, error } = await fetchDashboardData();
if (!error) {
dashboardData.value = data;
return data;
}
return null;
}
return {
token,
userInfo,
isLogin,
loginLoading,
resetStore,
permissions,
login,
refreshUserInfo,
register,
captcha,
checkUserRepeat,
updateUserProfile,
dashboardData,
getDashboardData
};
});