Skip to content

Usenet streaming with a WebDAV server and a SABnzbd-compatible API

C#

Refactor frontend/backend auth flows. Allow disabling auth through env variables (#65)

nzbdav-devbeafd4485692
diff --git a/backend/Auth/ServiceCollectionAuthExtensions.cs b/backend/Auth/ServiceCollectionAuthExtensions.cs
new file mode 100644
index 00000000..7a05c29a
--- /dev/null
+++ b/backend/Auth/ServiceCollectionAuthExtensions.cs
@@ -0,0 +1,70 @@
+using System.Security.Claims;
+using Microsoft.AspNetCore.DataProtection;
+using Microsoft.Extensions.DependencyInjection;
+using NWebDav.Server;
+using NWebDav.Server.Authentication;
+using NzbWebDAV.Config;
+using NzbWebDAV.Database;
+using NzbWebDAV.Utils;
+
+namespace NzbWebDAV.Auth;
+
+public static class ServiceCollectionAuthExtensions
+{
+ public static IServiceCollection AddWebdavBasicAuthentication
+ (
+ this IServiceCollection services,
+ ConfigManager configManager
+ )
+ {
+ // no-op when webdav auth is disabled
+ if (WebApplicationAuthExtensions.IsWebdavAuthDisabled())
+ return services;
+
+ // otherwise configure basic auth
+ services
+ .AddDataProtection()
+ .PersistKeysToFileSystem(new DirectoryInfo(Path.Join(DavDatabaseContext.ConfigPath, "data-protection")));
+ services
+ .AddAuthentication(opts => opts.DefaultScheme = BasicAuthenticationDefaults.AuthenticationScheme)
+ .AddBasicAuthentication(opts =>
+ {
+ opts.AllowInsecureProtocol = true;
+ opts.CacheCookieName = "nzb-webdav-backend";
+ opts.CacheCookieExpiration = TimeSpan.FromHours(1);
+ opts.Events.OnValidateCredentials = (ValidateCredentialsContext context) =>
+ ValidateCredentials(context, configManager);
+ });
+
+ return services;
+ }
+
+ private static Task ValidateCredentials(ValidateCredentialsContext context, ConfigManager configManager)
+ {
+ var user = configManager.GetWebdavUser();
+ var passwordHash = configManager.GetWebdavPasswordHash();
+
+ if (user == null || passwordHash == null)
+ context.Fail("webdav user and password are not yet configured.");
+
+ if (context.Username == user && PasswordUtil.Verify(passwordHash!, context.Password))
+ {
+ var claims = new[]
+ {
+ new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String,
+ context.Options.ClaimsIssuer),
+ new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String,
+ context.Options.ClaimsIssuer)
+ };
+
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
+ context.Success();
+ }
+ else
+ {
+ context.Fail("invalid credentials");
+ }
+
+ return Task.CompletedTask;
+ }
+}
\ No newline at end of file
diff --git a/backend/Auth/WebApplicationAuthExtensions.cs b/backend/Auth/WebApplicationAuthExtensions.cs
new file mode 100644
index 00000000..257fe270
--- /dev/null
+++ b/backend/Auth/WebApplicationAuthExtensions.cs
@@ -0,0 +1,28 @@
+using Microsoft.AspNetCore.Builder;
+using NzbWebDAV.Utils;
+using Serilog;
+
+namespace NzbWebDAV.Auth;
+
+public static class WebApplicationAuthExtensions
+{
+ private const string DisableWebdavAuthEnvVar = "DISABLE_WEBDAV_AUTH";
+
+ private const string DisabledWebdavAuthLog =
+ "WebDAV authentication is DISABLED via the DISABLE_WEBDAV_AUTH environment variable";
+
+ private static readonly Action<Action> LogOnlyOnce = DebounceUtil.RunOnlyOnce();
+
+ public static bool IsWebdavAuthDisabled()
+ {
+ var isWebdavAuthDisabled = EnvironmentUtil.IsVariableTrue(DisableWebdavAuthEnvVar);
+ if (isWebdavAuthDisabled) LogOnlyOnce(() => Log.Information(DisabledWebdavAuthLog));
+ return isWebdavAuthDisabled;
+ }
+
+ public static void UseWebdavBasicAuthentication(this WebApplication app)
+ {
+ if (IsWebdavAuthDisabled()) return;
+ app.UseAuthentication();
+ }
+}
\ No newline at end of file
diff --git a/backend/Program.cs b/backend/Program.cs
index 3996cf9f..8904bc47 100644
--- a/backend/Program.cs
+++ b/backend/Program.cs
@@ -1,13 +1,11 @@
-using System.Security.Claims;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.DataProtection;
+using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using NWebDav.Server;
-using NWebDav.Server.Authentication;
using NWebDav.Server.Stores;
using NzbWebDAV.Api.SabControllers;
+using NzbWebDAV.Auth;
using NzbWebDAV.Clients.Usenet;
using NzbWebDAV.Config;
using NzbWebDAV.Database;
@@ -49,13 +47,6 @@ class Program
.WriteTo.Console(theme: AnsiConsoleTheme.Code)
.CreateLogger();
- // Check if WebDAV auth should be disabled
- var webdavAuthDisabled = Environment.GetEnvironmentVariable("DISABLE_WEBDAV_AUTH")?.ToLower() == "true";
- if (webdavAuthDisabled)
- {
- Log.Information("WebDAV authentication is DISABLED via DISABLE_WEBDAV_AUTH environment variable");
- }
-
// initialize database
await using var databaseContext = new DavDatabaseContext();
@@ -83,6 +74,7 @@ class Program
builder.Services.AddControllers();
builder.Services.AddHealthChecks();
builder.Services
+ .AddWebdavBasicAuthentication(configManager)
.AddSingleton(configManager)
.AddSingleton(websocketManager)
.AddSingleton<UsenetStreamingClient>()
@@ -100,26 +92,10 @@ class Program
opts.Handlers["GET"] = typeof(GetAndHeadHandlerPatch);
opts.Handlers["HEAD"] = typeof(GetAndHeadHandlerPatch);
opts.Filter = opts.GetFilter();
- opts.RequireAuthentication = !webdavAuthDisabled;
+ opts.RequireAuthentication = !WebApplicationAuthExtensions
+ .IsWebdavAuthDisabled();
});
- // add basic auth (only if not disabled)
- if (!webdavAuthDisabled)
- {
- builder.Services
- .AddDataProtection()
- .PersistKeysToFileSystem(new DirectoryInfo(Path.Join(DavDatabaseContext.ConfigPath, "data-protection")));
- builder.Services
- .AddAuthentication(opts => opts.DefaultScheme = BasicAuthenticationDefaults.AuthenticationScheme)
- .AddBasicAuthentication(opts =>
- {
- opts.AllowInsecureProtocol = true;
- opts.CacheCookieName = "nzb-webdav-backend";
- opts.CacheCookieExpiration = TimeSpan.FromHours(1);
- opts.Events.OnValidateCredentials = (context) => ValidateCredentials(context, configManager);
- });
- }
-
// force instantiation of services
var app = builder.Build();
app.Services.GetRequiredService<ArrMonitoringService>();
@@ -131,44 +107,9 @@ class Program
app.MapHealthChecks("/health");
app.Map("/ws", websocketManager.HandleRoute);
app.MapControllers();
-
- // Only use authentication if not disabled
- if (!webdavAuthDisabled)
- {
- app.UseAuthentication();
- }
-
+ app.UseWebdavBasicAuthentication();
app.UseNWebDav();
app.Lifetime.ApplicationStopping.Register(SigtermUtil.Cancel);
await app.RunAsync();
}
-
- private static Task ValidateCredentials(ValidateCredentialsContext context, ConfigManager configManager)
- {
- var user = configManager.GetWebdavUser();
- var passwordHash = configManager.GetWebdavPasswordHash();
-
- if (user == null || passwordHash == null)
- context.Fail("webdav user and password are not yet configured.");
-
- if (context.Username == user && PasswordUtil.Verify(passwordHash!, context.Password))
- {
- var claims = new[]
- {
- new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String,
- context.Options.ClaimsIssuer),
- new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String,
- context.Options.ClaimsIssuer)
- };
-
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
- context.Success();
- }
- else
- {
- context.Fail("invalid credentials");
- }
-
- return Task.CompletedTask;
- }
}
\ No newline at end of file
diff --git a/backend/Queue/PostProcessors/RenameDuplicatesPostProcessor.cs b/backend/Queue/PostProcessors/RenameDuplicatesPostProcessor.cs
index 1451e137..3bfd382d 100644
--- a/backend/Queue/PostProcessors/RenameDuplicatesPostProcessor.cs
+++ b/backend/Queue/PostProcessors/RenameDuplicatesPostProcessor.cs
@@ -1,8 +1,6 @@
using Microsoft.EntityFrameworkCore;
-using NzbWebDAV.Config;
using NzbWebDAV.Database;
using NzbWebDAV.Database.Models;
-using Serilog;
namespace NzbWebDAV.Queue.PostProcessors;
diff --git a/backend/Queue/QueueItemProcessor.cs b/backend/Queue/QueueItemProcessor.cs
index 60961f81..524fbfd2 100644
--- a/backend/Queue/QueueItemProcessor.cs
+++ b/backend/Queue/QueueItemProcessor.cs
@@ -7,7 +7,6 @@ using NzbWebDAV.Clients.Usenet.Connections;
using NzbWebDAV.Config;
using NzbWebDAV.Database;
using NzbWebDAV.Database.Models;
-using NzbWebDAV.Exceptions;
using NzbWebDAV.Extensions;
using NzbWebDAV.Queue.DeobfuscationSteps._1.FetchFirstSegment;
using NzbWebDAV.Queue.DeobfuscationSteps._2.GetPar2FileDescriptors;
diff --git a/backend/Utils/DebounceUtil.cs b/backend/Utils/DebounceUtil.cs
index f7d75ebb..43552930 100644
--- a/backend/Utils/DebounceUtil.cs
+++ b/backend/Utils/DebounceUtil.cs
@@ -1,6 +1,6 @@
namespace NzbWebDAV.Utils;
-public class DebounceUtil
+public static class DebounceUtil
{
public static Action<Action> CreateDebounce(TimeSpan timespan)
{
@@ -28,4 +28,15 @@ public class DebounceUtil
actionToMaybeInvoke?.Invoke();
};
}
+
+ public static Action<Action> RunOnlyOnce()
+ {
+ var isAlreadyRan = false;
+ return actionToMaybeInvoke =>
+ {
+ if (isAlreadyRan) return;
+ isAlreadyRan = true;
+ actionToMaybeInvoke?.Invoke();
+ };
+ }
}
\ No newline at end of file
diff --git a/backend/Utils/EnvironmentUtil.cs b/backend/Utils/EnvironmentUtil.cs
index 4b4ef712..4aee2032 100644
--- a/backend/Utils/EnvironmentUtil.cs
+++ b/backend/Utils/EnvironmentUtil.cs
@@ -12,4 +12,10 @@ public static class EnvironmentUtil
{
return long.TryParse(Environment.GetEnvironmentVariable(envVariable), out var longValue) ? longValue : null;
}
+
+ public static bool IsVariableTrue(string envVariable)
+ {
+ var value = Environment.GetEnvironmentVariable(envVariable)?.ToLower();
+ return value is "y" or "yes" or "true";
+ }
}
\ No newline at end of file
diff --git a/frontend/app/auth/authentication.server.ts b/frontend/app/auth/authentication.server.ts
index d1e62e5a..c451284a 100644
--- a/frontend/app/auth/authentication.server.ts
+++ b/frontend/app/auth/authentication.server.ts
@@ -1,18 +1,16 @@
import { createCookieSessionStorage } from "react-router";
import crypto from "crypto"
import { backendClient } from "~/clients/backend-client.server";
+import type { IncomingMessage } from "http";
+
+export const IS_FRONTEND_AUTH_DISABLED = process.env.DISABLE_FRONTEND_AUTH === 'true';
type User = {
username: string;
};
-// Add auth bypass configuration
-const AUTH_DISABLED = process.env.DISABLE_FRONTEND_AUTH === 'true';
-const BYPASS_USERNAME = process.env.BYPASS_USERNAME || 'admin';
-
const oneYear = 60 * 60 * 24 * 365; // seconds
-
-export const sessionStorage = createCookieSessionStorage({
+const sessionStorage = createCookieSessionStorage({
cookie: {
name: "__session",
httpOnly: true,
@@ -24,12 +22,40 @@ export const sessionStorage = createCookieSessionStorage({
},
});
-export async function authenticate(request: Request): Promise<User> {
- // If auth is disabled, return a default user without checking credentials
- if (AUTH_DISABLED) {
- return { username: BYPASS_USERNAME };
- }
+export async function isAuthenticated(request: Request | IncomingMessage): Promise<boolean> {
+ // If auth is disabled, always return true
+ if (IS_FRONTEND_AUTH_DISABLED) return true;
+
+ // Otherwise, check session storage
+ const cookieHeader = request instanceof Request
+ ? request.headers.get("cookie")
+ : request.headers.cookie;
+ if (!cookieHeader) return false;
+ const session = await sessionStorage.getSession(cookieHeader);
+ const user = session.get("user");
+ return !!user;
+}
+
+export async function login(request: Request): Promise<ResponseInit> {
+ let user = await authenticate(request);
+ let session = await sessionStorage.getSession(request.headers.get("cookie"));
+ session.set("user", user);
+ return { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } };
+}
+export async function logout(request: Request): Promise<ResponseInit> {
+ let session = await sessionStorage.getSession(request.headers.get("cookie"));
+ session.unset("user");
+ return { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } };
+}
+
+export async function setSessionUser(request: Request, username: string): Promise<ResponseInit> {
+ let session = await sessionStorage.getSession(request.headers.get("cookie"));
+ session.set("user", { username: username })
+ return { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } };
+}
+
+async function authenticate(request: Request): Promise<User> {
const formData = await request.formData();
const username = formData.get("username")?.toString();
const password = formData.get("password")?.toString();
@@ -37,14 +63,3 @@ export async function authenticate(request: Request): Promise<User> {
if (await backendClient.authenticate(username, password)) return { username: username };
throw new Error("Invalid credentials");
}
-
-export async function isAuthenticated(cookieHeader: string | null | undefined): Promise<boolean> {
- // If auth is disabled, always return true
- if (AUTH_DISABLED) {
- return true;
- }
-
- const session = await sessionStorage.getSession(cookieHeader);
- const user = session.get("user");
- return !!user;
-}
\ No newline at end of file
diff --git a/frontend/app/root.tsx b/frontend/app/root.tsx
index 1cf68bcb..335380c0 100644
--- a/frontend/app/root.tsx
+++ b/frontend/app/root.tsx
@@ -12,7 +12,7 @@ import {
import 'bootstrap/dist/css/bootstrap.min.css';
import "./app.css";
import type { Route } from "./+types/root";
-import { sessionStorage } from "~/auth/authentication.server";
+import { IS_FRONTEND_AUTH_DISABLED, isAuthenticated } from "~/auth/authentication.server";
import { TopNavigation } from "./routes/_index/components/top-navigation/top-navigation";
import { LeftNavigation } from "./routes/_index/components/left-navigation/left-navigation";
import { PageLayout } from "./routes/_index/components/page-layout/page-layout";
@@ -24,24 +24,12 @@ export async function loader({ request }: Route.LoaderArgs) {
if (path === "/login") return { useLayout: false };
if (path === "/onboarding") return { useLayout: false };
- // Check if auth is disabled via env var
- const frontendAuthDisabled = process.env.DISABLE_FRONTEND_AUTH === 'true';
-
- if (frontendAuthDisabled) {
- // Skip authentication check when disabled
- return {
- useLayout: true,
- version: process.env.NZBDAV_VERSION
- };
- }
-
// ensure all other routes are authenticated
- let session = await sessionStorage.getSession(request.headers.get("cookie"));
- let user = session.get("user");
- if (!user) return redirect("/login");
+ if (!await isAuthenticated(request)) return redirect("/login");
return {
useLayout: true,
- version: process.env.NZBDAV_VERSION
+ version: process.env.NZBDAV_VERSION,
+ isFrontendAuthDisabled: IS_FRONTEND_AUTH_DISABLED,
};
}
@@ -66,7 +54,7 @@ export function Layout({ children }: { children: React.ReactNode }) {
}
export default function App({ loaderData }: Route.ComponentProps) {
- const { useLayout, version } = loaderData;
+ const { useLayout, version, isFrontendAuthDisabled } = loaderData;
const location = useLocation();
const navigation = useNavigation();
const isNavigating = Boolean(navigation.location);
@@ -82,7 +70,11 @@ export default function App({ loaderData }: Route.ComponentProps) {
<PageLayout
topNavComponent={TopNavigation}
bodyChild={showLoading ? <Loading /> : <Outlet />}
- leftNavChild={<LeftNavigation version={version} />} />
+ leftNavChild={
+ <LeftNavigation
+ version={version}
+ isFrontendAuthDisabled={isFrontendAuthDisabled} />
+ } />
);
}
diff --git a/frontend/app/routes/_index/components/left-navigation/left-navigation.tsx b/frontend/app/routes/_index/components/left-navigation/left-navigation.tsx
index d15eb408..9f270f7b 100644
--- a/frontend/app/routes/_index/components/left-navigation/left-navigation.tsx
+++ b/frontend/app/routes/_index/components/left-navigation/left-navigation.tsx
@@ -5,12 +5,11 @@ import type React from "react";
import { LiveUsenetConnections } from "../live-usenet-connections/live-usenet-connections";
export type LeftNavigationProps = {
- version?: string
+ version?: string,
+ isFrontendAuthDisabled?: boolean,
}
-export function LeftNavigation({ version }: LeftNavigationProps) {
- const frontendAuthDisabled = process.env.DISABLE_FRONTEND_AUTH === 'true';
-
+export function LeftNavigation({ version, isFrontendAuthDisabled }: LeftNavigationProps) {
return (
<div className={styles.container}>
<Item target="/queue">
@@ -44,8 +43,8 @@ export function LeftNavigation({ version }: LeftNavigationProps) {
<div className={styles["footer-item"]}>
version: {version || 'unknown'}
</div>
- <hr />
- {!frontendAuthDisabled && (
+ {!isFrontendAuthDisabled && <>
+ <hr />
<Form method="post" action="/logout">
<input name="confirm" value="true" type="hidden" />
<button className={styles.unstyled + ' ' + styles.item} type="submit">
@@ -53,7 +52,7 @@ export function LeftNavigation({ version }: LeftNavigationProps) {
<div className={styles.title}>Logout</div>
</button>
</Form>
- )}
+ </>}
</div>
</div>
);
diff --git a/frontend/app/routes/login/route.tsx b/frontend/app/routes/login/route.tsx
index 5e6131a9..360e9b3f 100644
--- a/frontend/app/routes/login/route.tsx
+++ b/frontend/app/routes/login/route.tsx
@@ -1,7 +1,7 @@
import { Alert, Button, Form as BootstrapForm } from "react-bootstrap";
import styles from "./route.module.css"
import type { Route } from "./+types/route";
-import { authenticate, sessionStorage } from "~/auth/authentication.server";
+import { isAuthenticated, login } from "~/auth/authentication.server";
import { Form, redirect, useNavigation } from "react-router";
import { backendClient } from "~/clients/backend-client.server";
@@ -10,14 +10,8 @@ type LoginPageData = {
}
export async function loader({ request }: Route.LoaderArgs) {
- // If auth is disabled, redirect directly to main app
- if (process.env.DISABLE_FRONTEND_AUTH === 'true') {
- return redirect("/");
- }
// if already logged in, redirect to landing page
- let session = await sessionStorage.getSession(request.headers.get("cookie"));
- let user = session.get("user");
- if (user) return redirect("/");
+ if (await isAuthenticated(request)) return redirect("/");
// if we need to go through onboarding, redirect to onboarding page
const isOnboarding = await backendClient.isOnboarding();
@@ -49,10 +43,8 @@ export default function Index({ loaderData, actionData }: Route.ComponentProps)
export async function action({ request }: Route.ActionArgs) {
try {
- let user = await authenticate(request);
- let session = await sessionStorage.getSession(request.headers.get("cookie"));
- session.set("user", user);
- return redirect("/", { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } });
+ var responseInit = await login(request);
+ return redirect("/", responseInit);
}
catch (error) {
if (error instanceof Error) {
diff --git a/frontend/app/routes/logout/route.tsx b/frontend/app/routes/logout/route.tsx
index 33bc7ce4..031f2059 100644
--- a/frontend/app/routes/logout/route.tsx
+++ b/frontend/app/routes/logout/route.tsx
@@ -1,17 +1,10 @@
import type { Route } from "./+types/route";
-import { sessionStorage } from "~/auth/authentication.server";
+import { isAuthenticated, logout } from "~/auth/authentication.server";
import { redirect } from "react-router";
export async function action({ request }: Route.ActionArgs) {
- // If auth is disabled, just redirect to home
- if (process.env.DISABLE_FRONTEND_AUTH === 'true') {
- return redirect("/");
- }
-
// if already logged out, redirect to login page
- let session = await sessionStorage.getSession(request.headers.get("cookie"));
- let user = session.get("user");
- if (!user) return redirect("/login");
+ if (!await isAuthenticated(request)) return redirect("/login");
// if we logout intent is not confirmed, redirect to landing page
const formData = await request.formData();
@@ -19,6 +12,6 @@ export async function action({ request }: Route.ActionArgs) {
if (confirm !== "true") return redirect("/");
// otherwise, proceed to log out!
- session.unset("user");
- return redirect("/login", { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } });
+ const responseInit = await logout(request);
+ return redirect("/login", responseInit);
}
\ No newline at end of file
diff --git a/frontend/app/routes/onboarding/route.tsx b/frontend/app/routes/onboarding/route.tsx
index 1adbdc05..bcb89344 100644
--- a/frontend/app/routes/onboarding/route.tsx
+++ b/frontend/app/routes/onboarding/route.tsx
@@ -4,22 +4,15 @@ import type { Route } from "./+types/route";
import { useState } from "react";
import { backendClient } from "~/clients/backend-client.server";
import { Form, redirect, useNavigation } from "react-router";
-import { sessionStorage } from "~/auth/authentication.server";
+import { isAuthenticated, setSessionUser } from "~/auth/authentication.server";
type OnboardingPageData = {
error: string
}
export async function loader({ request }: Route.LoaderArgs) {
- // If auth is disabled, redirect to main app (no onboarding needed)
- if (process.env.DISABLE_FRONTEND_AUTH === 'true') {
- return redirect("/");
- }
-
// if already logged in, redirect to landing page
- let session = await sessionStorage.getSession(request.headers.get("cookie"));
- let user = session.get("user");
- if (user) return redirect("/");
+ if (await isAuthenticated(request)) return redirect("/")
// if we don't need to go through onboarding, redirect to login page
const isOnboarding = await backendClient.isOnboarding();
@@ -101,10 +94,8 @@ export default function Index({ loaderData, actionData }: Route.ComponentProps)
export async function action({ request }: Route.ActionArgs) {
try {
- // If auth is disabled, redirect to main app
- if (process.env.DISABLE_FRONTEND_AUTH === 'true') {
- return redirect("/");
- }
+ // if already logged in, redirect to landing page
+ if (await isAuthenticated(request)) return redirect("/")
// if we don't need to go through onboarding, redirect to login page
const isOnboarding = await backendClient.isOnboarding();
@@ -117,9 +108,8 @@ export async function action({ request }: Route.ActionArgs) {
if (!username || !password) throw new Error("username and password required");
var isSuccess = await backendClient.createAccount(username, password);
if (!isSuccess) throw new Error("Unknown error creating account");
- let session = await sessionStorage.getSession(request.headers.get("cookie"));
- session.set("user", { username: username });
- return redirect("/", { headers: { "Set-Cookie": await sessionStorage.commitSession(session) } });
+ var responseInit = await setSessionUser(request, username);
+ return redirect("/", responseInit);
}
catch (error) {
if (error instanceof Error) {
diff --git a/frontend/app/routes/queue/route.tsx b/frontend/app/routes/queue/route.tsx
index 95f61311..b4c0e795 100644
--- a/frontend/app/routes/queue/route.tsx
+++ b/frontend/app/routes/queue/route.tsx
@@ -1,6 +1,5 @@
import { Link, redirect } from "react-router";
import type { Route } from "./+types/route";
-import { sessionStorage } from "~/auth/authentication.server";
import styles from "./route.module.css"
import { Alert } from 'react-bootstrap';
import { backendClient, type HistorySlot, type QueueSlot } from "~/clients/backend-client.server";
@@ -9,6 +8,7 @@ import { HistoryTable } from "./components/history-table/history-table";
import { QueueTable } from "./components/queue-table/queue-table";
import { useCallback, useEffect, useState } from "react";
import { receiveMessage } from "~/utils/websocket-util";
+import { isAuthenticated } from "~/auth/authentication.server";
const topicNames = {
queueItemStatus: 'qs',
@@ -189,15 +189,8 @@ export default function Queue(props: Route.ComponentProps) {
}
export async function action({ request }: Route.ActionArgs) {
- // Check if auth is disabled
- const authDisabled = process.env.DISABLE_FRONTEND_AUTH === 'true';
-
- if (!authDisabled) {
- // ensure user is logged in (only if auth is enabled)
- let session = await sessionStorage.getSession(request.headers.get("cookie"));
- let user = session.get("user");
- if (!user) return redirect("/login");
- }
+ // ensure user is logged in
+ if (!await isAuthenticated(request)) return redirect("/login");
try {
const formData = await request.formData();
diff --git a/frontend/app/routes/settings.update/route.tsx b/frontend/app/routes/settings.update/route.tsx
index df64c257..f1dc8620 100644
--- a/frontend/app/routes/settings.update/route.tsx
+++ b/frontend/app/routes/settings.update/route.tsx
@@ -1,13 +1,11 @@
import type { Route } from "./+types/route";
import { backendClient, type ConfigItem } from "~/clients/backend-client.server";
import { redirect } from "react-router";
-import { sessionStorage } from "~/auth/authentication.server";
+import { isAuthenticated } from "~/auth/authentication.server";
export async function action({ request }: Route.ActionArgs) {
// ensure user is logged in
- let session = await sessionStorage.getSession(request.headers.get("cookie"));
- let user = session.get("user");
- if (!user) return redirect("/login");
+ if (!await isAuthenticated(request)) return redirect("/login");
// get the ConfigItems to update
const formData = await request.formData();
diff --git a/frontend/server/app.ts b/frontend/server/app.ts
index bac12755..86d93c7e 100644
--- a/frontend/server/app.ts
+++ b/frontend/server/app.ts
@@ -30,7 +30,7 @@ const setApiKeyForAuthenticatedRequests = async (req: express.Request) => {
if (hasApiKey) return;
// if the request is not authenticated, do nothing
- const authenticated = await isAuthenticated(req.headers.cookie);
+ const authenticated = await isAuthenticated(req);
if (!authenticated) return;
// otherwise, set the api key header
diff --git a/frontend/server/websocket.server.ts b/frontend/server/websocket.server.ts
index c5086aed..12234cdb 100644
--- a/frontend/server/websocket.server.ts
+++ b/frontend/server/websocket.server.ts
@@ -1,5 +1,5 @@
import WebSocket, { WebSocketServer } from 'ws';
-import { sessionStorage } from "../app/auth/authentication.server";
+import { isAuthenticated } from "../app/auth/authentication.server";
import type { IncomingMessage } from 'http';
function initializeWebsocketServer(wss: WebSocketServer) {
@@ -11,53 +11,46 @@ function initializeWebsocketServer(wss: WebSocketServer) {
// authenticate new websocket sessions
wss.on("connection", async (ws: WebSocket, request: IncomingMessage) => {
- const cookieHeader = request.headers.cookie;
- if (cookieHeader) {
- try {
- const session = await sessionStorage.getSession(cookieHeader);
- const user = session.get("user");
- if (!user) {
- ws.close(1008, "Unauthorized");
- return;
- }
+ try {
+ // ensure user is logged in
+ if (!await isAuthenticated(request)) {
+ ws.close(1008, "Unauthorized");
+ return;
+ }
- // handle topic subscription
- ws.onmessage = (event: WebSocket.MessageEvent) => {
- try {
- var topics = JSON.parse(event.data.toString());
- websockets.set(ws, topics);
- for (const topic in topics) {
- var topicSubscriptions = subscriptions.get(topic);
- if (topicSubscriptions) topicSubscriptions.add(ws);
- else subscriptions.set(topic, new Set<WebSocket>([ws]));
- if (topics[topic] === 'state') {
- var messageToSend = lastMessage.get(topic);
- if (messageToSend) ws.send(messageToSend);
- }
+ // handle topic subscription
+ ws.onmessage = (event: WebSocket.MessageEvent) => {
+ try {
+ var topics = JSON.parse(event.data.toString());
+ websockets.set(ws, topics);
+ for (const topic in topics) {
+ var topicSubscriptions = subscriptions.get(topic);
+ if (topicSubscriptions) topicSubscriptions.add(ws);
+ else subscriptions.set(topic, new Set<WebSocket>([ws]));
+ if (topics[topic] === 'state') {
+ var messageToSend = lastMessage.get(topic);
+ if (messageToSend) ws.send(messageToSend);
}
- } catch {
- ws.close(1003, "Could not process topic subscription. If recently updated, try refreshing the page.");
}
- };
-
- // unsubscribe from topics
- ws.onclose = () => {
- var topics = websockets.get(ws);
- if (topics) {
- websockets.delete(ws);
- for (const topic in topics) {
- var topicSubscriptions = subscriptions.get(topic);
- if (topicSubscriptions) topicSubscriptions.delete(ws);
- }
+ } catch {
+ ws.close(1003, "Could not process topic subscription. If recently updated, try refreshing the page.");
+ }
+ };
+
+ // unsubscribe from topics
+ ws.onclose = () => {
+ var topics = websockets.get(ws);
+ if (topics) {
+ websockets.delete(ws);
+ for (const topic in topics) {
+ var topicSubscriptions = subscriptions.get(topic);
+ if (topicSubscriptions) topicSubscriptions.delete(ws);
}
- };
- } catch (error) {
- console.error("Error authenticating websocket session:", error);
- ws.close(1011, "Internal server error");
- return;
- }
- } else {
- ws.close(1008, "Unauthorized");
+ }
+ };
+ } catch (error) {
+ console.error("Error authenticating websocket session:", error);
+ ws.close(1011, "Internal server error");
return;
}
});