import { MiddlewareHandlerContext } from "$fresh/server.ts"; import { deleteCookie, getCookies } from "$std/http/cookie.ts"; import { getUserFromNonExpiredLoginToken } from "@/db/mod.ts"; import { type ContextState } from "@/types.ts"; async function currentUser( request: Request, context: MiddlewareHandlerContext, ) { let hasBadAuthCookie = false; const { lsauth } = getCookies(request.headers); console.log("lsauth cookie:", lsauth); if (lsauth) { const user = await getUserFromNonExpiredLoginToken(lsauth); if (!user) hasBadAuthCookie = true; else { context.state.user = user; delete context.state.user.createdAt; delete context.state.user.updatedAt; delete context.state.user.passwordDigest; } } const resp = await context.next(); if (resp) { if (hasBadAuthCookie) deleteCookie(resp.headers, "lsauth"); } return resp; } export async function serverHeader( _request: Request, context: MiddlewareHandlerContext, ) { const resp = await context.next(); if (resp) { resp.headers.set("server", "fresh server"); } return resp; } export const handler = [ currentUser, serverHeader, ];