access.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import {
  2. ApiPath,
  3. DEFAULT_API_HOST,
  4. ServiceProvider,
  5. StoreKey,
  6. } from "../constant";
  7. import { getHeaders } from "../client/api";
  8. import { getClientConfig, getFullApi } from "../config/client";
  9. import { createPersistStore } from "../utils/store";
  10. import { ensure } from "../utils/clone";
  11. import dayjs from "dayjs";
  12. let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
  13. const DEFAULT_OPENAI_URL =
  14. getClientConfig()?.buildMode === "export" ? DEFAULT_API_HOST : ApiPath.OpenAI;
  15. const DEFAULT_ACCESS_STATE = {
  16. accessCode: "",
  17. useCustomConfig: false,
  18. provider: ServiceProvider.Oauth,
  19. // openai
  20. openaiUrl: DEFAULT_OPENAI_URL,
  21. openaiApiKey: "",
  22. // oauth2
  23. accessToken: "",
  24. expiresIn: 0,
  25. tokenType: "bearer",
  26. hasLogin: false,
  27. // azure
  28. azureUrl: "",
  29. azureApiKey: "",
  30. azureApiVersion: "2023-08-01-preview",
  31. // server config
  32. needCode: true,
  33. hideUserApiKey: false,
  34. hideBalanceQuery: false,
  35. disableGPT4: false,
  36. disableFastLink: false,
  37. customModels: "",
  38. };
  39. export const useAccessStore = createPersistStore(
  40. { ...DEFAULT_ACCESS_STATE },
  41. (set, get) => ({
  42. enabledAccessControl() {
  43. this.fetch();
  44. return get().needCode;
  45. },
  46. clearToken() {
  47. set(() => ({
  48. accessToken: "",
  49. expiresIn: 0,
  50. tokenType: "bearer",
  51. hasLogin: false,
  52. }));
  53. },
  54. setAccessToken(token: any) {
  55. set(() => ({ ...token }));
  56. },
  57. setLogin(login = true) {
  58. set(() => ({ hasLogin: login }));
  59. },
  60. isLogin() {
  61. return get().hasLogin;
  62. },
  63. hasAccessToken() {
  64. const state = get();
  65. if (state.provider == ServiceProvider.Oauth) {
  66. return !!state.accessToken?.length && dayjs().unix() < state.expiresIn;
  67. }
  68. return false;
  69. },
  70. isValidOpenAI() {
  71. return ensure(get(), ["openaiApiKey"]);
  72. },
  73. isValidAzure() {
  74. return ensure(get(), ["azureUrl", "azureApiKey", "azureApiVersion"]);
  75. },
  76. isAuthorized() {
  77. this.fetch();
  78. // has token or has code or disabled access control
  79. return (
  80. this.isValidOpenAI() ||
  81. this.isValidAzure() ||
  82. !this.enabledAccessControl() ||
  83. (this.enabledAccessControl() && ensure(get(), ["accessCode"]))
  84. );
  85. },
  86. fetch() {
  87. if (fetchState > 0 || getClientConfig()?.buildMode === "export") return;
  88. fetchState = 1;
  89. fetch(getFullApi("/api/config"), {
  90. method: "post",
  91. body: null,
  92. headers: {
  93. ...getHeaders(),
  94. },
  95. })
  96. .then((res) => res.json())
  97. .then((res: DangerConfig) => {
  98. console.log("[Config] got config from server", res);
  99. set(() => ({ ...res }));
  100. })
  101. .catch(() => {
  102. console.error("[Config] failed to fetch config");
  103. })
  104. .finally(() => {
  105. fetchState = 2;
  106. });
  107. },
  108. }),
  109. {
  110. name: StoreKey.Access,
  111. version: 2,
  112. migrate(persistedState, version) {
  113. if (version < 2) {
  114. const state = persistedState as {
  115. token: string;
  116. openaiApiKey: string;
  117. azureApiVersion: string;
  118. };
  119. state.openaiApiKey = state.token;
  120. state.azureApiVersion = "2023-08-01-preview";
  121. }
  122. return persistedState as any;
  123. },
  124. },
  125. );