|
|
@@ -10,7 +10,14 @@ const H5_LAST_AUTH_TOKEN_KEY = "H5_LAST_AUTH_TOKEN";
|
|
|
const H5_LAST_AUTH_SESSION_ID_KEY = "H5_LAST_AUTH_SESSION_ID";
|
|
|
const H5_LAST_AUTH_TIME_KEY = "H5_LAST_AUTH_TIME";
|
|
|
const H5_SESSION_REFRESH_COOLDOWN_MS = 5 * 60 * 1000;
|
|
|
-let miniProgramSessionRefreshPromise = null;
|
|
|
+const AUTH_RECOVERY_STATUS = Object.freeze({
|
|
|
+ SUCCESS: "SUCCESS",
|
|
|
+ TEMPORARY_FAILURE: "TEMPORARY_FAILURE",
|
|
|
+ TOKEN_INVALID: "TOKEN_INVALID",
|
|
|
+ USER_MISMATCH: "USER_MISMATCH",
|
|
|
+ NO_AUTH: "NO_AUTH",
|
|
|
+});
|
|
|
+const miniProgramSessionRefreshPromises = new Map();
|
|
|
|
|
|
// 获取URL参数的工具函数
|
|
|
function getUrlParams() {
|
|
|
@@ -361,9 +368,108 @@ function clearMiniProgramSessionAuth() {
|
|
|
document.cookie = "JSESSIONID=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
|
|
|
}
|
|
|
|
|
|
+function createAuthRecoveryError(status, message, cause) {
|
|
|
+ const error = new Error(message || status || "登录状态恢复失败");
|
|
|
+ error.name = "AuthRecoveryError";
|
|
|
+ error.authStatus = status || AUTH_RECOVERY_STATUS.TEMPORARY_FAILURE;
|
|
|
+ if (cause) {
|
|
|
+ error.cause = cause;
|
|
|
+ }
|
|
|
+ return error;
|
|
|
+}
|
|
|
+
|
|
|
+function isExplicitTokenInvalidData(data) {
|
|
|
+ if (!data || typeof data !== "object") {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ const message = String(
|
|
|
+ data.msg || data.message || data.ssMsg || data.error_description || ""
|
|
|
+ ).trim();
|
|
|
+ return (
|
|
|
+ Number(data.errorcode) === 1 ||
|
|
|
+ data.error === "UNAUTHORIZED" ||
|
|
|
+ /(自动登录|登录状态|登录令牌|令牌|mdToken).*(过期|失效|无效|不存在|未找到)/i.test(
|
|
|
+ message
|
|
|
+ )
|
|
|
+ );
|
|
|
+}
|
|
|
+
|
|
|
+function isTemporaryAuthHttpStatus(status) {
|
|
|
+ return status === 408 || status === 429 || status >= 500;
|
|
|
+}
|
|
|
+
|
|
|
+function classifyAuthRecoveryException(error) {
|
|
|
+ if (error?.authStatus) {
|
|
|
+ return error;
|
|
|
+ }
|
|
|
+
|
|
|
+ const response = error?.response;
|
|
|
+ if (!response) {
|
|
|
+ return createAuthRecoveryError(
|
|
|
+ AUTH_RECOVERY_STATUS.TEMPORARY_FAILURE,
|
|
|
+ "网络连接失败,暂时无法恢复登录状态",
|
|
|
+ error
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ if (isExplicitTokenInvalidData(response.data)) {
|
|
|
+ return createAuthRecoveryError(
|
|
|
+ AUTH_RECOVERY_STATUS.TOKEN_INVALID,
|
|
|
+ response.data?.msg || response.data?.message || "登录令牌已失效",
|
|
|
+ error
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ if (response.status === 401 || response.status === 403) {
|
|
|
+ return createAuthRecoveryError(
|
|
|
+ AUTH_RECOVERY_STATUS.TOKEN_INVALID,
|
|
|
+ response.data?.msg || response.data?.message || "登录令牌已失效",
|
|
|
+ error
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ if (isTemporaryAuthHttpStatus(response.status)) {
|
|
|
+ return createAuthRecoveryError(
|
|
|
+ AUTH_RECOVERY_STATUS.TEMPORARY_FAILURE,
|
|
|
+ `服务暂时不可用(HTTP ${response.status})`,
|
|
|
+ error
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ return createAuthRecoveryError(
|
|
|
+ AUTH_RECOVERY_STATUS.TEMPORARY_FAILURE,
|
|
|
+ error?.message || "登录状态恢复失败",
|
|
|
+ error
|
|
|
+ );
|
|
|
+}
|
|
|
+
|
|
|
+function resolveSessionRecoveryAuth() {
|
|
|
+ const { params, token: urlToken, urlUserId } = getMiniProgramUrlAuthState();
|
|
|
+ const storedUserInfo = readStoredUserInfo();
|
|
|
+ const storedUserId = normalizeAuthUserId(
|
|
|
+ storedUserInfo.yhid || storedUserInfo.userId
|
|
|
+ );
|
|
|
+ const token = urlToken || getStoredAuthToken(params);
|
|
|
+ const lastAuthToken = localStorage.getItem(H5_LAST_AUTH_TOKEN_KEY) || "";
|
|
|
+ const canUseStoredUserId =
|
|
|
+ !!token && (!urlToken || !lastAuthToken || lastAuthToken === token);
|
|
|
+
|
|
|
+ return {
|
|
|
+ params,
|
|
|
+ token,
|
|
|
+ urlUserId,
|
|
|
+ storedUserId,
|
|
|
+ userId: urlUserId || (canUseStoredUserId ? storedUserId : ""),
|
|
|
+ };
|
|
|
+}
|
|
|
+
|
|
|
async function doMiniProgramSessionRefresh(token, urlUserId, options = {}) {
|
|
|
if (typeof axios === "undefined") {
|
|
|
- throw new Error("axios未加载,无法刷新H5会话");
|
|
|
+ throw createAuthRecoveryError(
|
|
|
+ AUTH_RECOVERY_STATUS.TEMPORARY_FAILURE,
|
|
|
+ "axios未加载,无法刷新H5会话"
|
|
|
+ );
|
|
|
}
|
|
|
|
|
|
const deviceInfo = getDeviceInfo();
|
|
|
@@ -383,41 +489,57 @@ async function doMiniProgramSessionRefresh(token, urlUserId, options = {}) {
|
|
|
hasToken: !!token,
|
|
|
});
|
|
|
|
|
|
- const response = await axios.post(loginUrl, formData, {
|
|
|
- headers: {
|
|
|
- "Content-Type": "application/x-www-form-urlencoded",
|
|
|
- },
|
|
|
- timeout: 30000,
|
|
|
- withCredentials: true,
|
|
|
- });
|
|
|
+ let response;
|
|
|
+ try {
|
|
|
+ response = await axios.post(loginUrl, formData, {
|
|
|
+ headers: {
|
|
|
+ "Content-Type": "application/x-www-form-urlencoded",
|
|
|
+ },
|
|
|
+ timeout: 30000,
|
|
|
+ withCredentials: true,
|
|
|
+ });
|
|
|
+ } catch (error) {
|
|
|
+ throw classifyAuthRecoveryException(error);
|
|
|
+ }
|
|
|
const loginData = unwrapMiniProgramLoginData(response.data);
|
|
|
|
|
|
if (!loginData || typeof loginData !== "object") {
|
|
|
- throw new Error("自动登录响应数据无效");
|
|
|
+ throw createAuthRecoveryError(
|
|
|
+ AUTH_RECOVERY_STATUS.TEMPORARY_FAILURE,
|
|
|
+ "自动登录响应数据无效"
|
|
|
+ );
|
|
|
}
|
|
|
- if (
|
|
|
- loginData.errorcode === 1 ||
|
|
|
- loginData.error === "UNAUTHORIZED" ||
|
|
|
- String(loginData.msg || loginData.message || "").includes("失败")
|
|
|
- ) {
|
|
|
- throw new Error(loginData.msg || loginData.message || "自动登录失败");
|
|
|
+ if (isExplicitTokenInvalidData(loginData)) {
|
|
|
+ throw createAuthRecoveryError(
|
|
|
+ AUTH_RECOVERY_STATUS.TOKEN_INVALID,
|
|
|
+ loginData.msg || loginData.message || "登录令牌已失效"
|
|
|
+ );
|
|
|
}
|
|
|
|
|
|
const responseUserId = normalizeAuthUserId(
|
|
|
loginData.yhid || loginData.userId || loginData.ryid
|
|
|
);
|
|
|
- if (responseUserId && responseUserId !== urlUserId) {
|
|
|
- throw new Error("自动登录返回账号与当前小程序账号不一致");
|
|
|
+ if (urlUserId && responseUserId && responseUserId !== urlUserId) {
|
|
|
+ throw createAuthRecoveryError(
|
|
|
+ AUTH_RECOVERY_STATUS.USER_MISMATCH,
|
|
|
+ "自动登录返回账号与当前小程序账号不一致"
|
|
|
+ );
|
|
|
}
|
|
|
|
|
|
const sessionId =
|
|
|
loginData.sessId || loginData.JSESSIONID || loginData.jsessionId || "";
|
|
|
+ if (!sessionId) {
|
|
|
+ throw createAuthRecoveryError(
|
|
|
+ AUTH_RECOVERY_STATUS.TEMPORARY_FAILURE,
|
|
|
+ "自动登录未返回有效会话"
|
|
|
+ );
|
|
|
+ }
|
|
|
const storedUserInfo = readStoredUserInfo();
|
|
|
- const confirmedUserId = responseUserId || urlUserId;
|
|
|
+ const confirmedUserId = responseUserId || normalizeAuthUserId(urlUserId);
|
|
|
const userData = {
|
|
|
...storedUserInfo,
|
|
|
- devId: loginData.devId || storedUserInfo.devId,
|
|
|
- sbmc: loginData.sbmc || storedUserInfo.sbmc,
|
|
|
+ devId: loginData.devId || storedUserInfo.devId || deviceInfo.deviceId,
|
|
|
+ sbmc: loginData.sbmc || storedUserInfo.sbmc || deviceInfo.model,
|
|
|
sessId: sessionId || storedUserInfo.sessId,
|
|
|
JSESSIONID: sessionId || storedUserInfo.JSESSIONID,
|
|
|
jsessionId: sessionId || storedUserInfo.jsessionId,
|
|
|
@@ -460,15 +582,18 @@ async function doMiniProgramSessionRefresh(token, urlUserId, options = {}) {
|
|
|
});
|
|
|
|
|
|
return {
|
|
|
+ status: AUTH_RECOVERY_STATUS.SUCCESS,
|
|
|
refreshed: true,
|
|
|
userId: confirmedUserId,
|
|
|
sessionId,
|
|
|
+ userInfo: userData,
|
|
|
};
|
|
|
}
|
|
|
|
|
|
async function ensureMiniProgramSessionFresh(options = {}) {
|
|
|
- const { token, urlUserId } = getMiniProgramUrlAuthState();
|
|
|
+ const { token, urlUserId, userId } = resolveSessionRecoveryAuth();
|
|
|
const forceRefresh = options.force === true;
|
|
|
+ const forceRecovery = options.forceRecovery === true;
|
|
|
const storedUserInfo = readStoredUserInfo();
|
|
|
const storedUserId = normalizeAuthUserId(
|
|
|
storedUserInfo.yhid || storedUserInfo.userId
|
|
|
@@ -481,17 +606,26 @@ async function ensureMiniProgramSessionFresh(options = {}) {
|
|
|
page: options.page || "",
|
|
|
service: options.service || "",
|
|
|
urlUserId,
|
|
|
+ recoveryUserId: userId,
|
|
|
storedUserId,
|
|
|
lastAuthUserId,
|
|
|
hasToken: !!token,
|
|
|
force: forceRefresh,
|
|
|
});
|
|
|
|
|
|
- if (!urlUserId || !token) {
|
|
|
- return { refreshed: false, skipped: true, reason: "NO_URL_AUTH" };
|
|
|
+ if (!token) {
|
|
|
+ throw createAuthRecoveryError(
|
|
|
+ AUTH_RECOVERY_STATUS.NO_AUTH,
|
|
|
+ "未找到可用登录令牌"
|
|
|
+ );
|
|
|
}
|
|
|
|
|
|
- if (forceRefresh && hasFreshMiniProgramSession(token, urlUserId)) {
|
|
|
+ if (
|
|
|
+ forceRefresh &&
|
|
|
+ !options.bypassCooldown &&
|
|
|
+ urlUserId &&
|
|
|
+ hasFreshMiniProgramSession(token, urlUserId)
|
|
|
+ ) {
|
|
|
console.log("H5_SESSION_REFRESH_SKIP_RECENT", {
|
|
|
page: options.page || "",
|
|
|
service: options.service || "",
|
|
|
@@ -500,7 +634,7 @@ async function ensureMiniProgramSessionFresh(options = {}) {
|
|
|
return { refreshed: false, skipped: true, reason: "RECENT_SESSION" };
|
|
|
}
|
|
|
|
|
|
- if (!forceRefresh && !shouldRefreshSessionForUrlUser()) {
|
|
|
+ if (!forceRefresh && !forceRecovery && !shouldRefreshSessionForUrlUser()) {
|
|
|
console.log("H5_SESSION_REFRESH_SKIP_SAME_USER", {
|
|
|
page: options.page || "",
|
|
|
service: options.service || "",
|
|
|
@@ -516,30 +650,36 @@ async function ensureMiniProgramSessionFresh(options = {}) {
|
|
|
});
|
|
|
}
|
|
|
|
|
|
- if (miniProgramSessionRefreshPromise) {
|
|
|
- return miniProgramSessionRefreshPromise;
|
|
|
+ const recoveryKey = `${userId || "unknown"}:${token}`;
|
|
|
+ if (miniProgramSessionRefreshPromises.has(recoveryKey)) {
|
|
|
+ return miniProgramSessionRefreshPromises.get(recoveryKey);
|
|
|
}
|
|
|
|
|
|
- miniProgramSessionRefreshPromise = doMiniProgramSessionRefresh(
|
|
|
+ const recoveryPromise = doMiniProgramSessionRefresh(
|
|
|
token,
|
|
|
- urlUserId,
|
|
|
+ urlUserId || userId,
|
|
|
options
|
|
|
)
|
|
|
.catch((error) => {
|
|
|
+ const classifiedError = classifyAuthRecoveryException(error);
|
|
|
console.error("H5_SESSION_REFRESH_FAIL", {
|
|
|
page: options.page || "",
|
|
|
service: options.service || "",
|
|
|
urlUserId,
|
|
|
- message: error?.message || String(error),
|
|
|
+ status: classifiedError.authStatus,
|
|
|
+ message: classifiedError.message || String(classifiedError),
|
|
|
});
|
|
|
- clearMiniProgramSessionAuth();
|
|
|
- throw error;
|
|
|
+ if (classifiedError.authStatus === AUTH_RECOVERY_STATUS.TOKEN_INVALID) {
|
|
|
+ clearMiniProgramSessionAuth();
|
|
|
+ }
|
|
|
+ throw classifiedError;
|
|
|
})
|
|
|
.finally(() => {
|
|
|
- miniProgramSessionRefreshPromise = null;
|
|
|
+ miniProgramSessionRefreshPromises.delete(recoveryKey);
|
|
|
});
|
|
|
|
|
|
- return miniProgramSessionRefreshPromise;
|
|
|
+ miniProgramSessionRefreshPromises.set(recoveryKey, recoveryPromise);
|
|
|
+ return recoveryPromise;
|
|
|
}
|
|
|
|
|
|
// 模拟微信授权码获取 (H5环境下的处理)
|
|
|
@@ -696,6 +836,7 @@ function formatDate(dateStr, format = "YYYY-MM-DD HH:mm:ss") {
|
|
|
|
|
|
window.ENTRY_SOURCE_KEY = ENTRY_SOURCE_KEY;
|
|
|
window.ENTRY_SOURCE_MY = ENTRY_SOURCE_MY;
|
|
|
+window.AUTH_RECOVERY_STATUS = AUTH_RECOVERY_STATUS;
|
|
|
window.getUrlParams = getUrlParams;
|
|
|
|
|
|
window.isAuthPage = isAuthPage;
|