339 lines
11 KiB
TypeScript
339 lines
11 KiB
TypeScript
/**
|
|
* shared/utils/auth.ts
|
|
* 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步等认证相关本地存储能力。
|
|
* 依赖:浏览器 localStorage/sessionStorage、Casdoor refresh 接口。
|
|
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理,既支持 30 天免登录,也支持按业务确认方案回填账号密码。
|
|
*/
|
|
export interface AuthUser {
|
|
id?: number;
|
|
username?: string;
|
|
real_name?: string;
|
|
employee_id?: string;
|
|
role?: string;
|
|
feature_permissions?: {
|
|
training_hr_manage?: boolean;
|
|
[key: string]: boolean | undefined;
|
|
};
|
|
token?: string;
|
|
access_token?: string;
|
|
refresh_token?: string;
|
|
expires_in?: number;
|
|
token_expires_at?: number;
|
|
}
|
|
|
|
interface StoredAuthPayload {
|
|
user?: AuthUser;
|
|
expiry?: number;
|
|
}
|
|
|
|
export interface RememberedLoginProfile {
|
|
username: string;
|
|
password: string;
|
|
updated_at: number;
|
|
}
|
|
|
|
interface StoredRememberedLoginProfile {
|
|
username?: string;
|
|
password_ciphertext?: string;
|
|
updated_at?: number;
|
|
}
|
|
|
|
const AUTH_USER_KEY = 'hxops_user';
|
|
const LOGIN_REMEMBER_KEY = 'hxops_login_remember';
|
|
const LOGIN_PROFILE_KEY = 'hxops_login_profile';
|
|
|
|
/**
|
|
* 对登录页 remember password 做轻量编码,避免在本地存储中直接裸露原始密码文本。
|
|
* AI 触发时机:当业务明确要求自动回填密码时使用;这里只做本地编码,不改变“浏览器端可恢复”的事实。
|
|
*/
|
|
const encodeRememberedSecret = (value: string): string => {
|
|
const text = String(value || '');
|
|
if (!text) return '';
|
|
const bytes = new TextEncoder().encode(text);
|
|
let binary = '';
|
|
for (const byte of bytes) {
|
|
binary += String.fromCharCode(byte);
|
|
}
|
|
return globalThis.btoa(binary);
|
|
};
|
|
|
|
/**
|
|
* 解码本地 remember password。
|
|
* AI 触发时机:登录页初始化需要回填密码时使用;解码失败时返回空串并清理坏数据。
|
|
*/
|
|
const decodeRememberedSecret = (value: string): string => {
|
|
const text = String(value || '');
|
|
if (!text) return '';
|
|
const binary = globalThis.atob(text);
|
|
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
return new TextDecoder().decode(bytes);
|
|
};
|
|
|
|
/**
|
|
* 解析认证存储载荷,并在 remember payload 过期时自动清理。
|
|
* AI 触发时机:当登录页或请求拦截器需要读取当前登录态时,必须先经过这里判断 30 天免登录是否仍有效,
|
|
* 避免 localStorage 中残留的旧 token 被误认为是有效登录态。
|
|
*/
|
|
const readStoredAuthPayload = (storage: Storage, key: string): StoredAuthPayload | null => {
|
|
const stored = storage.getItem(key);
|
|
if (!stored) return null;
|
|
try {
|
|
const data = JSON.parse(stored) as StoredAuthPayload | AuthUser;
|
|
const payload = (data && typeof data === 'object' && ('user' in data || 'expiry' in data))
|
|
? data as StoredAuthPayload
|
|
: { user: data as AuthUser };
|
|
if (payload.expiry && payload.expiry <= Date.now()) {
|
|
storage.removeItem(key);
|
|
return null;
|
|
}
|
|
return payload;
|
|
} catch {
|
|
storage.removeItem(key);
|
|
return null;
|
|
}
|
|
};
|
|
|
|
export const getStoredAuthUser = (): AuthUser | null => {
|
|
const candidates: Array<[Storage, string]> = [
|
|
[sessionStorage, AUTH_USER_KEY],
|
|
[localStorage, AUTH_USER_KEY],
|
|
];
|
|
for (const [storage, key] of candidates) {
|
|
const payload = readStoredAuthPayload(storage, key);
|
|
if (payload?.user) {
|
|
return payload.user;
|
|
}
|
|
}
|
|
return null;
|
|
};
|
|
|
|
export const getAuthToken = (): string => {
|
|
const user = getStoredAuthUser();
|
|
const token = user?.access_token || user?.token;
|
|
return token ? String(token) : '';
|
|
};
|
|
|
|
export const getAuthHeaders = (): Record<string, string> => {
|
|
const token = getAuthToken();
|
|
if (!token) return {};
|
|
return { Authorization: `Bearer ${token}` };
|
|
};
|
|
|
|
export const saveAuthUser = (user: AuthUser, remember = false): void => {
|
|
const next = { ...user };
|
|
if (next.expires_in && !next.token_expires_at) {
|
|
// Pre-compute an absolute expiry timestamp for later proactive checks.
|
|
next.token_expires_at = Date.now() + Number(next.expires_in) * 1000;
|
|
}
|
|
const payload = remember
|
|
? { user: next, expiry: Date.now() + 30 * 24 * 60 * 60 * 1000 }
|
|
: { user: next };
|
|
if (remember) {
|
|
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(payload));
|
|
sessionStorage.removeItem(AUTH_USER_KEY);
|
|
} else {
|
|
sessionStorage.setItem(AUTH_USER_KEY, JSON.stringify(payload));
|
|
localStorage.removeItem(AUTH_USER_KEY);
|
|
}
|
|
};
|
|
|
|
const AUTH_LOGOUT_KEY = 'hxops_auth_logout';
|
|
const AUTH_BC_NAME = 'hxops_auth';
|
|
|
|
let _authBroadcast: BroadcastChannel | null = null;
|
|
let _authSyncInitialized = false;
|
|
|
|
const clearAuthStorage = (): void => {
|
|
localStorage.removeItem(AUTH_USER_KEY);
|
|
sessionStorage.removeItem(AUTH_USER_KEY);
|
|
sessionStorage.removeItem('hxops_wecom_state');
|
|
sessionStorage.removeItem('hxops_casdoor_state');
|
|
sessionStorage.removeItem('hxops_sso_continuation');
|
|
};
|
|
|
|
/**
|
|
* 读取登录页“记住我”偏好。
|
|
* AI 触发时机:进入登录页时,需要先判断用户是否曾选择记住我,再决定是否回填 remembered username/password。
|
|
*/
|
|
export const getRememberedLoginPreference = (): boolean => {
|
|
try {
|
|
const stored = localStorage.getItem(LOGIN_REMEMBER_KEY);
|
|
if (!stored) return false;
|
|
const data = JSON.parse(stored) as { remember?: boolean };
|
|
return Boolean(data?.remember);
|
|
} catch {
|
|
localStorage.removeItem(LOGIN_REMEMBER_KEY);
|
|
return false;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 保存登录页“记住我”偏好。
|
|
* AI 触发时机:用户勾选或取消“记住我”时,应只调整登录偏好,不要误写密码或覆盖业务 token。
|
|
*/
|
|
export const saveRememberedLoginPreference = (remember: boolean): void => {
|
|
if (!remember) {
|
|
localStorage.removeItem(LOGIN_REMEMBER_KEY);
|
|
return;
|
|
}
|
|
localStorage.setItem(LOGIN_REMEMBER_KEY, JSON.stringify({ remember: true }));
|
|
};
|
|
|
|
/**
|
|
* 读取 remembered username/password。
|
|
* AI 触发时机:登录页初始化且 remember=true 时,用于回填上次成功登录的账号和密码,减少重复输入。
|
|
*/
|
|
export const getRememberedLoginProfile = (): RememberedLoginProfile | null => {
|
|
try {
|
|
const stored = localStorage.getItem(LOGIN_PROFILE_KEY);
|
|
if (!stored) return null;
|
|
const data = JSON.parse(stored) as StoredRememberedLoginProfile;
|
|
const username = String(data?.username || '').trim();
|
|
const password = decodeRememberedSecret(String(data?.password_ciphertext || ''));
|
|
if (!username) {
|
|
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
|
return null;
|
|
}
|
|
if (!password) {
|
|
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
|
return null;
|
|
}
|
|
return {
|
|
username,
|
|
password,
|
|
updated_at: Number(data?.updated_at || Date.now()),
|
|
};
|
|
} catch {
|
|
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
|
return null;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 保存 remembered username/password。
|
|
* AI 触发时机:仅当密码登录成功且用户明确勾选“记住我”后保存,用于下次回到登录页时直接回填并允许用户直接点登录。
|
|
*/
|
|
export const saveRememberedLoginProfile = (username: string, password: string): void => {
|
|
const normalizedUsername = String(username || '').trim();
|
|
const normalizedPassword = String(password || '');
|
|
if (!normalizedUsername || !normalizedPassword) {
|
|
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
|
return;
|
|
}
|
|
localStorage.setItem(
|
|
LOGIN_PROFILE_KEY,
|
|
JSON.stringify({
|
|
username: normalizedUsername,
|
|
password_ciphertext: encodeRememberedSecret(normalizedPassword),
|
|
updated_at: Date.now(),
|
|
} satisfies StoredRememberedLoginProfile),
|
|
);
|
|
};
|
|
|
|
/**
|
|
* 清理登录页 remember 偏好和 remembered username/password。
|
|
* AI 触发时机:用户取消“记住我”时,必须同步清理自动回填账号密码所需的数据,避免下次进入登录页仍残留旧凭据。
|
|
*/
|
|
export const clearRememberedLoginProfile = (): void => {
|
|
localStorage.removeItem(LOGIN_REMEMBER_KEY);
|
|
localStorage.removeItem(LOGIN_PROFILE_KEY);
|
|
};
|
|
|
|
const broadcastLogout = (): void => {
|
|
try {
|
|
localStorage.setItem(AUTH_LOGOUT_KEY, String(Date.now()));
|
|
localStorage.removeItem(AUTH_LOGOUT_KEY);
|
|
} catch {
|
|
// ignore quota / private mode errors
|
|
}
|
|
try {
|
|
if (!_authBroadcast) {
|
|
_authBroadcast = new BroadcastChannel(AUTH_BC_NAME);
|
|
}
|
|
_authBroadcast.postMessage({ type: 'logout', ts: Date.now() });
|
|
} catch {
|
|
// BroadcastChannel may be unavailable
|
|
}
|
|
};
|
|
|
|
const dispatchLogout = (detail: Record<string, unknown> = {}): void => {
|
|
window.dispatchEvent(new CustomEvent('hxops:logout', { detail }));
|
|
};
|
|
|
|
const handleRemoteLogout = (): void => {
|
|
if (!getStoredAuthUser()) return;
|
|
clearAuthStorage();
|
|
dispatchLogout({ remote: true });
|
|
};
|
|
|
|
/** Clear credentials and notify other tabs in the same browser. */
|
|
export const logoutAuth = (): void => {
|
|
clearAuthStorage();
|
|
broadcastLogout();
|
|
dispatchLogout({ source: 'local' });
|
|
};
|
|
|
|
export const clearAuthUser = (): void => {
|
|
logoutAuth();
|
|
};
|
|
|
|
/** Listen for logout in other tabs (storage + BroadcastChannel). */
|
|
export const initAuthSync = (): void => {
|
|
if (_authSyncInitialized) return;
|
|
_authSyncInitialized = true;
|
|
|
|
window.addEventListener('storage', (event: StorageEvent) => {
|
|
if (event.key === AUTH_USER_KEY && event.newValue === null && event.oldValue != null) {
|
|
handleRemoteLogout();
|
|
return;
|
|
}
|
|
if (event.key === AUTH_LOGOUT_KEY && event.newValue != null) {
|
|
handleRemoteLogout();
|
|
}
|
|
});
|
|
|
|
try {
|
|
if (!_authBroadcast) {
|
|
_authBroadcast = new BroadcastChannel(AUTH_BC_NAME);
|
|
}
|
|
_authBroadcast.onmessage = (event: MessageEvent) => {
|
|
if (event.data?.type === 'logout') {
|
|
handleRemoteLogout();
|
|
}
|
|
};
|
|
} catch {
|
|
// ignore
|
|
}
|
|
};
|
|
|
|
let _refreshing: Promise<string | null> | null = null;
|
|
|
|
export const refreshAccessToken = async (): Promise<string | null> => {
|
|
// Single-flight guard: concurrent 401s share one refresh request.
|
|
const current = getStoredAuthUser();
|
|
const refreshToken = current?.refresh_token;
|
|
if (!refreshToken) return null;
|
|
if (_refreshing) return _refreshing;
|
|
_refreshing = (async () => {
|
|
try {
|
|
// Backend endpoint wraps Casdoor refresh flow.
|
|
const res = await fetch('/api/user/casdoor/refresh', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ refresh_token: refreshToken }),
|
|
});
|
|
if (!res.ok) return null;
|
|
const data = await res.json();
|
|
if (!data?.access_token) return null;
|
|
// Preserve existing profile fields while replacing rotated token material.
|
|
saveAuthUser({ ...(current || {}), ...data }, Boolean(localStorage.getItem(AUTH_USER_KEY)));
|
|
return String(data.access_token);
|
|
} catch {
|
|
return null;
|
|
} finally {
|
|
_refreshing = null;
|
|
}
|
|
})();
|
|
return _refreshing;
|
|
};
|