Download src/lib/session.ts from HonzaH/Letschat: direct link, hf CLI and curl.
- Browser
- Download file 2.11 kB
-
https://huggingface.co/spaces/HonzaH/Letschat/resolve/main/src/lib/session.ts
- Command line
-
hf download hf://spaces/HonzaH/Letschat/src/lib/session.ts
-
curl -L -o session.ts https://huggingface.co/spaces/HonzaH/Letschat/resolve/main/src/lib/session.ts
2.11 kB
| import { cookies } from 'next/headers' | |
| export interface AnonymousSession { | |
| codeId: string | |
| sessionHash: string | |
| roomId?: string | |
| expiresAt: number | |
| } | |
| const SESSION_COOKIE_NAME = 'letschat_anonymous_session' | |
| const DEFAULT_SESSION_DURATION = 30 * 24 * 60 * 60 * 1000 // 30 dní | |
| export async function setAnonymousSession(session: AnonymousSession) { | |
| // Await cookies() to avoid sync-access warnings in Next.js runtime | |
| // Use a permissive any cast because Next's cookie types differ between versions | |
| // and we only need get/set/delete methods at runtime. | |
| // @ts-ignore | |
| const cookieStore = await cookies() as any | |
| const effectiveExpiresAt = session.expiresAt || (Date.now() + DEFAULT_SESSION_DURATION) | |
| const maxAgeSeconds = Math.max(1, Math.floor((effectiveExpiresAt - Date.now()) / 1000)) | |
| cookieStore.set(SESSION_COOKIE_NAME, JSON.stringify({ ...session, expiresAt: effectiveExpiresAt }), { | |
| httpOnly: true, | |
| secure: process.env.NODE_ENV === 'production', | |
| sameSite: 'lax', | |
| maxAge: maxAgeSeconds, | |
| path: '/' | |
| }) | |
| } | |
| export async function getAnonymousSession(): Promise<AnonymousSession | null> { | |
| try { | |
| // @ts-ignore | |
| const cookieStore = await cookies() as any | |
| const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME) | |
| if (!sessionCookie?.value) { | |
| return null | |
| } | |
| const session: AnonymousSession = JSON.parse(sessionCookie.value) | |
| // Check if session is expired | |
| if (Date.now() > session.expiresAt) { | |
| await clearAnonymousSession() | |
| return null | |
| } | |
| return session | |
| } catch (error) { | |
| console.error('Error parsing anonymous session:', error) | |
| await clearAnonymousSession() | |
| return null | |
| } | |
| } | |
| export async function clearAnonymousSession() { | |
| // @ts-ignore | |
| const cookieStore = await cookies() as any | |
| // Prefer delete if available, otherwise set cookie to expired | |
| if (typeof cookieStore.delete === 'function') { | |
| cookieStore.delete(SESSION_COOKIE_NAME) | |
| } else { | |
| cookieStore.set(SESSION_COOKIE_NAME, '', { maxAge: 0, path: '/' }) | |
| } | |
| } | |