Usenet streaming with a WebDAV server and a SABnzbd-compatible API
C#
Allow authenticated frontend api requests.
nzbdav-dev48dbce4de1da
diff --git a/frontend/app/auth/authentication.server.ts b/frontend/app/auth/authentication.server.tsindex e082a476..1395a571 100644--- a/frontend/app/auth/authentication.server.ts+++ b/frontend/app/auth/authentication.server.ts@@ -24,4 +24,10 @@ export async function authenticate(request: Request): Promise<User> {if (!username || !password) throw new Error("username and password required");if (await backendClient.authenticate(username, password)) return { username: username };throw new Error("Invalid credentials");+}++export async function isAuthenticated(cookieHeader: string | null | undefined): Promise<boolean> {+ const session = await sessionStorage.getSession(cookieHeader);+ const user = session.get("user");+ return !!user;}\ No newline at end of filediff --git a/frontend/server/app.ts b/frontend/server/app.tsindex 6110b656..bac12755 100644--- a/frontend/server/app.ts+++ b/frontend/server/app.ts@@ -3,6 +3,7 @@ import { createRequestHandler } from "@react-router/express";import express from "express";import { createProxyMiddleware } from "http-proxy-middleware";import { websocketServer } from "./websocket.server";+import { isAuthenticated } from "~/auth/authentication.server";declare module "react-router" {interface AppLoadContext {@@ -19,7 +20,24 @@ const forwardToBackend = createProxyMiddleware({changeOrigin: true,});-app.use((req, res, next) => {+const setApiKeyForAuthenticatedRequests = async (req: express.Request) => {+ // if the path is not /api, do nothing+ if (!req.path.startsWith("/api")) return;+ var apikey = req.query.apikey || req.query.apiKey || req.headers["x-api-key"];+ var hasApiKey = apikey && typeof apikey === "string";++ // if the request already has an apikey, do nothing+ if (hasApiKey) return;++ // if the request is not authenticated, do nothing+ const authenticated = await isAuthenticated(req.headers.cookie);+ if (!authenticated) return;++ // otherwise, set the api key header+ req.headers["x-api-key"] = process.env.FRONTEND_BACKEND_API_KEY || "";+}++app.use(async (req, res, next) => {if (req.method.toUpperCase() === "PROPFIND"|| req.method.toUpperCase() === "OPTIONS"@@ -30,6 +48,7 @@ app.use((req, res, next) => {|| req.path.startsWith("/content")|| req.path.startsWith("/completed-symlinks")) {+ await setApiKeyForAuthenticatedRequests(req);return forwardToBackend(req, res, next);}next();