From 8dc12c4e0d6e9fff446dad21ef8d8a60e8424034 Mon Sep 17 00:00:00 2001 From: Julien Oculi Date: Thu, 13 Jun 2024 13:47:46 +0200 Subject: [PATCH] feat: :sparkles: add cookies auto reset --- routes/_middleware.ts | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/routes/_middleware.ts b/routes/_middleware.ts index 86a88bb..ca79b40 100644 --- a/routes/_middleware.ts +++ b/routes/_middleware.ts @@ -1,7 +1,9 @@ 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' +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() @@ -10,8 +12,24 @@ export async function handler(request: Request, ctx: FreshContext) { 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 - if (getCookies(request.headers)['_SESSION'] === undefined) { + if (cookies['_SESSION'] === undefined) { const session = SessionStore.createSession() // Set session cookie