Blame view

src/store/modules/user.ts 5.24 KB
Vben authored
1
import type { UserInfo } from '/#/store';
2
import type { ErrorMessageMode } from '/#/axios';
Vben authored
3
4
import { defineStore } from 'pinia';
import { store } from '/@/store';
陈文彬 authored
5
import { RoleEnum } from '/@/enums/roleEnum';
Vben authored
6
import { PageEnum } from '/@/enums/pageEnum';
7
import { ROLES_KEY, TOKEN_KEY, USER_INFO_KEY } from '/@/enums/cacheEnum';
Vben authored
8
import { getAuthCache, setAuthCache } from '/@/utils/auth';
9
import { GetUserInfoModel, LoginParams } from '/@/api/sys/model/userModel';
10
import { doLogout, getUserInfo, loginApi } from '/@/api/sys/user';
vben authored
11
import { useI18n } from '/@/hooks/web/useI18n';
Vben authored
12
import { useMessage } from '/@/hooks/web/useMessage';
Vben authored
13
import { router } from '/@/router';
14
15
import { usePermissionStore } from '/@/store/modules/permission';
import { RouteRecordRaw } from 'vue-router';
16
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
17
import { isArray } from '/@/utils/is';
18
import { h } from 'vue';
陈文彬 authored
19
Vben authored
20
21
22
23
interface UserState {
  userInfo: Nullable<UserInfo>;
  token?: string;
  roleList: RoleEnum[];
24
  sessionTimeout?: boolean;
25
  lastUpdateTime: number;
Vben authored
26
}
27
Vben authored
28
29
30
31
32
33
34
35
36
export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: null,
    // token
    token: undefined,
    // roleList
    roleList: [],
37
38
    // Whether the login expired
    sessionTimeout: false,
39
40
    // Last fetch time
    lastUpdateTime: 0,
Vben authored
41
42
  }),
  getters: {
vben authored
43
    getUserInfo(): UserInfo {
Vben authored
44
45
      return this.userInfo || getAuthCache<UserInfo>(USER_INFO_KEY) || {};
    },
vben authored
46
    getToken(): string {
Vben authored
47
48
      return this.token || getAuthCache<string>(TOKEN_KEY);
    },
vben authored
49
    getRoleList(): RoleEnum[] {
Vben authored
50
51
      return this.roleList.length > 0 ? this.roleList : getAuthCache<RoleEnum[]>(ROLES_KEY);
    },
52
53
54
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout;
    },
55
56
57
    getLastUpdateTime(): number {
      return this.lastUpdateTime;
    },
Vben authored
58
59
  },
  actions: {
60
    setToken(info: string | undefined) {
无木 authored
61
      this.token = info ? info : ''; // for null or undefined value
Vben authored
62
63
64
65
66
67
      setAuthCache(TOKEN_KEY, info);
    },
    setRoleList(roleList: RoleEnum[]) {
      this.roleList = roleList;
      setAuthCache(ROLES_KEY, roleList);
    },
68
    setUserInfo(info: UserInfo | null) {
Vben authored
69
      this.userInfo = info;
70
      this.lastUpdateTime = new Date().getTime();
Vben authored
71
72
      setAuthCache(USER_INFO_KEY, info);
    },
73
74
75
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
Vben authored
76
77
78
79
    resetState() {
      this.userInfo = null;
      this.token = '';
      this.roleList = [];
80
      this.sessionTimeout = false;
Vben authored
81
82
83
84
85
86
87
88
    },
    /**
     * @description: login
     */
    async login(
      params: LoginParams & {
        goHome?: boolean;
        mode?: ErrorMessageMode;
vben authored
89
      },
90
    ): Promise<GetUserInfoModel | null> {
Vben authored
91
92
93
      try {
        const { goHome = true, mode, ...loginParams } = params;
        const data = await loginApi(loginParams, mode);
94
        const { token } = data;
Vben authored
95
96
97

        // save token
        this.setToken(token);
98
        return this.afterLoginAction(goHome);
Vben authored
99
      } catch (error) {
100
        return Promise.reject(error);
Vben authored
101
102
      }
    },
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
    async afterLoginAction(goHome?: boolean): Promise<GetUserInfoModel | null> {
      if (!this.getToken) return null;
      // get user info
      const userInfo = await this.getUserInfoAction();

      const sessionTimeout = this.sessionTimeout;
      if (sessionTimeout) {
        this.setSessionTimeout(false);
      } else {
        const permissionStore = usePermissionStore();
        if (!permissionStore.isDynamicAddedRoute) {
          const routes = await permissionStore.buildRoutesAction();
          routes.forEach((route) => {
            router.addRoute(route as unknown as RouteRecordRaw);
          });
          router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
          permissionStore.setDynamicAddedRoute(true);
        }
121
        goHome && (await router.replace(userInfo?.homePath || PageEnum.BASE_HOME));
122
123
124
      }
      return userInfo;
    },
125
126
    async getUserInfoAction(): Promise<UserInfo | null> {
      if (!this.getToken) return null;
127
      const userInfo = await getUserInfo();
128
129
130
131
132
133
134
135
      const { roles = [] } = userInfo;
      if (isArray(roles)) {
        const roleList = roles.map((item) => item.value) as RoleEnum[];
        this.setRoleList(roleList);
      } else {
        userInfo.roles = [];
        this.setRoleList([]);
      }
Vben authored
136
      this.setUserInfo(userInfo);
陈文彬 authored
137
      return userInfo;
Vben authored
138
139
140
141
    },
    /**
     * @description: logout
     */
142
    async logout(goLogin = false) {
143
      if (this.getToken) {
144
145
146
147
148
        try {
          await doLogout();
        } catch {
          console.log('注销Token失败');
        }
149
150
151
      }
      this.setToken(undefined);
      this.setSessionTimeout(false);
152
      this.setUserInfo(null);
Vben authored
153
154
155
156
157
158
159
160
161
162
163
      goLogin && router.push(PageEnum.BASE_LOGIN);
    },

    /**
     * @description: Confirm before logging out
     */
    confirmLoginOut() {
      const { createConfirm } = useMessage();
      const { t } = useI18n();
      createConfirm({
        iconType: 'warning',
164
165
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('sys.app.logoutMessage')),
Vben authored
166
167
168
169
170
171
172
173
174
        onOk: async () => {
          await this.logout(true);
        },
      });
    },
  },
});

// Need to be used outside the setup
175
export function useUserStoreWithOut() {
Vben authored
176
  return useUserStore(store);
陈文彬 authored
177
}