ls-deno/routes/_middleware.ts

45 lines
1.2 KiB
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
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);
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 {
2022-10-10 21:44:20 -05:00
context.state.user = user;
delete context.state.user.createdAt;
delete context.state.user.updatedAt;
delete context.state.user.passwordDigest;
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();
if (resp) {
if (hasBadAuthCookie) deleteCookie(resp.headers, "lsauth");
}
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,
];