lock.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import type { LockInfo } from '#/store';
  2. import { defineStore } from 'pinia';
  3. import { LOCK_INFO_KEY } from '@/enums/cacheEnum';
  4. import { Persistent } from '@/utils/cache/persistent';
  5. import { useUserStore } from './user';
  6. interface LockState {
  7. lockInfo: Nullable<LockInfo>;
  8. }
  9. export const useLockStore = defineStore({
  10. id: 'app-lock',
  11. state: (): LockState => ({
  12. lockInfo: Persistent.getLocal(LOCK_INFO_KEY),
  13. }),
  14. getters: {
  15. getLockInfo(state): Nullable<LockInfo> {
  16. return state.lockInfo;
  17. },
  18. },
  19. actions: {
  20. setLockInfo(info: LockInfo) {
  21. this.lockInfo = Object.assign({}, this.lockInfo, info);
  22. Persistent.setLocal(LOCK_INFO_KEY, this.lockInfo, true);
  23. },
  24. resetLockInfo() {
  25. Persistent.removeLocal(LOCK_INFO_KEY, true);
  26. this.lockInfo = null;
  27. },
  28. // Unlock
  29. async unLock(password?: string) {
  30. const userStore = useUserStore();
  31. if (this.lockInfo?.pwd === password) {
  32. this.resetLockInfo();
  33. return true;
  34. }
  35. const tryLogin = async () => {
  36. try {
  37. const username = userStore.getUserInfo?.username;
  38. const res = await userStore.login({
  39. username,
  40. password: password!,
  41. goHome: false,
  42. mode: 'none',
  43. });
  44. if (res) {
  45. this.resetLockInfo();
  46. }
  47. return res;
  48. } catch (error) {
  49. return false;
  50. }
  51. };
  52. return await tryLogin();
  53. },
  54. },
  55. });