feat(frontend): 步骤 6.5 — Cookie 工具函数
This commit is contained in:
40
frontend/src/utils/cookie.ts
Normal file
40
frontend/src/utils/cookie.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
const COOKIE_NAME = "ai_agent_login";
|
||||||
|
const COOKIE_DAYS = 7;
|
||||||
|
|
||||||
|
export interface UserInfo {
|
||||||
|
user: string;
|
||||||
|
ts: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setCookie(name: string, value: string, days: number) {
|
||||||
|
const expires = new Date(Date.now() + days * 864e5).toUTCString();
|
||||||
|
document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires};path=/`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCookie(name: string): string | null {
|
||||||
|
const match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
|
||||||
|
return match ? decodeURIComponent(match[2]) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteCookie(name: string) {
|
||||||
|
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setUserInfo(user: string) {
|
||||||
|
const info: UserInfo = { user, ts: Date.now() };
|
||||||
|
setCookie(COOKIE_NAME, JSON.stringify(info), COOKIE_DAYS);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getUserInfo(): UserInfo | null {
|
||||||
|
const raw = getCookie(COOKIE_NAME);
|
||||||
|
if (!raw) return null;
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw) as UserInfo;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearUserInfo() {
|
||||||
|
deleteCookie(COOKIE_NAME);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user