website/routes/_middleware.ts

63 lines
1.5 KiB
TypeScript
Raw Normal View History

import { FreshContext } from '$fresh/server.ts'
import { deleteCookie, getCookies, setCookie } from '@std/http/cookie'
2024-06-13 12:20:47 +02:00
import { SessionStore } from '../src/session/mod.ts'
const instanceToken = crypto.randomUUID() // Instance uuid to reset perform cookie reset on server restart
export async function handler(request: Request, ctx: FreshContext) {
// Allow service worker to serve root scope
const response = await ctx.next()
const url = new URL(request.url)
if (url.pathname.endsWith('island-startserviceworker.js')) {
response.headers.set('Service-Worker-Allowed', '/')
}
2024-06-13 12:20:47 +02:00
const cookies = getCookies(request.headers)
// Clear outdated cookies
if (cookies['_INSTANCE'] !== instanceToken) {
for (const cookie in cookies) {
deleteCookie(request.headers, cookie)
}
setCookie(response.headers, {
name: '_INSTANCE',
value: instanceToken,
httpOnly: true,
sameSite: 'Strict',
secure: true,
})
}
2024-06-13 12:20:47 +02:00
// Start session
if (cookies['_SESSION'] === undefined) {
2024-06-13 12:20:47 +02:00
const session = SessionStore.createSession()
// Set session cookie
setCookie(response.headers, {
name: '_SESSION',
value: session.uuid,
httpOnly: true,
sameSite: 'Strict',
secure: true,
2024-06-13 14:38:27 +02:00
path: '/',
2024-06-13 12:20:47 +02:00
expires: SessionStore.maxAge,
})
// Set csrf
const csrf = crypto.randomUUID()
session.set('_csrf', csrf)
setCookie(response.headers, {
name: '_CSRF',
value: csrf,
httpOnly: false,
sameSite: 'Strict',
secure: true,
2024-06-13 14:38:27 +02:00
path: '/',
2024-06-13 12:20:47 +02:00
expires: SessionStore.maxAge,
})
}
return response
}