user.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 oAuthLogin(code: string) {
  112. setRequestLoading('isLogining', true);
  113. const [err, res] = await to(loginApi.oAuthLogin({ code }));
  114. setRequestLoading('isLogining', false);
  115. if (err) {
  116. return Promise.reject(err);
  117. }
  118. const resToken = res?.data?.token;
  119. if (resToken) {
  120. token.value = resToken;
  121. Local.set(CACHE_KEY.TOKEN, resToken);
  122. // 登录成功后主动获取用户信息
  123. await fetchUserInfo();
  124. }
  125. return res;
  126. }
  127. /**
  128. * 获取用户信息
  129. */
  130. async function fetchUserInfo() {
  131. setRequestLoading('fetchUserInfoLoading', true);
  132. const [err, res] = await to(userApi.getUserByUserName());
  133. setRequestLoading('fetchUserInfoLoading', false);
  134. if (err) {
  135. return Promise.reject(err);
  136. }
  137. // 解决解构变量和 ref 变量重名问题
  138. const {
  139. userInfo: resUserInfo,
  140. perms: resPerms,
  141. roles: resRoles,
  142. } = res?.data || {};
  143. userInfo.value = resUserInfo || ({} as UserInfo);
  144. perms.value = resPerms || [];
  145. roles.value = resRoles || [];
  146. Local.set(CACHE_KEY.USER_INFO, userInfo.value);
  147. Local.set(CACHE_KEY.PERMS, perms.value);
  148. Local.set(CACHE_KEY.ROLES, roles.value);
  149. }
  150. /**
  151. * 用户登出
  152. */
  153. async function logout() {
  154. setRequestLoading('logoutLoading', true);
  155. const [err] = await to(loginApi.signOut());
  156. setRequestLoading('logoutLoading', false);
  157. // 即便接口报错也要清空本地缓存和状态
  158. clearUserStatus();
  159. if (err) {
  160. console.warn('退出登录异常', err);
  161. }
  162. }
  163. return {
  164. ...loadings,
  165. token,
  166. userInfo,
  167. perms,
  168. roles,
  169. configSetting,
  170. login,
  171. dingTalkLogin,
  172. oAuthLogin,
  173. fetchUserInfo,
  174. logout,
  175. clearUserStatus,
  176. setRequestLoading,
  177. checkCaptcha,
  178. };
  179. });