import { MiddlewareHandlerContext } from "$fresh/server.ts"; import { deleteCookie, getCookies } from "$std/http/cookie.ts"; import { getUserFromNonExpiredLoginToken } from "@/db/mod.ts"; import { type ContextState, type PublicUser, type User } from "@/types.ts"; import { log } from "@/log.ts"; function toPublicUser(user: User): PublicUser { const { createdAt: _createdAt, updatedAt: _updatedAt, passwordDigest: _passwordDigest, ...publicUser } = user; return publicUser; } async function currentUser( request: Request, context: MiddlewareHandlerContext, ) { let hasBadAuthCookie = false; const { lsauth } = getCookies(request.headers); const url = new URL(request.url); if (!url.pathname.startsWith("/_frsh/") || url.pathname == "favicon.ico") { // don't log certain requests' cookies log.info("lsauth cookie:", lsauth); } if (lsauth) { try { context.state.user = toPublicUser( await getUserFromNonExpiredLoginToken(lsauth), ); } catch (e) { hasBadAuthCookie = true; } } const resp = await context.next(); if (resp && 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, ];