feat(auth): 重构认证逻辑,支持 HttpOnly Cookie 登录;移除不再使用的 Token 存储方式
Some checks failed
lotteryadmin CI / build (push) Has been cancelled
Some checks failed
lotteryadmin CI / build (push) Has been cancelled
This commit is contained in:
@@ -3,6 +3,13 @@ import {
|
||||
ADMIN_TOKEN_STORAGE_KEY,
|
||||
} from "@/lib/admin-token-constants";
|
||||
|
||||
const COOKIE_BASE_OPTIONS = {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: ADMIN_TOKEN_COOKIE_MAX_AGE_SECONDS,
|
||||
} as const;
|
||||
|
||||
export function readAdminTokenFromCookieString(
|
||||
cookieHeader: string | null | undefined,
|
||||
): string | null {
|
||||
@@ -32,30 +39,24 @@ export function readAdminTokenFromCookieString(
|
||||
}
|
||||
|
||||
export function readAdminTokenFromDocumentCookie(): string | null {
|
||||
if (typeof document === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return readAdminTokenFromCookieString(document.cookie);
|
||||
return null;
|
||||
}
|
||||
|
||||
export function writeAdminTokenCookie(token: string | null): void {
|
||||
if (typeof document === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
const secure =
|
||||
typeof window !== "undefined" && window.location.protocol === "https:";
|
||||
const base = `path=/; SameSite=Lax`;
|
||||
|
||||
if (!token || token.trim() === "") {
|
||||
document.cookie = `${ADMIN_TOKEN_STORAGE_KEY}=; ${base}; max-age=0`;
|
||||
return;
|
||||
}
|
||||
|
||||
const value = encodeURIComponent(token.trim());
|
||||
const maxAge = `max-age=${ADMIN_TOKEN_COOKIE_MAX_AGE_SECONDS}`;
|
||||
document.cookie = `${ADMIN_TOKEN_STORAGE_KEY}=${value}; ${base}; ${maxAge}${
|
||||
secure ? "; Secure" : ""
|
||||
}`;
|
||||
void token;
|
||||
}
|
||||
|
||||
export function adminTokenCookieOptions(secure: boolean) {
|
||||
return {
|
||||
...COOKIE_BASE_OPTIONS,
|
||||
secure,
|
||||
};
|
||||
}
|
||||
|
||||
export function expiredAdminTokenCookieOptions(secure: boolean) {
|
||||
return {
|
||||
...COOKIE_BASE_OPTIONS,
|
||||
secure,
|
||||
maxAge: 0,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user