feat: add cookies auto reset

This commit is contained in:
Julien Oculi 2024-06-13 13:47:46 +02:00
parent 7a6497a5fe
commit 8dc12c4e0d

View file

@ -1,7 +1,9 @@
import { FreshContext } from '$fresh/server.ts' import { FreshContext } from '$fresh/server.ts'
import { getCookies, setCookie } from '@std/http/cookie' import { deleteCookie, getCookies, setCookie } from '@std/http/cookie'
import { SessionStore } from '../src/session/mod.ts' 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) { export async function handler(request: Request, ctx: FreshContext) {
// Allow service worker to serve root scope // Allow service worker to serve root scope
const response = await ctx.next() const response = await ctx.next()
@ -10,8 +12,24 @@ export async function handler(request: Request, ctx: FreshContext) {
response.headers.set('Service-Worker-Allowed', '/') response.headers.set('Service-Worker-Allowed', '/')
} }
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,
})
}
// Start session // Start session
if (getCookies(request.headers)['_SESSION'] === undefined) { if (cookies['_SESSION'] === undefined) {
const session = SessionStore.createSession() const session = SessionStore.createSession()
// Set session cookie // Set session cookie