78 lines
2.0 KiB
TypeScript
78 lines
2.0 KiB
TypeScript
import type { AuthConfig } from "./types";
|
|
import { getCookie, setCookie, removeCookie } from "./cookie";
|
|
|
|
export function createTokenManager(config: AuthConfig) {
|
|
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
|
|
|
|
const getCookieDomain = (): string | undefined => {
|
|
if (typeof window === "undefined") return undefined;
|
|
|
|
if (config.cookieDomain) return config.cookieDomain;
|
|
|
|
const { hostname } = window.location;
|
|
if (hostname === "localhost" || hostname === "127.0.0.1") return undefined;
|
|
|
|
return hostname;
|
|
};
|
|
|
|
return {
|
|
getToken(key: string): string | undefined {
|
|
return getCookie(key);
|
|
},
|
|
|
|
setToken(key: string, value: string): void {
|
|
const domain = getCookieDomain();
|
|
const isHttps =
|
|
typeof window !== "undefined" && window.location.protocol === "https:";
|
|
|
|
setCookie(key, value, {
|
|
secure: isHttps,
|
|
sameSite: "lax",
|
|
domain,
|
|
path: "/",
|
|
});
|
|
},
|
|
|
|
removeToken(key: string): void {
|
|
const domain = getCookieDomain();
|
|
removeCookie(key, { domain, path: "/" });
|
|
},
|
|
|
|
setupRefreshTimer(callback: () => Promise<void>, delayMs: number): void {
|
|
if (refreshTimer) {
|
|
clearTimeout(refreshTimer);
|
|
}
|
|
|
|
refreshTimer = setTimeout(() => {
|
|
callback().catch((error) => {
|
|
console.error("Silent refresh timer callback failed:", error);
|
|
});
|
|
}, delayMs);
|
|
},
|
|
|
|
clearAuthToken(): void {
|
|
if (refreshTimer) {
|
|
clearTimeout(refreshTimer);
|
|
refreshTimer = null;
|
|
}
|
|
|
|
this.removeToken(config.claimName);
|
|
this.removeToken(config.authUserId);
|
|
},
|
|
|
|
getAccessToken(): string | undefined {
|
|
return this.getToken(config.claimName);
|
|
},
|
|
|
|
getRefreshToken(): string | undefined {
|
|
return config.refreshToken ? this.getToken(config.refreshToken) : undefined;
|
|
},
|
|
|
|
getUserId(): string | undefined {
|
|
return this.getToken(config.authUserId);
|
|
},
|
|
};
|
|
}
|
|
|
|
export type TokenManager = ReturnType<typeof createTokenManager>;
|