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-09-27 14:41:17 -05:00
|
|
|
|
|
|
|
interface State {
|
|
|
|
data: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function handler(
|
2022-10-08 02:01:48 -05:00
|
|
|
request: Request,
|
2022-09-27 14:41:17 -05:00
|
|
|
ctx: MiddlewareHandlerContext<State>,
|
|
|
|
) {
|
2022-10-08 02:01:48 -05:00
|
|
|
ctx.state.data = "";
|
|
|
|
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 {ctx.state.data += "user:" + JSON.stringify({
|
|
|
|
id: user.id,
|
|
|
|
username: user.username,
|
|
|
|
displayName: user.displayName || user.username,
|
|
|
|
}) +
|
|
|
|
"\n";}
|
|
|
|
}
|
|
|
|
|
2022-09-27 14:41:17 -05:00
|
|
|
const resp = await ctx.next();
|
2022-10-08 02:01:48 -05:00
|
|
|
if (resp) {
|
|
|
|
resp.headers.set("server", "fresh server");
|
|
|
|
if (hasBadAuthCookie) deleteCookie(resp.headers, "lsauth");
|
|
|
|
}
|
2022-09-27 14:41:17 -05:00
|
|
|
return resp;
|
|
|
|
}
|