ls-deno/routes/_middleware.ts

31 lines
935 B
TypeScript
Raw Normal View History

2022-09-27 14:41:17 -05:00
import { MiddlewareHandlerContext } from "$fresh/server.ts";
2022-10-08 02:01:48 -05:00
import { deleteCookie, getCookies } from "$std/http/cookie.ts";
import { getUserFromNonExpiredLoginToken } from "@/db/mod.ts";
2022-10-08 02:53:13 -05:00
import { type ContextState } from "@/types.ts";
2022-09-27 14:41:17 -05:00
export async function handler(
2022-10-08 02:01:48 -05:00
request: Request,
2022-10-08 02:53:13 -05:00
ctx: MiddlewareHandlerContext<ContextState>,
2022-09-27 14:41:17 -05:00
) {
2022-10-08 02:01:48 -05:00
let hasBadAuthCookie = false;
const { lsauth } = getCookies(request.headers);
console.log("lsauth cookie:", lsauth);
if (lsauth) {
const user = await getUserFromNonExpiredLoginToken(lsauth);
if (!user) hasBadAuthCookie = true;
2022-10-08 02:53:13 -05:00
else {
ctx.state.user = user;
delete ctx.state.user.createdAt;
delete ctx.state.user.updatedAt;
delete ctx.state.user.passwordDigest;
}
2022-10-08 02:01:48 -05:00
}
2022-09-27 14:41:17 -05:00
const resp = await ctx.next();
2022-10-08 02:01:48 -05:00
if (resp) {
resp.headers.set("server", "fresh server");
if (hasBadAuthCookie) deleteCookie(resp.headers, "lsauth");
}
2022-09-27 14:41:17 -05:00
return resp;
}