You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
81 lines
2.5 KiB
81 lines
2.5 KiB
const superagent = require("superagent");
|
|
|
|
// Global cache for FastGPT Token
|
|
let cachedFastgptToken = null;
|
|
|
|
async function checkTokenValid(conf, token) {
|
|
if (!token) return false;
|
|
try {
|
|
const res = await superagent
|
|
.get(`${conf.fastGpt.apiUrl}/api/core/plugin/admin/tool/list`)
|
|
.set({
|
|
token,
|
|
});
|
|
return res?.status === 200;
|
|
} catch (error) {
|
|
const status = Number(error?.status || error?.response?.status || 0);
|
|
const code = Number(error?.response?.body?.code || 0);
|
|
// FastGPT token 失效时:HTTP 500 + body.code=403
|
|
if (status === 500 && code === 403) return false;
|
|
// 其他异常也按无效处理,触发刷新,确保返回可用 token
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get FastGPT Token with caching
|
|
* @param {Object} conf - Configuration object containing FastGPT credentials and API URL
|
|
* @param {Boolean} forceRefresh - Whether to force refresh the token (default: false)
|
|
* @param {Number} status - Interface status code (default: 200)
|
|
* @returns {Promise<String>} - FastGPT Token
|
|
*/
|
|
async function getFastGptToken(conf, forceRefresh = false, status = 200) {
|
|
// 缓存存在时,先探活,只有有效才返回缓存
|
|
if (cachedFastgptToken && !forceRefresh && status != 403) {
|
|
const valid = await checkTokenValid(conf, cachedFastgptToken);
|
|
if (valid) return cachedFastgptToken;
|
|
}
|
|
|
|
try {
|
|
let loginParams = {
|
|
username: conf.fastGpt.username,
|
|
password: conf.fastGpt.password,
|
|
code: "",
|
|
};
|
|
|
|
const preLoginRes = await superagent
|
|
.get(`${conf.fastGpt.apiUrl}/api/support/user/account/preLogin`)
|
|
.query({
|
|
username: conf.fastGpt.username,
|
|
});
|
|
|
|
if (
|
|
preLoginRes.body &&
|
|
preLoginRes.body.data &&
|
|
preLoginRes.body.code === 200
|
|
) {
|
|
loginParams.code = preLoginRes.body.data.code;
|
|
}
|
|
|
|
const res = await superagent
|
|
.post(
|
|
`${conf.fastGpt.apiUrl}/api/support/user/account/loginByPassword`
|
|
)
|
|
.send(loginParams);
|
|
|
|
if (res.body && res.body.data && res.body.data.token) {
|
|
cachedFastgptToken = res.body.data.token;
|
|
console.log("FastGPT token refreshed successfully", Date.now());
|
|
return cachedFastgptToken;
|
|
}
|
|
|
|
throw new Error("Failed to get FastGPT token");
|
|
} catch (error) {
|
|
console.error("Error getting FastGPT token:", error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
getFastGptToken,
|
|
};
|
|
|