import { cookies } from 'next/headers'; import { SignJWT, jwtVerify } from 'jose'; const SESSION_COOKIE_NAME = 'auth_session'; const SESSION_DURATION = 7 * 24 * 60 * 60 * 1000; // 7 Tage const secretKey = process.env.AUTH_SECRET || 'default-secret-change-in-production'; const key = new TextEncoder().encode(secretKey); export interface SessionData { username: string; isAuthenticated: boolean; expiresAt: number; } async function encrypt(payload: SessionData): Promise { return await new SignJWT(payload as unknown as Record) .setProtectedHeader({ alg: 'HS256' }) .setIssuedAt() .setExpirationTime(new Date(payload.expiresAt)) .sign(key); } async function decrypt(token: string): Promise { try { const { payload } = await jwtVerify(token, key, { algorithms: ['HS256'], }); return { username: payload.username as string, isAuthenticated: payload.isAuthenticated as boolean, expiresAt: payload.expiresAt as number, }; } catch { return null; } } export async function createSession(username: string): Promise { const expiresAt = Date.now() + SESSION_DURATION; const session: SessionData = { username, isAuthenticated: true, expiresAt }; const encryptedSession = await encrypt(session); const cookieStore = await cookies(); cookieStore.set(SESSION_COOKIE_NAME, encryptedSession, { httpOnly: true, secure: process.env.NODE_ENV === 'production', expires: expiresAt, sameSite: 'lax', path: '/', }); } export async function getSession(): Promise { const cookieStore = await cookies(); const cookie = cookieStore.get(SESSION_COOKIE_NAME); if (!cookie?.value) return null; const session = await decrypt(cookie.value); if (!session || session.expiresAt < Date.now()) return null; return session; } export async function deleteSession(): Promise { const cookieStore = await cookies(); cookieStore.delete(SESSION_COOKIE_NAME); } export async function isAuthenticated(): Promise { const session = await getSession(); return session?.isAuthenticated ?? false; }