35 lines
876 B
TypeScript
35 lines
876 B
TypeScript
export const SESSION_COOKIE_NAME = "session"
|
|
|
|
const SESSION_KEY_PREFIX = "label:session:"
|
|
|
|
const normalizeClientIp = (ip: string) => ip.replace(/^::ffff:/, "")
|
|
|
|
export const createSessionRedisKey = () =>
|
|
`${SESSION_KEY_PREFIX}${crypto.randomUUID()}`
|
|
|
|
export const getSessionRedisKeyFromCookieValue = (
|
|
sessionCookieValue?: string | null
|
|
) => {
|
|
if (!sessionCookieValue) {
|
|
return ""
|
|
}
|
|
|
|
try {
|
|
const parsedValue = JSON.parse(sessionCookieValue)
|
|
return typeof parsedValue === "string" ? parsedValue : ""
|
|
} catch {
|
|
return sessionCookieValue
|
|
}
|
|
}
|
|
|
|
export const getClientIpFromRequest = (req: any) => {
|
|
const forwardedFor =
|
|
req?.headers?.get?.("x-forwarded-for") ||
|
|
req?.headers?.["x-forwarded-for"] ||
|
|
""
|
|
const clientIP =
|
|
forwardedFor?.split(",")[0]?.trim() || req?.socket?.remoteAddress || ""
|
|
|
|
return normalizeClientIp(clientIP)
|
|
}
|