Blame view

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

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