ls-deno/routes/_middleware.ts

31 lines
935 B
TypeScript

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";
export async function handler(
request: Request,
ctx: MiddlewareHandlerContext<ContextState>,
) {
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 {
ctx.state.user = user;
delete ctx.state.user.createdAt;
delete ctx.state.user.updatedAt;
delete ctx.state.user.passwordDigest;
}
}
const resp = await ctx.next();
if (resp) {
resp.headers.set("server", "fresh server");
if (hasBadAuthCookie) deleteCookie(resp.headers, "lsauth");
}
return resp;
}