ls-deno/routes/_middleware.tsx

74 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-10-12 03:31:26 -05:00
import { LayoutProps, 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-12 03:31:26 -05:00
function Layout({ state, Component }: LayoutProps<ContextState>) {
return (
<>
{state.something
? <p>Oh my! You said something!</p>
: <p>You aren't saying anything.</p>}
<Component />
</>
);
}
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-12 03:31:26 -05:00
context.layout = Layout;
2022-10-08 02:01:48 -05:00
let hasBadAuthCookie = false;
const { lsauth } = getCookies(request.headers);
2022-10-11 23:49:36 -05:00
log.debug("lsauth cookie:", lsauth);
2022-10-08 02:01:48 -05:00
if (lsauth) {
const user = await getUserFromNonExpiredLoginToken(lsauth);
if (!user) hasBadAuthCookie = true;
2022-10-08 02:53:13 -05:00
else {
2022-10-11 17:12:32 -05:00
context.state.user = toPublicUser(user);
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
2022-10-12 03:31:26 -05:00
export async function someState(
_request: Request,
context: MiddlewareHandlerContext<ContextState>,
) {
context.state.something = "I said something!";
return await context.next();
}
2022-10-10 21:44:20 -05:00
export const handler = [
2022-10-12 03:31:26 -05:00
someState,
2022-10-10 21:44:20 -05:00
currentUser,
serverHeader,
];