access.ts 1.9 KB

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