access.ts 2.2 KB

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