mirror of
https://github.com/arsvendg/Stirling-PDF.git
synced 2026-07-15 19:10:47 +02:00
fix file sharing bug (#6161)
# Description of Changes Fixes share-link navigation for SSO users. Reported on v2.9.2 with `SSOAutoLogin: true`: clicking a `/share/<token>` link in an email redirected the user to the home page after SSO instead of the shared file. ## Root cause Three compounding issues had to be fixed together; the first was the initial symptom but the other two only surfaced during live verification. 1. **Spring Security blocked `/share/<token>` for unauthenticated users.** The route wasn't in `RequestUriUtils.isPublicAuthEndpoint`, so the server 302'd straight to `/login` before React could load `ShareLinkPage`. The share URL was lost because `NullRequestCache` is configured and never persisted the original destination. 2. **`httpErrorHandler` full-page-redirected to `/login?from=<path>` on any unhandled 401** (fired by `LicenseContext`, `AppConfig`, etc. during normal ShareLinkPage mount). That *did* preserve the return path — but **Spring Security strips query strings from `/login`** (302 to bare `/login`), so `?from=` never reached React. Confirmed via `curl -i http://localhost:8080/login?from=xyz` → `Location: /login`. 3. **`AuthCallback.tsx` unconditionally `navigate("/")`** after the SAML/OAuth round-trip, discarding any intended destination. ## Fix **Backend** — make `/share/<token>` a public SPA bootstrap, data APIs stay protected: - `RequestUriUtils.isPublicAuthEndpoint` — permits `^/share/[^/]+/?$` (tight regex, single token segment only; `/share/<token>/anything` stays protected). - `ReactRoutingController` — dedicated `@GetMapping("/share/{token}")` mirroring `/auth/callback`. - `/api/v1/storage/share-links/**` remains behind Spring Security with its existing `canAccessShareLink` check. **Frontend** — persist the return path across full-page redirects via `sessionStorage` (same-origin, survives the SSO round-trip): - `httpErrorHandler.ts` — stashes current pathname to `stirling_post_login_path` before the 401 → `/login` redirect. - `springAuthClient.ts` — new `isSafePostLoginRedirect` / `setPostLoginRedirectPath` / `consumePostLoginRedirectPath` helpers (rejects protocol-relative URLs and auth-plumbing paths to guard against open-redirect abuse). - `Login.tsx` — on explicit user sign-in, read path from `location.state` or `?from=` query and stash it; don't clobber an already-stashed value. - `AuthCallback.tsx` — consume the stashed path (single-use) and `navigate(target)` instead of always `/`. --- ## Checklist ### General - [ ] I have read the [Contribution Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md) - [ ] I have read the [Stirling-PDF Developer Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md) (if applicable) - [ ] I have read the [How to add new languages to Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md) (if applicable) - [ ] I have performed a self-review of my own code - [ ] My changes generate no new warnings ### Documentation - [ ] I have updated relevant docs on [Stirling-PDF's doc repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/) (if functionality has heavily changed) - [ ] I have read the section [Add New Translation Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags) (for new translation tags only) ### Translations (if applicable) - [ ] I ran [`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md) ### UI Changes (if applicable) - [ ] Screenshots or videos demonstrating the UI changes are attached (e.g., as comments or direct attachments in the PR) ### Testing (if applicable) - [ ] I have run `task check` to verify linters, typechecks, and tests pass - [ ] I have tested my changes locally. Refer to the [Testing Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing) for more details. --------- Co-authored-by: EthanHealy01 <[email protected]>
This commit is contained in:
co-authored by
EthanHealy01
parent
3e94157137
commit
c294e9b2cb
@@ -16,6 +16,35 @@ import {
|
||||
const recentSpecialByEndpoint: Record<string, number> = {};
|
||||
const SPECIAL_SUPPRESS_MS = 1500; // brief window to suppress generic duplicate after special toast
|
||||
|
||||
// Mirrors the key in proprietary/auth/springAuthClient.ts; AuthCallback consumes it.
|
||||
const POST_LOGIN_REDIRECT_STORAGE_KEY = "stirling_post_login_path";
|
||||
|
||||
function isSafePostLoginPath(path: string): boolean {
|
||||
if (
|
||||
!path.startsWith("/") ||
|
||||
path.startsWith("//") ||
|
||||
path.startsWith("/\\")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const lowered = path.toLowerCase();
|
||||
return (
|
||||
!lowered.startsWith("/login") &&
|
||||
!lowered.startsWith("/auth/") &&
|
||||
!lowered.startsWith("/oauth2") &&
|
||||
!lowered.startsWith("/saml2")
|
||||
);
|
||||
}
|
||||
|
||||
function stashPostLoginRedirect(path: string): void {
|
||||
try {
|
||||
if (typeof window === "undefined" || !isSafePostLoginPath(path)) return;
|
||||
window.sessionStorage.setItem(POST_LOGIN_REDIRECT_STORAGE_KEY, path);
|
||||
} catch {
|
||||
// sessionStorage unavailable (private mode) — fail open
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles HTTP errors with toast notifications and file error broadcasting
|
||||
* Returns true if the error should be suppressed (deduplicated), false otherwise
|
||||
@@ -42,9 +71,10 @@ export async function handleHttpError(error: any): Promise<boolean> {
|
||||
// If not on auth page, redirect to login with expired session message
|
||||
if (!isAuthPage && !skipAuthRedirect) {
|
||||
console.debug("[httpErrorHandler] 401 detected, redirecting to login");
|
||||
// Store the current location so we can redirect back after login
|
||||
// Spring 302-strips the ?from= query from /login, so stash the return
|
||||
// path in sessionStorage (AuthCallback reads it after SSO round-trip).
|
||||
const currentLocation = window.location.pathname + window.location.search;
|
||||
// Redirect to login with state (only show expired when a JWT existed)
|
||||
stashPostLoginRedirect(currentLocation);
|
||||
let hadStoredJwt = false;
|
||||
try {
|
||||
hadStoredJwt = Boolean(localStorage.getItem("stirling_jwt"));
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { describe, it, expect, beforeEach, vi, afterEach } from "vitest";
|
||||
import { springAuth } from "@app/auth/springAuthClient";
|
||||
import {
|
||||
consumePostLoginRedirectPath,
|
||||
isSafePostLoginRedirect,
|
||||
POST_LOGIN_REDIRECT_STORAGE_KEY,
|
||||
setPostLoginRedirectPath,
|
||||
springAuth,
|
||||
} from "@app/auth/springAuthClient";
|
||||
import { startOAuthNavigation } from "@app/extensions/oauthNavigation";
|
||||
import apiClient from "@app/services/apiClient";
|
||||
import {
|
||||
@@ -382,4 +388,95 @@ describe("SpringAuthClient", () => {
|
||||
expect(result.error).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("post-login redirect path", () => {
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
describe("isSafePostLoginRedirect", () => {
|
||||
it("accepts same-origin paths with a single leading slash", () => {
|
||||
expect(isSafePostLoginRedirect("/share/abc123")).toBe(true);
|
||||
expect(isSafePostLoginRedirect("/workbench")).toBe(true);
|
||||
expect(isSafePostLoginRedirect("/share/abc?x=1")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects empty, null, or non-string values", () => {
|
||||
expect(isSafePostLoginRedirect("")).toBe(false);
|
||||
expect(isSafePostLoginRedirect(null)).toBe(false);
|
||||
expect(isSafePostLoginRedirect(undefined)).toBe(false);
|
||||
expect(isSafePostLoginRedirect(42 as unknown)).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects protocol-relative and absolute URLs (open-redirect guard)", () => {
|
||||
expect(isSafePostLoginRedirect("//evil.example")).toBe(false);
|
||||
expect(isSafePostLoginRedirect("http://evil.example")).toBe(false);
|
||||
expect(isSafePostLoginRedirect("https://evil.example/x")).toBe(false);
|
||||
expect(isSafePostLoginRedirect("/\\evil")).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects auth-plumbing paths to avoid login loops", () => {
|
||||
expect(isSafePostLoginRedirect("/login")).toBe(false);
|
||||
expect(isSafePostLoginRedirect("/login?foo=1")).toBe(false);
|
||||
expect(isSafePostLoginRedirect("/auth/callback")).toBe(false);
|
||||
expect(isSafePostLoginRedirect("/oauth2/authorization/google")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isSafePostLoginRedirect("/saml2/authenticate/x")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setPostLoginRedirectPath", () => {
|
||||
it("stores a safe path in sessionStorage", () => {
|
||||
setPostLoginRedirectPath("/share/abc123");
|
||||
expect(sessionStorage.getItem(POST_LOGIN_REDIRECT_STORAGE_KEY)).toBe(
|
||||
"/share/abc123",
|
||||
);
|
||||
});
|
||||
|
||||
it("clears any existing entry when given an unsafe value", () => {
|
||||
sessionStorage.setItem(POST_LOGIN_REDIRECT_STORAGE_KEY, "/share/old");
|
||||
setPostLoginRedirectPath("//evil.example");
|
||||
expect(
|
||||
sessionStorage.getItem(POST_LOGIN_REDIRECT_STORAGE_KEY),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("clears any existing entry when given null", () => {
|
||||
sessionStorage.setItem(POST_LOGIN_REDIRECT_STORAGE_KEY, "/share/old");
|
||||
setPostLoginRedirectPath(null);
|
||||
expect(
|
||||
sessionStorage.getItem(POST_LOGIN_REDIRECT_STORAGE_KEY),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("consumePostLoginRedirectPath", () => {
|
||||
it("returns the stored path and clears it (single-use)", () => {
|
||||
sessionStorage.setItem(
|
||||
POST_LOGIN_REDIRECT_STORAGE_KEY,
|
||||
"/share/abc123",
|
||||
);
|
||||
expect(consumePostLoginRedirectPath()).toBe("/share/abc123");
|
||||
expect(
|
||||
sessionStorage.getItem(POST_LOGIN_REDIRECT_STORAGE_KEY),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null (and still clears) when the stored value is unsafe", () => {
|
||||
sessionStorage.setItem(
|
||||
POST_LOGIN_REDIRECT_STORAGE_KEY,
|
||||
"//evil.example",
|
||||
);
|
||||
expect(consumePostLoginRedirectPath()).toBeNull();
|
||||
expect(
|
||||
sessionStorage.getItem(POST_LOGIN_REDIRECT_STORAGE_KEY),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when nothing is stored", () => {
|
||||
expect(consumePostLoginRedirectPath()).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -53,6 +53,8 @@ const OAUTH_REDIRECT_COOKIE = "stirling_redirect_path";
|
||||
const OAUTH_REDIRECT_COOKIE_MAX_AGE = 60 * 5; // 5 minutes
|
||||
const DEFAULT_REDIRECT_PATH = `${BASE_PATH || ""}/auth/callback`;
|
||||
|
||||
export const POST_LOGIN_REDIRECT_STORAGE_KEY = "stirling_post_login_path";
|
||||
|
||||
function normalizeRedirectPath(target?: string): string {
|
||||
if (!target || typeof target !== "string") {
|
||||
return DEFAULT_REDIRECT_PATH;
|
||||
@@ -80,6 +82,52 @@ function persistRedirectPath(path: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
// Same-origin relative path, not pointing at auth plumbing. Rejects protocol-relative
|
||||
// URLs to guard against open-redirect abuse if the stored value is tampered with.
|
||||
export function isSafePostLoginRedirect(path: unknown): path is string {
|
||||
if (typeof path !== "string" || path.length === 0) return false;
|
||||
if (!path.startsWith("/") || path.startsWith("//")) return false;
|
||||
if (path.startsWith("/\\")) return false;
|
||||
const lowered = path.toLowerCase();
|
||||
if (
|
||||
lowered.startsWith("/login") ||
|
||||
lowered.startsWith("/auth/") ||
|
||||
lowered.startsWith("/oauth2") ||
|
||||
lowered.startsWith("/saml2")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function setPostLoginRedirectPath(
|
||||
path: string | null | undefined,
|
||||
): void {
|
||||
try {
|
||||
if (typeof window === "undefined") return;
|
||||
if (isSafePostLoginRedirect(path)) {
|
||||
window.sessionStorage.setItem(POST_LOGIN_REDIRECT_STORAGE_KEY, path);
|
||||
} else {
|
||||
window.sessionStorage.removeItem(POST_LOGIN_REDIRECT_STORAGE_KEY);
|
||||
}
|
||||
} catch (_error) {
|
||||
// sessionStorage unavailable (private mode) — fail open
|
||||
}
|
||||
}
|
||||
|
||||
export function consumePostLoginRedirectPath(): string | null {
|
||||
try {
|
||||
if (typeof window === "undefined") return null;
|
||||
const value = window.sessionStorage.getItem(
|
||||
POST_LOGIN_REDIRECT_STORAGE_KEY,
|
||||
);
|
||||
window.sessionStorage.removeItem(POST_LOGIN_REDIRECT_STORAGE_KEY);
|
||||
return isSafePostLoginRedirect(value) ? value : null;
|
||||
} catch (_error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Auth types
|
||||
export interface User {
|
||||
id: string;
|
||||
|
||||
@@ -2,14 +2,23 @@ import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import AuthCallback from "@app/routes/AuthCallback";
|
||||
import { springAuth } from "@app/auth/springAuthClient";
|
||||
import {
|
||||
POST_LOGIN_REDIRECT_STORAGE_KEY,
|
||||
springAuth,
|
||||
} from "@app/auth/springAuthClient";
|
||||
|
||||
// Mock springAuth
|
||||
vi.mock("@app/auth/springAuthClient", () => ({
|
||||
springAuth: {
|
||||
getSession: vi.fn(),
|
||||
},
|
||||
}));
|
||||
// Mock springAuth; keep the real redirect-path helpers.
|
||||
vi.mock("@app/auth/springAuthClient", async () => {
|
||||
const actual = await vi.importActual<
|
||||
typeof import("@app/auth/springAuthClient")
|
||||
>("@app/auth/springAuthClient");
|
||||
return {
|
||||
...actual,
|
||||
springAuth: {
|
||||
getSession: vi.fn(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Mock useNavigate
|
||||
const mockNavigate = vi.fn();
|
||||
@@ -24,6 +33,7 @@ vi.mock("react-router-dom", async () => {
|
||||
describe("AuthCallback", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
// Reset window.location.hash
|
||||
window.location.hash = "";
|
||||
@@ -149,6 +159,82 @@ describe("AuthCallback", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("should navigate to the stored post-login path when one is present", async () => {
|
||||
const mockToken = "oauth-jwt-token";
|
||||
const mockUser = {
|
||||
id: "123",
|
||||
email: "[email protected]",
|
||||
username: "oauthuser",
|
||||
role: "USER",
|
||||
};
|
||||
|
||||
window.location.hash = `#access_token=${mockToken}`;
|
||||
sessionStorage.setItem(POST_LOGIN_REDIRECT_STORAGE_KEY, "/share/abc123");
|
||||
|
||||
vi.mocked(springAuth.getSession).mockResolvedValueOnce({
|
||||
data: {
|
||||
session: {
|
||||
user: mockUser,
|
||||
access_token: mockToken,
|
||||
expires_in: 3600,
|
||||
expires_at: Date.now() + 3600000,
|
||||
},
|
||||
},
|
||||
error: null,
|
||||
});
|
||||
|
||||
render(
|
||||
<BrowserRouter>
|
||||
<AuthCallback />
|
||||
</BrowserRouter>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith("/share/abc123", {
|
||||
replace: true,
|
||||
});
|
||||
});
|
||||
// Stored path is single-use
|
||||
expect(sessionStorage.getItem(POST_LOGIN_REDIRECT_STORAGE_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it("should fall back to home when the stored post-login path is unsafe", async () => {
|
||||
const mockToken = "oauth-jwt-token";
|
||||
const mockUser = {
|
||||
id: "123",
|
||||
email: "[email protected]",
|
||||
username: "oauthuser",
|
||||
role: "USER",
|
||||
};
|
||||
|
||||
window.location.hash = `#access_token=${mockToken}`;
|
||||
// Protocol-relative URL — must not be followed
|
||||
sessionStorage.setItem(POST_LOGIN_REDIRECT_STORAGE_KEY, "//evil.example");
|
||||
|
||||
vi.mocked(springAuth.getSession).mockResolvedValueOnce({
|
||||
data: {
|
||||
session: {
|
||||
user: mockUser,
|
||||
access_token: mockToken,
|
||||
expires_in: 3600,
|
||||
expires_at: Date.now() + 3600000,
|
||||
},
|
||||
},
|
||||
error: null,
|
||||
});
|
||||
|
||||
render(
|
||||
<BrowserRouter>
|
||||
<AuthCallback />
|
||||
</BrowserRouter>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith("/", { replace: true });
|
||||
});
|
||||
expect(sessionStorage.getItem(POST_LOGIN_REDIRECT_STORAGE_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it("should display loading state while processing", () => {
|
||||
window.location.hash = "#access_token=processing-token";
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { springAuth } from "@app/auth/springAuthClient";
|
||||
import {
|
||||
consumePostLoginRedirectPath,
|
||||
springAuth,
|
||||
} from "@app/auth/springAuthClient";
|
||||
import { handleAuthCallbackSuccess } from "@app/extensions/authCallback";
|
||||
import styles from "@app/routes/AuthCallback.module.css";
|
||||
|
||||
@@ -157,12 +160,11 @@ export default function AuthCallback() {
|
||||
`[AuthCallback:${executionId}] Elapsed after stabilization wait: ${(performance.now() - startTime).toFixed(2)}ms`,
|
||||
);
|
||||
|
||||
const target = consumePostLoginRedirectPath() ?? "/";
|
||||
console.log(
|
||||
`[AuthCallback:${executionId}] Step 7: Navigating to home page`,
|
||||
`[AuthCallback:${executionId}] Step 7: Navigating to ${target}`,
|
||||
);
|
||||
|
||||
// Clear the hash from URL and redirect to home page
|
||||
navigate("/", { replace: true });
|
||||
navigate(target, { replace: true });
|
||||
|
||||
const duration = performance.now() - startTime;
|
||||
console.log(
|
||||
|
||||
@@ -40,13 +40,19 @@ vi.mock("@app/auth/UseSession", () => ({
|
||||
useAuth: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock springAuth
|
||||
vi.mock("@app/auth/springAuthClient", () => ({
|
||||
springAuth: {
|
||||
signInWithPassword: vi.fn(),
|
||||
signInWithOAuth: vi.fn(),
|
||||
},
|
||||
}));
|
||||
// Mock springAuth; keep the real redirect-path helpers.
|
||||
vi.mock("@app/auth/springAuthClient", async () => {
|
||||
const actual = await vi.importActual<
|
||||
typeof import("@app/auth/springAuthClient")
|
||||
>("@app/auth/springAuthClient");
|
||||
return {
|
||||
...actual,
|
||||
springAuth: {
|
||||
signInWithPassword: vi.fn(),
|
||||
signInWithOAuth: vi.fn(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Mock useDocumentMeta
|
||||
vi.mock("@app/hooks/useDocumentMeta", () => ({
|
||||
@@ -692,4 +698,55 @@ describe("Login", () => {
|
||||
expect(submitButton).not.toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
it("should persist location.state.from.pathname before triggering SSO so the user returns to their original URL", async () => {
|
||||
const user = userEvent.setup();
|
||||
sessionStorage.clear();
|
||||
|
||||
vi.mocked(apiClient.get).mockResolvedValue({
|
||||
data: {
|
||||
enableLogin: true,
|
||||
providerList: {
|
||||
"/oauth2/authorization/authentik": "Authentik",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
vi.mocked(springAuth.signInWithOAuth).mockResolvedValueOnce({
|
||||
error: null,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestWrapper>
|
||||
<MemoryRouter
|
||||
initialEntries={[
|
||||
{
|
||||
pathname: "/login",
|
||||
state: { from: { pathname: "/share/abc123" } },
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Login />
|
||||
</MemoryRouter>
|
||||
</TestWrapper>,
|
||||
);
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(screen.getByText("Authentik")).toBeTruthy();
|
||||
},
|
||||
{ timeout: 3000 },
|
||||
);
|
||||
|
||||
await user.click(screen.getByText("Authentik"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(springAuth.signInWithOAuth).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Must be stashed before the cross-origin SSO redirect wipes location.state.
|
||||
expect(sessionStorage.getItem("stirling_post_login_path")).toBe(
|
||||
"/share/abc123",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,10 @@ import {
|
||||
useSearchParams,
|
||||
} from "react-router-dom";
|
||||
import { Text, Stack, Alert } from "@mantine/core";
|
||||
import { springAuth } from "@app/auth/springAuthClient";
|
||||
import {
|
||||
setPostLoginRedirectPath,
|
||||
springAuth,
|
||||
} from "@app/auth/springAuthClient";
|
||||
import { useAuth } from "@app/auth/UseSession";
|
||||
import { useAppConfig } from "@app/contexts/AppConfigContext";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -34,6 +37,19 @@ export default function Login() {
|
||||
const location = useLocation();
|
||||
const [searchParams] = useSearchParams();
|
||||
const { session, loading } = useAuth();
|
||||
const resolveReturnPath = (): string | null => {
|
||||
const fromState = (
|
||||
location.state as { from?: { pathname?: string } } | null
|
||||
)?.from?.pathname;
|
||||
if (fromState) return fromState;
|
||||
const fromQuery = searchParams.get("from");
|
||||
if (!fromQuery) return null;
|
||||
try {
|
||||
return decodeURIComponent(fromQuery);
|
||||
} catch {
|
||||
return fromQuery;
|
||||
}
|
||||
};
|
||||
const { refetch } = useAppConfig();
|
||||
const { t } = useTranslation();
|
||||
const [isSigningIn, setIsSigningIn] = useState(false);
|
||||
@@ -166,15 +182,13 @@ export default function Login() {
|
||||
// Redirect immediately if user has valid session (JWT already validated by AuthProvider)
|
||||
useEffect(() => {
|
||||
if (!loading && session) {
|
||||
const returnPath = (
|
||||
location.state as { from?: { pathname?: string } } | null
|
||||
)?.from?.pathname;
|
||||
const returnPath = resolveReturnPath();
|
||||
console.debug("[Login] User already authenticated, redirecting to home", {
|
||||
returnPath,
|
||||
});
|
||||
navigate(returnPath || "/", { replace: true });
|
||||
}
|
||||
}, [session, loading, navigate, location.state]);
|
||||
}, [session, loading, navigate, location.state, searchParams]);
|
||||
|
||||
// If backend reports login is disabled, redirect to home (anonymous mode)
|
||||
useEffect(() => {
|
||||
@@ -267,6 +281,12 @@ export default function Login() {
|
||||
setError(null);
|
||||
clearLogoutBlock();
|
||||
|
||||
// Don't overwrite a path already stashed by httpErrorHandler on a prior 401.
|
||||
const returnPath = resolveReturnPath();
|
||||
if (returnPath) {
|
||||
setPostLoginRedirectPath(returnPath);
|
||||
}
|
||||
|
||||
console.log(`[Login] Signing in with provider: ${provider}`);
|
||||
|
||||
// Redirect to Spring OAuth2 endpoint using the actual provider ID from backend
|
||||
|
||||
Reference in New Issue
Block a user