管理台可以密码登录、按角色进入,并把 Watchman 会话 token 交给浏览器。HXOPS 真实跳转仍未联调。 Co-authored-by: Cursor <cursoragent@cursor.com>
58 lines
1.5 KiB
TypeScript
58 lines
1.5 KiB
TypeScript
/** Browser copy of the Watchman session. This is not a Casdoor token. */
|
|
|
|
export type SessionUser = {
|
|
subject: string;
|
|
display_name: string;
|
|
login_name?: string;
|
|
roles: string[];
|
|
access_token?: string;
|
|
token_type?: string;
|
|
expires_in?: number;
|
|
token_expires_at?: number;
|
|
};
|
|
|
|
const STORAGE_KEY = "watchman_user";
|
|
const ENTER_ROLES = new Set(["watchman-admin", "watchman-operator", "watchman-viewer"]);
|
|
|
|
export function allowsEnter(roles: string[]): boolean {
|
|
return roles.some((role) => ENTER_ROLES.has(role));
|
|
}
|
|
|
|
export function saveSession(user: SessionUser): void {
|
|
const next = { ...user };
|
|
if (next.expires_in && !next.token_expires_at) {
|
|
next.token_expires_at = Date.now() + next.expires_in * 1000;
|
|
}
|
|
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
|
}
|
|
|
|
export function loadSession(): SessionUser | null {
|
|
const raw = sessionStorage.getItem(STORAGE_KEY);
|
|
if (!raw) {
|
|
return null;
|
|
}
|
|
try {
|
|
const user = JSON.parse(raw) as SessionUser;
|
|
if (user.token_expires_at && user.token_expires_at <= Date.now()) {
|
|
sessionStorage.removeItem(STORAGE_KEY);
|
|
return null;
|
|
}
|
|
return user;
|
|
} catch {
|
|
sessionStorage.removeItem(STORAGE_KEY);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function clearSession(): void {
|
|
sessionStorage.removeItem(STORAGE_KEY);
|
|
}
|
|
|
|
export function authHeaders(): Record<string, string> {
|
|
const token = loadSession()?.access_token;
|
|
if (!token) {
|
|
return {};
|
|
}
|
|
return { Authorization: `Bearer ${token}` };
|
|
}
|