ChatGPT-Next-Web/app/store/access.ts
sijinhui adc55d67d2 Merge remote-tracking branch 'upstream/main' into dev
# Conflicts:
#	.github/workflows/deploy_preview.yml
#	app/client/api.ts
#	app/client/platforms/google.ts
#	app/store/chat.ts
2024-02-08 21:29:22 +08:00

118 lines
2.6 KiB
TypeScript

import {
ApiPath,
DEFAULT_API_HOST,
ServiceProvider,
StoreKey,
} from "../constant";
import { getHeaders } from "../client/api";
import { getClientConfig } from "../config/client";
import { createPersistStore } from "../utils/store";
import { ensure } from "../utils/clone";
let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
const DEFAULT_OPENAI_URL =
getClientConfig()?.buildMode === "export"
? DEFAULT_API_HOST + "/api/proxy/openai"
: ApiPath.OpenAI;
const DEFAULT_ACCESS_STATE = {
accessCode: "",
useCustomConfig: false,
provider: ServiceProvider.OpenAI,
// openai
openaiUrl: DEFAULT_OPENAI_URL,
openaiApiKey: "",
// azure
azureUrl: "",
azureApiKey: "",
azureApiVersion: "2023-05-15",
// google ai studio
googleUrl: "",
googleApiKey: "",
googleApiVersion: "v1",
// server config
needCode: true,
hideUserApiKey: false,
hideBalanceQuery: false,
disableGPT4: false,
midjourneyProxyUrl: "",
useMjImgSelfProxy: false,
disableFastLink: false,
customModels: "",
};
export const useAccessStore = createPersistStore(
{ ...DEFAULT_ACCESS_STATE },
(set, get) => ({
enabledAccessControl() {
this.fetch();
return get().needCode;
},
isValidOpenAI() {
return ensure(get(), ["openaiApiKey"]);
},
isValidAzure() {
return true;
// return ensure(get(), ["azureUrl", "azureApiKey", "azureApiVersion"]);
},
isValidGoogle() {
return ensure(get(), ["googleApiKey"]);
},
isAuthorized() {
this.fetch();
// has token or has code or disabled access control
return (
this.isValidOpenAI() ||
this.isValidAzure() ||
this.isValidGoogle() ||
!this.enabledAccessControl() ||
(this.enabledAccessControl() && ensure(get(), ["accessCode"]))
);
},
fetch() {
if (fetchState > 0 || getClientConfig()?.buildMode === "export") return;
fetchState = 1;
const res = {
needCode: false,
hideUserApiKey: true,
disableGPT4: false,
hideBalanceQuery: true,
};
set(() => ({ ...res }));
fetchState = 2; // 设置 fetchState 值为 "获取已完成"
},
}),
{
name: StoreKey.Access,
version: 2.1,
migrate(persistedState, version) {
if (version < 2.1) {
const state = persistedState as {
token: string;
openaiApiKey: string;
azureApiVersion: string;
googleApiKey: string;
};
state.openaiApiKey = state.token;
state.azureApiVersion = "2023-05-15";
}
return persistedState as any;
},
},
);