ls-deno/routes/_middleware.tsx
2022-11-10 16:39:48 -06:00

59 lines
1.5 KiB
TypeScript

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<ContextState>,
) {
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<ContextState>,
) {
const resp = await context.next();
if (resp) {
resp.headers.set("server", "fresh server");
}
return resp;
}
export const handler = [
currentUser,
serverHeader,
];