From: Alec Armbruster <35377827+alectrocute@users.noreply.github.com> Date: Fri, 30 Jun 2023 13:42:09 +0000 (-0400) Subject: fix cache auth method X-Git-Url: http://these/git/readmes/%24%7B%60data:application/%7B%60%24%7BghostArchiveUrl%7D/static/git-logo.png?a=commitdiff_plain;h=da45ffb46b3cabc6513535b8d44cafe59add6068;p=lemmy-ui.git fix cache auth method --- diff --git a/src/server/middleware.ts b/src/server/middleware.ts index 235f072..7505d65 100644 --- a/src/server/middleware.ts +++ b/src/server/middleware.ts @@ -1,5 +1,5 @@ import type { NextFunction, Request, Response } from "express"; -import { UserService } from "../shared/services"; +import { isRequestAuthenticated } from "./utils/is-request-authenticated"; export function setDefaultCsp({ res, @@ -22,23 +22,30 @@ export function setDefaultCsp({ // interval is rather arbitrary and could be set higher (less server load) or lower (fresher data). // // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control -export function setCacheControl( - req: Request, - res: Response, - next: NextFunction -) { - const user = UserService.Instance; +export function setCacheControl({ + res, + req, + next, +}: { + res: Response; + req: Request; + next: NextFunction; +}) { let caching: string; + // Avoid any sort of caching in development + if (process.env.NODE_ENV !== "production") { + return next(); + } + if ( - process.env.NODE_ENV === "production" && - (req.path.match(/\.(js|css|txt|manifest\.webmanifest)\/?$/) || - req.path.includes("/css/themelist")) + req.path.match(/\.(js|css|txt|manifest\.webmanifest)\/?$/) || + req.path.includes("/css/themelist") ) { // Static content gets cached publicly for a day caching = "public, max-age=86400"; } else { - if (user.auth()) { + if (isRequestAuthenticated(req)) { caching = "private"; } else { caching = "public, max-age=5"; diff --git a/src/server/utils/is-request-authenticated.ts b/src/server/utils/is-request-authenticated.ts new file mode 100644 index 0000000..7b9fb22 --- /dev/null +++ b/src/server/utils/is-request-authenticated.ts @@ -0,0 +1,9 @@ +import type { Request } from "express"; + +export function isRequestAuthenticated(req: Request): boolean { + if (!req.headers.cookie) { + return false; + } + + return req.headers.cookie?.split("; ").some(c => c.startsWith("jwt")); +}