Browse Source
feat: implement cookie handling for HABIB_TOKEN and HABIB_COINS in AuthBridge and update request headers
master
feat: implement cookie handling for HABIB_TOKEN and HABIB_COINS in AuthBridge and update request headers
master
5 changed files with 207 additions and 56 deletions
-
27src/app/api/proxy/route.ts
-
70src/app/layout.tsx
-
77src/lib/auth-bridge.ts
-
65src/lib/cookies.ts
-
14src/lib/http.ts
@ -0,0 +1,65 @@ |
|||
const DEFAULT_COOKIE_PATH = "/"; |
|||
const DEFAULT_COOKIE_MAX_AGE = 60 * 60 * 24 * 30; |
|||
|
|||
function isClient() { |
|||
return typeof document !== "undefined"; |
|||
} |
|||
|
|||
function escapeCookieName(name: string) { |
|||
return name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); |
|||
} |
|||
|
|||
export function getClientCookie(name: string) { |
|||
if (!isClient()) { |
|||
return null; |
|||
} |
|||
|
|||
const match = document.cookie.match( |
|||
new RegExp(`(?:^|; )${escapeCookieName(name)}=([^;]*)`), |
|||
); |
|||
|
|||
return match ? decodeURIComponent(match[1]) : null; |
|||
} |
|||
|
|||
export function setClientCookie( |
|||
name: string, |
|||
value: string, |
|||
options?: { |
|||
maxAge?: number; |
|||
path?: string; |
|||
sameSite?: "Lax" | "Strict" | "None"; |
|||
secure?: boolean; |
|||
}, |
|||
) { |
|||
if (!isClient()) { |
|||
return; |
|||
} |
|||
|
|||
const maxAge = options?.maxAge ?? DEFAULT_COOKIE_MAX_AGE; |
|||
const path = options?.path ?? DEFAULT_COOKIE_PATH; |
|||
const sameSite = options?.sameSite ?? "Lax"; |
|||
const secure = options?.secure ?? window.location.protocol === "https:"; |
|||
|
|||
let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; Max-Age=${maxAge}; SameSite=${sameSite}`; |
|||
|
|||
if (secure) { |
|||
cookie += "; Secure"; |
|||
} |
|||
|
|||
document.cookie = cookie; |
|||
} |
|||
|
|||
export function deleteClientCookie(name: string, path = DEFAULT_COOKIE_PATH) { |
|||
if (!isClient()) { |
|||
return; |
|||
} |
|||
|
|||
const secure = window.location.protocol === "https:"; |
|||
let cookie = `${name}=; Path=${path}; Max-Age=0; SameSite=Lax`; |
|||
|
|||
if (secure) { |
|||
cookie += "; Secure"; |
|||
} |
|||
|
|||
document.cookie = cookie; |
|||
} |
|||
Write
Preview
Loading…
Cancel
Save
Reference in new issue