feat(auth): 实现全自动无感续杯 (401/即将过期自动重试换票) 与企业多身份唯一标识分层
This commit is contained in:
1 parent
189415cdac
commit
b7a3bf2c03
7 files changed
+122
-17
No files matched your search
+19
-6
@@ -1,17 +1,30 @@
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
import { createClient } from "../http/factory.js";
|
||||
import { createAuthClient } from "../http/factory.js";
|
||||
import { refreshSingleCorpAccessToken } from "./login.js";
|
||||
|
||||
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
||||
return {
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corpid: corp.credentials.corpId,
|
||||
staffid: corp.credentials.staffId,
|
||||
corpid: corp.corpId || corp.credentials.corpId,
|
||||
staffid: corp.staffId || corp.credentials.staffId,
|
||||
};
|
||||
}
|
||||
|
||||
export function createEkbClient(corp: CorpConfig) {
|
||||
return createClient({
|
||||
export async function createEkbClient(corp: CorpConfig) {
|
||||
// 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯
|
||||
if (corp.auth?.expiresAt) {
|
||||
const ttlMs = (corp.auth.refreshTtl || 300) * 1000;
|
||||
if (Date.now() >= corp.auth.expiresAt - ttlMs) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 使用带 401 自动重试与换票的 AuthClient
|
||||
return createAuthClient({
|
||||
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||||
headers: getEkbHeaders(corp),
|
||||
getHeaders: () => getEkbHeaders(corp),
|
||||
onUnauthorized: async () => {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user