Blame view

src/store/modules/user.ts 4.14 KB
陈文彬 authored
1
2
3
4
5
6
7
8
9
10
11
12
import type {
  LoginParams,
  GetUserInfoByUserIdModel,
  GetUserInfoByUserIdParams,
} from '/@/api/sys/model/userModel';

import store from '/@/store/index';
import { VuexModule, Module, getModule, Mutation, Action } from 'vuex-module-decorators';
import { hotModuleUnregisterModule } from '/@/utils/helper/vuexHelper';

import { PageEnum } from '/@/enums/pageEnum';
import { RoleEnum } from '/@/enums/roleEnum';
13
import { CacheTypeEnum, ROLES_KEY, TOKEN_KEY, USER_INFO_KEY } from '/@/enums/cacheEnum';
陈文彬 authored
14
15
16

import { useMessage } from '/@/hooks/web/useMessage';
vben authored
17
import router from '/@/router';
陈文彬 authored
18
19
20

import { loginApi, getUserInfoById } from '/@/api/sys/user';
21
22
import { setLocal, getLocal, getSession, setSession } from '/@/utils/helper/persistent';
import { useProjectSetting } from '/@/hooks/setting';
vben authored
23
import { useI18n } from '/@/hooks/web/useI18n';
24
import { ErrorMessageMode } from '/@/utils/http/axios/types';
陈文彬 authored
25
26
27
28
29

export type UserInfo = Omit<GetUserInfoByUserIdModel, 'roles'>;

const NAME = 'user';
hotModuleUnregisterModule(NAME);
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

const { permissionCacheType } = useProjectSetting();

function getCache<T>(key: string) {
  const fn = permissionCacheType === CacheTypeEnum.LOCAL ? getLocal : getSession;
  return fn(key) as T;
}

function setCache(USER_INFO_KEY: string, info: any) {
  if (!info) return;
  // const fn = permissionCacheType === CacheTypeEnum.LOCAL ? setLocal : setSession;
  setLocal(USER_INFO_KEY, info, true);
  // TODO
  setSession(USER_INFO_KEY, info, true);
}
陈文彬 authored
46
47
48
49
50
51
52
53
54
55
56
57
@Module({ namespaced: true, name: NAME, dynamic: true, store })
class User extends VuexModule {
  // user info
  private userInfoState: UserInfo | null = null;

  // token
  private tokenState = '';

  // roleList
  private roleListState: RoleEnum[] = [];

  get getUserInfoState(): UserInfo {
58
    return this.userInfoState || getCache<UserInfo>(USER_INFO_KEY) || {};
陈文彬 authored
59
60
61
  }

  get getTokenState(): string {
62
    return this.tokenState || getCache<string>(TOKEN_KEY);
陈文彬 authored
63
64
65
  }

  get getRoleListState(): RoleEnum[] {
66
    return this.roleListState.length > 0 ? this.roleListState : getCache<RoleEnum[]>(ROLES_KEY);
陈文彬 authored
67
68
69
  }

  @Mutation
vben authored
70
  commitResetState(): void {
陈文彬 authored
71
72
73
74
75
76
77
78
    this.userInfoState = null;
    this.tokenState = '';
    this.roleListState = [];
  }

  @Mutation
  commitUserInfoState(info: UserInfo): void {
    this.userInfoState = info;
79
    setCache(USER_INFO_KEY, info);
陈文彬 authored
80
81
82
83
84
  }

  @Mutation
  commitRoleListState(roleList: RoleEnum[]): void {
    this.roleListState = roleList;
85
    setCache(ROLES_KEY, roleList);
陈文彬 authored
86
87
88
89
90
  }

  @Mutation
  commitTokenState(info: string): void {
    this.tokenState = info;
91
    setCache(TOKEN_KEY, info);
陈文彬 authored
92
93
94
95
96
97
  }

  /**
   * @description: login
   */
  @Action
98
99
100
101
102
103
  async login(
    params: LoginParams & {
      goHome?: boolean;
      mode?: ErrorMessageMode;
    }
  ): Promise<GetUserInfoByUserIdModel | null> {
陈文彬 authored
104
    try {
105
106
107
      const { goHome = true, mode, ...loginParams } = params;
      const data = await loginApi(loginParams, mode);
陈文彬 authored
108
109
110
111
112
      const { token, userId } = data;

      // save token
      this.commitTokenState(token);
113
114
115
      // get user info
      const userInfo = await this.getUserInfoAction({ userId });
陈文彬 authored
116
117
      // const name = FULL_PAGE_NOT_FOUND_ROUTE.name;
      // name && router.removeRoute(name);
118
      goHome && (await router.replace(PageEnum.BASE_HOME));
陈文彬 authored
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
      return userInfo;
    } catch (error) {
      return null;
    }
  }

  @Action
  async getUserInfoAction({ userId }: GetUserInfoByUserIdParams) {
    const userInfo = await getUserInfoById({ userId });
    const { role } = userInfo;
    const roleList = [role.value] as RoleEnum[];
    this.commitUserInfoState(userInfo);
    this.commitRoleListState(roleList);
    return userInfo;
  }

  /**
   * @description: login out
   */
  @Action
  async loginOut(goLogin = false) {
    goLogin && router.push(PageEnum.BASE_LOGIN);
  }

  /**
   * @description: Confirm before logging out
   */
  @Action
  async confirmLoginOut() {
    const { createConfirm } = useMessage();
149
    const { t } = useI18n();
陈文彬 authored
150
151
    createConfirm({
      iconType: 'warning',
152
153
      title: t('sys.app.loginOutTip'),
      content: t('sys.app.loginOutMessage'),
陈文彬 authored
154
155
156
157
158
159
160
      onOk: async () => {
        await this.loginOut(true);
      },
    });
  }
}
export const userStore = getModule<User>(User);