123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- import { create } from "zustand";
- import { persist } from "zustand/middleware";
- import { StoreKey } from "../constant";
- import { getHeaders } from "../requests";
- import { BOT_HELLO } from "./chat";
- import { ALL_MODELS } from "./config";
- export interface AccessControlStore {
- accessCode: string;
- token: string;
- needCode: boolean;
- hideUserApiKey: boolean;
- openaiUrl: string;
- updateToken: (_: string) => void;
- updateCode: (_: string) => void;
- enabledAccessControl: () => boolean;
- isAuthorized: () => boolean;
- fetch: () => void;
- }
- let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
- export const useAccessStore = create<AccessControlStore>()(
- persist(
- (set, get) => ({
- token: "",
- accessCode: "",
- needCode: true,
- hideUserApiKey: false,
- openaiUrl: "/api/openai/",
- enabledAccessControl() {
- get().fetch();
- return get().needCode;
- },
- updateCode(code: string) {
- set(() => ({ accessCode: code }));
- },
- updateToken(token: string) {
- set(() => ({ token }));
- },
- isAuthorized() {
- get().fetch();
- // has token or has code or disabled access control
- return (
- !!get().token || !!get().accessCode || !get().enabledAccessControl()
- );
- },
- fetch() {
- if (fetchState > 0) return;
- fetchState = 1;
- fetch("/api/config", {
- method: "post",
- body: null,
- headers: {
- ...getHeaders(),
- },
- })
- .then((res) => res.json())
- .then((res: DangerConfig) => {
- console.log("[Config] got config from server", res);
- set(() => ({ ...res }));
- if (!res.enableGPT4) {
- ALL_MODELS.forEach((model) => {
- if (model.name.startsWith("gpt-4")) {
- (model as any).available = false;
- }
- });
- }
- if ((res as any).botHello) {
- BOT_HELLO.content = (res as any).botHello;
- }
- })
- .catch(() => {
- console.error("[Config] failed to fetch config");
- })
- .finally(() => {
- fetchState = 2;
- });
- },
- }),
- {
- name: StoreKey.Access,
- version: 1,
- },
- ),
- );
|