import cookieParser from 'cookie-parser' import { config } from '../config.js' import { isSessionPasswordCurrent } from '../services/passwordVersion.js' import { clearPreviewSession } from '../services/previewSession.js' export const SESSION_REVOKED_MESSAGE = 'Dein Passwort wurde geändert. Bitte melde dich mit dem neuen Passwort an.' const SESSION_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000 export function sessionMiddleware() { return cookieParser(config.sessionSecret) } export function setPortalSession(res, data, { maxAgeMs = SESSION_MAX_AGE_MS } = {}) { res.cookie(config.cookieName, JSON.stringify(data), { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', maxAge: maxAgeMs, signed: true, }) } export function clearPortalSession(res) { res.clearCookie(config.cookieName, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', signed: true, }) } export function parsePortalSession(req) { const raw = req.signedCookies?.[config.cookieName] if (!raw) return null try { return JSON.parse(raw) } catch { return null } } export async function requireSession(req, res, next) { const session = parsePortalSession(req) if (!session) { return res.status(401).json({ error: 'Nicht angemeldet' }) } if (!session.customerId || !session.appwriteUserId) { return res.status(401).json({ error: 'Ungültige Session' }) } // Nach einer Passwortaenderung gelten aeltere Sessions nicht mehr (auf anderen Geraeten abgemeldet) if (!(await isSessionPasswordCurrent(session))) { clearPortalSession(res) clearPreviewSession(res) return res.status(401).json({ error: SESSION_REVOKED_MESSAGE, code: 'session_revoked' }) } req.session = session next() } export function getSessionCustomerId(req) { return req.session?.customerId }