access.ts 1.7 KB

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