Vben
2021-02-28 15567e478c0f274b0f8f0a7410ea5cb636bacc3d
提交 | 用户 | age
2f6253 1 import type {
2   LoginParams,
3   GetUserInfoByUserIdModel,
4   GetUserInfoByUserIdParams,
5 } from '/@/api/sys/model/userModel';
6
7 import store from '/@/store/index';
8 import { VuexModule, Module, getModule, Mutation, Action } from 'vuex-module-decorators';
9 import { hotModuleUnregisterModule } from '/@/utils/helper/vuexHelper';
10
11 import { PageEnum } from '/@/enums/pageEnum';
12 import { RoleEnum } from '/@/enums/roleEnum';
26b610 13 import { CacheTypeEnum, ROLES_KEY, TOKEN_KEY, USER_INFO_KEY } from '/@/enums/cacheEnum';
2f6253 14
15 import { useMessage } from '/@/hooks/web/useMessage';
16
737b1b 17 import router from '/@/router';
2f6253 18
19 import { loginApi, getUserInfoById } from '/@/api/sys/user';
20
f57eb9 21 import { Persistent, BasicKeys } from '/@/utils/cache/persistent';
190112 22 import { useI18n } from '/@/hooks/web/useI18n';
4ce1d5 23 import { ErrorMessageMode } from '/@/utils/http/axios/types';
f57eb9 24 import projectSetting from '/@/settings/projectSetting';
2f6253 25
26 export type UserInfo = Omit<GetUserInfoByUserIdModel, 'roles'>;
27
15567e 28 const { permissionCacheType } = projectSetting;
V 29 const isLocal = permissionCacheType === CacheTypeEnum.LOCAL;
30
31 const NAME = 'app-user';
2f6253 32 hotModuleUnregisterModule(NAME);
26b610 33
f57eb9 34 function getCache<T>(key: BasicKeys) {
15567e 35   const fn = isLocal ? Persistent.getLocal : Persistent.getSession;
26b610 36   return fn(key) as T;
15567e 37 }
V 38
39 function setCache(key: BasicKeys, value) {
40   const fn = isLocal ? Persistent.setLocal : Persistent.setSession;
41   return fn(key, value);
26b610 42 }
V 43
2f6253 44 @Module({ namespaced: true, name: NAME, dynamic: true, store })
45 class User extends VuexModule {
46   // user info
47   private userInfoState: UserInfo | null = null;
48
49   // token
50   private tokenState = '';
51
52   // roleList
53   private roleListState: RoleEnum[] = [];
54
55   get getUserInfoState(): UserInfo {
26b610 56     return this.userInfoState || getCache<UserInfo>(USER_INFO_KEY) || {};
2f6253 57   }
58
59   get getTokenState(): string {
26b610 60     return this.tokenState || getCache<string>(TOKEN_KEY);
2f6253 61   }
62
63   get getRoleListState(): RoleEnum[] {
26b610 64     return this.roleListState.length > 0 ? this.roleListState : getCache<RoleEnum[]>(ROLES_KEY);
2f6253 65   }
66
67   @Mutation
737b1b 68   commitResetState(): void {
2f6253 69     this.userInfoState = null;
70     this.tokenState = '';
71     this.roleListState = [];
72   }
73
74   @Mutation
75   commitUserInfoState(info: UserInfo): void {
76     this.userInfoState = info;
15567e 77     setCache(USER_INFO_KEY, info);
2f6253 78   }
79
80   @Mutation
81   commitRoleListState(roleList: RoleEnum[]): void {
82     this.roleListState = roleList;
15567e 83     setCache(ROLES_KEY, roleList);
2f6253 84   }
85
86   @Mutation
87   commitTokenState(info: string): void {
88     this.tokenState = info;
15567e 89     setCache(TOKEN_KEY, info);
2f6253 90   }
91
92   /**
93    * @description: login
94    */
95   @Action
4ce1d5 96   async login(
V 97     params: LoginParams & {
98       goHome?: boolean;
99       mode?: ErrorMessageMode;
100     }
101   ): Promise<GetUserInfoByUserIdModel | null> {
2f6253 102     try {
4ce1d5 103       const { goHome = true, mode, ...loginParams } = params;
V 104       const data = await loginApi(loginParams, mode);
105
2f6253 106       const { token, userId } = data;
107
108       // save token
109       this.commitTokenState(token);
110
116a1f 111       // get user info
V 112       const userInfo = await this.getUserInfoAction({ userId });
113
043403 114       goHome && (await router.replace(PageEnum.BASE_HOME));
2f6253 115       return userInfo;
116     } catch (error) {
117       return null;
118     }
119   }
120
121   @Action
122   async getUserInfoAction({ userId }: GetUserInfoByUserIdParams) {
123     const userInfo = await getUserInfoById({ userId });
589409 124     const { roles } = userInfo;
V 125     const roleList = roles.map((item) => item.value) as RoleEnum[];
2f6253 126     this.commitUserInfoState(userInfo);
127     this.commitRoleListState(roleList);
128     return userInfo;
129   }
130
131   /**
da0491 132    * @description: logout
2f6253 133    */
134   @Action
da0491 135   async logout(goLogin = false) {
2f6253 136     goLogin && router.push(PageEnum.BASE_LOGIN);
137   }
138
139   /**
140    * @description: Confirm before logging out
141    */
142   @Action
143   async confirmLoginOut() {
144     const { createConfirm } = useMessage();
962f90 145     const { t } = useI18n();
2f6253 146     createConfirm({
147       iconType: 'warning',
da0491 148       title: t('sys.app.logoutTip'),
V 149       content: t('sys.app.logoutMessage'),
2f6253 150       onOk: async () => {
da0491 151         await this.logout(true);
2f6253 152       },
153     });
154   }
155 }
156 export const userStore = getModule<User>(User);