Blame view

Yi.Vben5.Vue3/playground/src/store/auth.ts 2.99 KB
515fceeb   “wangming”   框架初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
  import type { Recordable, UserInfo } from '@vben/types';
  
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  
  import { LOGIN_PATH } from '@vben/constants';
  import { preferences } from '@vben/preferences';
  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';
  
  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<any>,
      onSuccess?: () => Promise<void> | void,
    ) {
      // 异步处理用户登录操作并获取 accessToken
      let userInfo: null | UserInfo = null;
      try {
        loginLoading.value = true;
        const { accessToken } = await loginApi(params);
  
        // 如果成功获取到 accessToken
        if (accessToken) {
          accessStore.setAccessToken(accessToken);
  
          // 获取用户信息并存储到 accessStore 中
          const [fetchUserInfoResult, accessCodes] = await Promise.all([
            fetchUserInfo(),
            getAccessCodesApi(),
          ]);
  
          userInfo = fetchUserInfoResult;
  
          userStore.setUserInfo(userInfo);
          accessStore.setAccessCodes(accessCodes);
  
          if (accessStore.loginExpired) {
            accessStore.setLoginExpired(false);
          } else {
            onSuccess
              ? await onSuccess?.()
              : await router.push(
                  userInfo.homePath || preferences.app.defaultHomePath,
                );
          }
  
          if (userInfo?.realName) {
            notification.success({
              description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
              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,
    };
  });