Files
seminarhof-e2e-mrffmekh/packages/functions/src/middleware/session-cookie.ts
2026-07-10 23:12:46 +02:00

27 lines
910 B
TypeScript

import { pikkuMiddleware } from '@pikku/core'
import type { SingletonServices } from '../application-types.d.js'
export const SESSION_COOKIE = 'sh_session'
export const sessionCookieMiddleware = pikkuMiddleware<SingletonServices>(
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()
},
)