zhengyiming
2025-02-18 251c70f836e4f922904b9131c52f15d5ac58c9fd
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import { defineStore } from 'pinia';
import { store } from '@/store';
import { getToken, setToken, removeToken, removeUserInfo, setUserInfo, getUserInfo } from '@/utils';
import { resetRouter, router } from '@/router';
import { useTagsViewStoreHook } from './tagsView';
import * as accountServices from '@/services/api/Account';
import { usePermissionStoreHook } from './permission';
import { getAccountInfoFromAccessToken, AccountInfo } from '@bole-core/core';
import { useClearSubModule } from '@/hooks';
import { myClient } from '@/constants/query';
 
export interface UserState {
  token: string;
  userInfo: API.IdentityModelTokenCacheItem;
  accountInfo: Partial<AccountInfo>;
  name: string;
}
 
function getDefaultState() {
  const accessToken = getToken();
  const userInfo = getUserInfo();
  const accountInfo = getAccountInfoFromAccessToken(accessToken);
 
  return {
    token: accessToken,
    name: accountInfo.name,
    accountInfo: accountInfo || {},
    userInfo: userInfo || {},
  } as UserState;
}
 
export const useUserStore = defineStore({
  id: 'user',
  state: getDefaultState,
  getters: {
    accessToken(state) {
      return state.token;
    },
    user(state) {
      return state.userInfo;
    },
 
    userId(state) {
      return state.accountInfo.sub;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
      setToken(token);
    },
    setName(name: string) {
      this.name = name;
    },
    setUserInfo(userInfo: API.IdentityModelTokenCacheItem) {
      this.userInfo = userInfo;
      setUserInfo(userInfo);
    },
    setAccountInfo(accountInfo: Partial<AccountInfo>) {
      this.accountInfo = accountInfo;
    },
 
    // 用户登入
    loginByUsername(data: API.AccessRequestDto) {
      return new Promise<void>((resolve, reject) => {
        accountServices
          .getTokenForWeb(data, { showLoading: false })
          // .passwordLogin(
          //   {
          //     loginName: data.userName,
          //     password: data.userPassword,
          //   },
          //   { showLoading: false }
          // )
          .then((res) => {
            if (res) {
              console.log('res: ', res);
              this.setToken(res.accessToken);
 
              const accountInfo = getAccountInfoFromAccessToken(res.accessToken);
 
              this.setName(accountInfo.name);
              this.setAccountInfo(accountInfo);
 
              // 获取用户信息
              this.setUserInfo(res);
 
              resolve();
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
 
    // 登出 清空缓存
    logout(redirectPath = '/') {
      return new Promise(async (resolve) => {
        removeToken();
        removeUserInfo();
        this.resetState();
        resetRouter();
        myClient.removeQueries();
 
        await router.push(`/login?redirect=${redirectPath}`);
 
        const tagsViewStore = useTagsViewStoreHook();
        tagsViewStore.delAllViews();
        const { clearSubModule } = useClearSubModule();
        clearSubModule();
 
        const permissionStore = usePermissionStoreHook();
        permissionStore.resetModuleList();
        resolve(1);
      });
    },
 
    resetToken() {
      this.token = '';
      removeToken();
      this.resetState();
    },
 
    resetState() {
      Object.assign(this, getDefaultState());
    },
 
    refreshToken(params: API.AccessRefreshToken) {
      return new Promise<API.IdentityModelTokenCacheItem>(
        // eslint-disable-next-line no-async-promise-executor
        async (resolve, reject) => {
          try {
            const res = await accountServices.getTokenByRefreshToken(params, {
              showLoading: false,
            });
            if (res) {
              this.setToken(res.accessToken);
              this.setUserInfo(res);
              resolve(res);
              return;
            }
            reject('出错了');
          } catch (error) {
            reject(error);
          }
        }
      );
    },
  },
});
 
export function useUserStoreHook() {
  return useUserStore(store);
}