use-user-store.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { defineStore } from "pinia";
  2. import ls from "@/utils/store2";
  3. import { ref } from "vue";
  4. import { userToken } from "../composables/config";
  5. import crypt from "../composables/crypt";
  6. export interface UserInfo {
  7. id?: string;
  8. name: string;
  9. email: string;
  10. phone: string;
  11. approveStatus?: number;
  12. }
  13. export interface AccountInfo {
  14. loginName: string;
  15. password: string;
  16. rememberPassword: boolean;
  17. }
  18. const STORAGE_KEY = "user";
  19. const ACCOUNT_INFO_KEY = "accountInfo";
  20. const useUserStore = defineStore("userStore", () => {
  21. const userInfo = ref<UserInfo | null>(null);
  22. const accountInfo = ref<AccountInfo | null>(null);
  23. const isLoggedIn = ref(false);
  24. const initUserInfo = () => {
  25. const encryptedInfo = ls.get(STORAGE_KEY);
  26. if (encryptedInfo) {
  27. const decryptedInfo = crypt.decrypt(encryptedInfo);
  28. if (decryptedInfo) {
  29. userInfo.value = JSON.parse(decryptedInfo);
  30. isLoggedIn.value = true;
  31. }
  32. }
  33. };
  34. const initAccountInfo = () => {
  35. const encryptedInfo = ls.get(ACCOUNT_INFO_KEY);
  36. if (encryptedInfo) {
  37. const decryptedInfo = crypt.decrypt(encryptedInfo);
  38. if (decryptedInfo) {
  39. accountInfo.value = JSON.parse(decryptedInfo);
  40. }
  41. }
  42. };
  43. const saveUserInfo = (info: UserInfo) => {
  44. userInfo.value = info;
  45. isLoggedIn.value = true;
  46. const encryptedInfo = crypt.encrypt(JSON.stringify(info));
  47. ls.set(STORAGE_KEY, encryptedInfo);
  48. };
  49. const saveAccountInfo = (info: AccountInfo) => {
  50. accountInfo.value = info;
  51. const encryptedInfo = crypt.encrypt(JSON.stringify(info));
  52. ls.set(ACCOUNT_INFO_KEY, encryptedInfo);
  53. };
  54. const clearUserInfo = () => {
  55. userInfo.value = null;
  56. isLoggedIn.value = false;
  57. userToken.value = "";
  58. ls.remove(STORAGE_KEY);
  59. };
  60. initUserInfo();
  61. initAccountInfo();
  62. return {
  63. userInfo,
  64. accountInfo,
  65. isLoggedIn,
  66. saveUserInfo,
  67. saveAccountInfo,
  68. clearUserInfo,
  69. };
  70. });
  71. export default useUserStore;