Files
kiss-translator/src/libs/auth.js

72 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-08-31 00:18:57 +08:00
import { getMsauth, setMsauth } from "./storage";
2024-03-19 18:07:18 +08:00
import { kissLog } from "./log";
2025-09-27 21:21:56 +08:00
import { apiMsAuth } from "../apis";
2023-07-20 13:45:41 +08:00
2023-08-05 15:32:51 +08:00
const parseMSToken = (token) => {
try {
return JSON.parse(atob(token.split(".")[1])).exp;
} catch (err) {
kissLog("parseMSToken", err);
2023-08-05 15:32:51 +08:00
}
return 0;
};
2023-07-20 13:45:41 +08:00
/**
* 闭包缓存token减少对storage查询
* @returns
*/
const _msAuth = () => {
2025-09-27 21:21:56 +08:00
let tokenPromise = null;
const EXPIRATION_MS = 1000;
2023-07-20 13:45:41 +08:00
2025-09-27 21:21:56 +08:00
const fetchNewToken = async () => {
try {
const now = Date.now();
// 1. 查询storage缓存
const storageToken = await getMsauth();
if (storageToken) {
const storageExp = parseMSToken(storageToken);
const storageExpiresAt = storageExp * 1000;
if (storageExpiresAt > now + EXPIRATION_MS) {
return { token: storageToken, expiresAt: storageExpiresAt };
}
}
// 2. 缓存没有或失效,查询接口
const apiToken = await apiMsAuth();
if (!apiToken) {
throw new Error("Failed to fetch ms token");
}
const apiExp = parseMSToken(apiToken);
const apiExpiresAt = apiExp * 1000;
await setMsauth(apiToken);
return { token: apiToken, expiresAt: apiExpiresAt };
} catch (error) {
kissLog("get msauth failed", error);
throw error;
2023-07-20 13:45:41 +08:00
}
2025-09-27 21:21:56 +08:00
};
2023-07-20 13:45:41 +08:00
2025-09-27 21:21:56 +08:00
return async () => {
// 检查是否有缓存的 Promise
if (tokenPromise) {
try {
const cachedResult = await tokenPromise;
if (cachedResult.expiresAt > Date.now() + EXPIRATION_MS) {
return cachedResult.token;
}
} catch (error) {
//
}
2023-07-20 13:45:41 +08:00
}
2025-09-27 21:21:56 +08:00
tokenPromise = fetchNewToken();
const result = await tokenPromise;
return result.token;
2023-07-20 13:45:41 +08:00
};
};
export const msAuth = _msAuth();