access.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { create } from "zustand";
  2. import { persist } from "zustand/middleware";
  3. import { StoreKey } from "../constant";
  4. import { BOT_HELLO } from "./chat";
  5. export interface AccessControlStore {
  6. accessCode: string;
  7. token: string;
  8. needCode: boolean;
  9. updateToken: (_: string) => void;
  10. updateCode: (_: string) => void;
  11. enabledAccessControl: () => boolean;
  12. isAuthorized: () => boolean;
  13. fetch: () => void;
  14. }
  15. let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
  16. export const useAccessStore = create<AccessControlStore>()(
  17. persist(
  18. (set, get) => ({
  19. token: "",
  20. accessCode: "",
  21. needCode: true,
  22. enabledAccessControl() {
  23. get().fetch();
  24. return get().needCode;
  25. },
  26. updateCode(code: string) {
  27. set((state) => ({ accessCode: code }));
  28. },
  29. updateToken(token: string) {
  30. set((state) => ({ token }));
  31. },
  32. isAuthorized() {
  33. // has token or has code or disabled access control
  34. return (
  35. !!get().token || !!get().accessCode || !get().enabledAccessControl()
  36. );
  37. },
  38. fetch() {
  39. if (fetchState > 0) return;
  40. fetchState = 1;
  41. fetch("/api/config", {
  42. method: "post",
  43. body: null,
  44. })
  45. .then((res) => res.json())
  46. .then((res: DangerConfig) => {
  47. console.log("[Config] got config from server", res);
  48. set(() => ({ ...res }));
  49. })
  50. .catch(() => {
  51. console.error("[Config] failed to fetch config");
  52. })
  53. .finally(() => {
  54. fetchState = 2;
  55. });
  56. },
  57. }),
  58. {
  59. name: StoreKey.Access,
  60. version: 1,
  61. },
  62. ),
  63. );