import { pikkuMiddleware } from '@pikku/core' import type { SingletonServices } from '../application-types.d.js' export const SESSION_COOKIE = 'sh_session' export const sessionCookieMiddleware = pikkuMiddleware( async ({ kysely }, { http, setSession, session }, next) => { if (!http?.request || !setSession || session) { return next() } const token = http.request.cookie(SESSION_COOKIE) if (token) { const row = await kysely .selectFrom('bookingSession') .innerJoin('user', 'user.id', 'bookingSession.userId') .where('bookingSession.sessionId', '=', token) .where('bookingSession.expiresAt', '>', new Date().toISOString()) .select(['user.id as userId', 'user.role']) .executeTakeFirst() if (row) { setSession({ userId: row.userId, role: row.role as string }) } } await next() }, )