user.ts 4.1 KB

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