ls-deno/routes/_middleware.tsx

59 lines
1.5 KiB
TypeScript
Raw Normal View History

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-11 17:12:32 -05:00
import { type ContextState, type PublicUser, type User } from "@/types.ts";
2022-10-11 23:49:36 -05:00
import { log } from "@/log.ts";
2022-10-11 17:12:32 -05:00
function toPublicUser(user: User): PublicUser {
const {
createdAt: _createdAt,
updatedAt: _updatedAt,
passwordDigest: _passwordDigest,
...publicUser
} = user;
return publicUser;
}
2022-09-27 14:41:17 -05:00
2022-10-10 21:44:20 -05:00
async function currentUser(
2022-10-08 02:01:48 -05:00
request: Request,
2022-10-10 21:44:20 -05:00
context: 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);
2022-11-10 14:34:27 -06:00
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);
}
2022-10-08 02:01:48 -05:00
if (lsauth) {
2022-10-21 03:06:37 -05:00
try {
context.state.user = toPublicUser(
await getUserFromNonExpiredLoginToken(lsauth),
);
} catch (e) {
hasBadAuthCookie = true;
2022-10-08 02:53:13 -05:00
}
2022-10-08 02:01:48 -05:00
}
2022-10-10 21:44:20 -05:00
const resp = await context.next();
2022-11-10 14:34:27 -06:00
if (resp && hasBadAuthCookie) {
deleteCookie(resp.headers, "lsauth");
2022-10-10 21:44:20 -05:00
}
return resp;
}
2022-10-08 02:01:48 -05:00
2022-10-10 21:44:20 -05:00
export async function serverHeader(
_request: Request,
context: MiddlewareHandlerContext<ContextState>,
) {
const resp = await context.next();
2022-10-08 02:01:48 -05:00
if (resp) {
resp.headers.set("server", "fresh server");
}
2022-09-27 14:41:17 -05:00
return resp;
}
2022-10-10 21:44:20 -05:00
export const handler = [
currentUser,
serverHeader,
];