ls-deno/routes/_middleware.ts
2022-10-08 02:01:48 -05:00

35 lines
963 B
TypeScript

import { MiddlewareHandlerContext } from "$fresh/server.ts";
import { deleteCookie, getCookies } from "$std/http/cookie.ts";
import { getUserFromNonExpiredLoginToken } from "@/db/mod.ts";
interface State {
data: string;
}
export async function handler(
request: Request,
ctx: MiddlewareHandlerContext<State>,
) {
ctx.state.data = "";
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.data += "user:" + JSON.stringify({
id: user.id,
username: user.username,
displayName: user.displayName || user.username,
}) +
"\n";}
}
const resp = await ctx.next();
if (resp) {
resp.headers.set("server", "fresh server");
if (hasBadAuthCookie) deleteCookie(resp.headers, "lsauth");
}
return resp;
}