user.ts 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import { defineStore } from 'pinia';
  2. import { ref } from 'vue';
  3. import { CACHE_KEY } from '@/constants/index';
  4. // @ts-ignore 因为 utils 可能还没做完整的 ts 设置
  5. import { Local, Session } from '@/utils/storage';
  6. import { useLoginApi } from '@/api/system/login';
  7. import { useSystemApi } from '@/api/system/index';
  8. import { useUserApi } from '@/api/user/index';
  9. import type { LoginParams, UserInfo } from '@/types/user';
  10. import { sm3 } from 'sm-crypto';
  11. import to from 'await-to-js';
  12. const loginApi = useLoginApi();
  13. const systemApi = useSystemApi();
  14. const userApi = useUserApi();
  15. export const useUserStore = defineStore('user', () => {
  16. // ==================== State ====================
  17. const token = ref<string>(Local.get(CACHE_KEY.TOKEN) || '');
  18. const userInfo = ref<UserInfo>(Local.get(CACHE_KEY.USER_INFO) || ({} as UserInfo));
  19. const perms = ref<string[]>([]);
  20. const roles = ref<string[]>([]);
  21. const configSetting = ref<any>({});
  22. // 页面请求加载状态
  23. const loadings = {
  24. loginLoading: ref<boolean>(false),
  25. isLogining: ref<boolean>(false),
  26. fetchUserInfoLoading: ref<boolean>(false),
  27. logoutLoading: ref<boolean>(false),
  28. } as const;
  29. // ==================== Actions ====================
  30. /**
  31. * 设置请求加载状态
  32. */
  33. function setRequestLoading(field: keyof typeof loadings, value: boolean) {
  34. loadings[field].value = value;
  35. }
  36. /**
  37. * 检查验证码配置
  38. */
  39. async function checkCaptcha() {
  40. const [err, res] = await to(systemApi.getEntityMapByKeys({ configKeys: ['isCaptcha'] }));
  41. if (err) return;
  42. if (res?.data) {
  43. configSetting.value = res.data;
  44. }
  45. }
  46. /**
  47. * 清理用户状态和本地缓存
  48. */
  49. function clearUserStatus() {
  50. token.value = '';
  51. roles.value = [];
  52. perms.value = [];
  53. userInfo.value = {} as UserInfo;
  54. Local.remove(CACHE_KEY.TOKEN);
  55. Local.remove(CACHE_KEY.USER_INFO);
  56. Local.remove(CACHE_KEY.PERMS);
  57. Local.remove(CACHE_KEY.ROLES);
  58. Session.clear();
  59. }
  60. /**
  61. * 用户登录
  62. */
  63. async function login(loginParams: LoginParams) {
  64. setRequestLoading('loginLoading', true);
  65. // 使用 sm3 加密密码
  66. const encryptedPassword = loginParams.password ? sm3(loginParams.password) : '';
  67. const [err, res] = await to(
  68. loginApi.signIn({
  69. userName: loginParams.userName,
  70. password: encryptedPassword,
  71. idValueC: loginParams.idValueC,
  72. idKeyC: loginParams.idKeyC,
  73. saltValue: loginParams.saltValue,
  74. })
  75. );
  76. setRequestLoading('loginLoading', false);
  77. if (err) {
  78. return Promise.reject(err);
  79. }
  80. const resToken = res?.data?.token;
  81. if (resToken) {
  82. token.value = resToken;
  83. Local.set(CACHE_KEY.TOKEN, resToken);
  84. // 登录成功后主动获取用户信息
  85. await fetchUserInfo();
  86. }
  87. return res;
  88. }
  89. /**
  90. * 钉钉免登
  91. */
  92. async function dingTalkLogin(code: string) {
  93. setRequestLoading('isLogining', true);
  94. const [err, res] = await to(loginApi.dingTalkLogin({ code }));
  95. setRequestLoading('isLogining', false);
  96. if (err) {
  97. return Promise.reject(err);
  98. }
  99. const resToken = res?.data?.token;
  100. if (resToken) {
  101. token.value = resToken;
  102. Local.set(CACHE_KEY.TOKEN, resToken);
  103. // 登录成功后主动获取用户信息
  104. await fetchUserInfo();
  105. }
  106. return res;
  107. }
  108. /**
  109. * 获取用户信息
  110. */
  111. async function fetchUserInfo() {
  112. setRequestLoading('fetchUserInfoLoading', true);
  113. const [err, res] = await to(userApi.getUserByUserName());
  114. setRequestLoading('fetchUserInfoLoading', false);
  115. if (err) {
  116. return Promise.reject(err);
  117. }
  118. // 解决解构变量和 ref 变量重名问题
  119. const {
  120. userInfo: resUserInfo,
  121. perms: resPerms,
  122. roles: resRoles,
  123. } = res?.data || {};
  124. userInfo.value = resUserInfo || ({} as UserInfo);
  125. perms.value = resPerms || [];
  126. roles.value = resRoles || [];
  127. Local.set(CACHE_KEY.USER_INFO, userInfo.value);
  128. Local.set(CACHE_KEY.PERMS, perms.value);
  129. Local.set(CACHE_KEY.ROLES, roles.value);
  130. }
  131. /**
  132. * 用户登出
  133. */
  134. async function logout() {
  135. setRequestLoading('logoutLoading', true);
  136. const [err] = await to(loginApi.signOut());
  137. setRequestLoading('logoutLoading', false);
  138. // 即便接口报错也要清空本地缓存和状态
  139. clearUserStatus();
  140. if (err) {
  141. console.warn('退出登录异常', err);
  142. }
  143. }
  144. return {
  145. ...loadings,
  146. token,
  147. userInfo,
  148. perms,
  149. roles,
  150. configSetting,
  151. login,
  152. dingTalkLogin,
  153. fetchUserInfo,
  154. logout,
  155. clearUserStatus,
  156. setRequestLoading,
  157. checkCaptcha,
  158. };
  159. });