52 lines
1.3 KiB
TypeScript
52 lines
1.3 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";
|
|
|
|
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);
|
|
console.log("lsauth cookie:", lsauth);
|
|
if (lsauth) {
|
|
const user = await getUserFromNonExpiredLoginToken(lsauth);
|
|
if (!user) hasBadAuthCookie = true;
|
|
else {
|
|
context.state.user = toPublicUser(user);
|
|
}
|
|
}
|
|
const resp = await context.next();
|
|
if (resp) {
|
|
if (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,
|
|
];
|