Blame view

src/store/modules/user.ts 3.69 KB
Vben authored
1
2
import type { UserInfo } from '/#/store';
import type { ErrorMessageMode } from '/@/utils/http/axios/types';
陈文彬 authored
3
Vben authored
4
5
import { defineStore } from 'pinia';
import { store } from '/@/store';
陈文彬 authored
6
7

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

        // save token
        this.setToken(token);
        // get user info
92
        const userInfo = await this.getUserInfoAction();
Vben authored
93
94
95
96
        const sessionTimeout = this.sessionTimeout;
        sessionTimeout && this.setSessionTimeout(false);
        !sessionTimeout && goHome && (await router.replace(PageEnum.BASE_HOME));
Vben authored
97
98
        return userInfo;
      } catch (error) {
99
        return Promise.reject(error);
Vben authored
100
101
      }
    },
102
103
    async getUserInfoAction() {
      const userInfo = await getUserInfo();
Vben authored
104
105
106
107
      const { roles } = userInfo;
      const roleList = roles.map((item) => item.value) as RoleEnum[];
      this.setUserInfo(userInfo);
      this.setRoleList(roleList);
陈文彬 authored
108
      return userInfo;
Vben authored
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
    },
    /**
     * @description: logout
     */
    logout(goLogin = false) {
      goLogin && router.push(PageEnum.BASE_LOGIN);
    },

    /**
     * @description: Confirm before logging out
     */
    confirmLoginOut() {
      const { createConfirm } = useMessage();
      const { t } = useI18n();
      createConfirm({
        iconType: 'warning',
        title: t('sys.app.logoutTip'),
        content: t('sys.app.logoutMessage'),
        onOk: async () => {
          await this.logout(true);
        },
      });
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWidthOut() {
  return useUserStore(store);
陈文彬 authored
138
}