access.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. get().fetch();
  38. // has token or has code or disabled access control
  39. return (
  40. !!get().token || !!get().accessCode || !get().enabledAccessControl()
  41. );
  42. },
  43. fetch() {
  44. if (fetchState > 0) return;
  45. fetchState = 1;
  46. fetch("/api/config", {
  47. method: "post",
  48. body: null,
  49. })
  50. .then((res) => res.json())
  51. .then((res: DangerConfig) => {
  52. console.log("[Config] got config from server", res);
  53. set(() => ({ ...res }));
  54. if ((res as any).botHello) {
  55. BOT_HELLO.content = (res as any).botHello;
  56. }
  57. })
  58. .catch(() => {
  59. console.error("[Config] failed to fetch config");
  60. })
  61. .finally(() => {
  62. fetchState = 2;
  63. });
  64. },
  65. }),
  66. {
  67. name: StoreKey.Access,
  68. version: 1,
  69. },
  70. ),
  71. );