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-11 17:12:32 -05:00
|
|
|
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;
|
|
|
|
}
|
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-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
|
|
|
|
|
|
|
export const handler = [
|
|
|
|
currentUser,
|
|
|
|
serverHeader,
|
|
|
|
];
|