fix: replace nested Routes with useLocation, remove pushState+reload, add debug logs
- ProfileRoutes: removed nested <Routes> in favor of useLocation()/useNavigate() with strict allowlist for /profile/me and /profile/me/edit - ProfileComponentWrapper: replaced pushState()+reload() with navigate() - useApi: log 401 and non-401 errors - contexts.tsx: log fetchCurrentUser lifecycle and auth:unauthorized events - axios.ts: log auth server 401s
This commit is contained in:
@@ -17,7 +17,9 @@ export function attachAuthInterceptors(client: AxiosInstance) {
|
|||||||
(res) => res,
|
(res) => res,
|
||||||
(error) => {
|
(error) => {
|
||||||
if (error.response?.status === 401) {
|
if (error.response?.status === 401) {
|
||||||
|
console.log("[authAxios] 401 from %s %s", error.config?.method, error.config?.url);
|
||||||
tokenStore.clear();
|
tokenStore.clear();
|
||||||
|
window.dispatchEvent(new CustomEvent("auth:unauthorized"));
|
||||||
}
|
}
|
||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,9 +27,11 @@ const AuthContext = createContext<AuthContextModel | undefined>(undefined);
|
|||||||
export function AuthProvider({
|
export function AuthProvider({
|
||||||
children,
|
children,
|
||||||
authConfig,
|
authConfig,
|
||||||
|
onUnauthorized,
|
||||||
}: {
|
}: {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
authConfig: AuthServerConfig;
|
authConfig: AuthServerConfig;
|
||||||
|
onUnauthorized?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const [currentUser, setCurrentUser] = useState<AuthUser | null>(null);
|
const [currentUser, setCurrentUser] = useState<AuthUser | null>(null);
|
||||||
const [token, setToken] = useState<string | null>(tokenStore.get());
|
const [token, setToken] = useState<string | null>(tokenStore.get());
|
||||||
@@ -82,20 +84,43 @@ export function AuthProvider({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const fetchCurrentUser = async () => {
|
const fetchCurrentUser = async () => {
|
||||||
if (!token) return;
|
if (!token) { console.log("[AuthProvider] fetchCurrentUser SKIP no token"); return; }
|
||||||
|
console.log("[AuthProvider] fetchCurrentUser calling %s%s", authConfig.serverUrl, authConfig.mePath);
|
||||||
try {
|
try {
|
||||||
const me = await auth.get(authConfig.mePath);
|
const me = await auth.get(authConfig.mePath);
|
||||||
|
console.log("[AuthProvider] fetchCurrentUser SUCCESS", me.data);
|
||||||
setCurrentUser({ ...me.data });
|
setCurrentUser({ ...me.data });
|
||||||
} catch {
|
} catch (e: any) {
|
||||||
|
console.log("[AuthProvider] fetchCurrentUser ERROR", e.message, e.response?.status);
|
||||||
tokenStore.clear();
|
tokenStore.clear();
|
||||||
setToken(null);
|
setToken(null);
|
||||||
setCurrentUser(null);
|
setCurrentUser(null);
|
||||||
|
onUnauthorized?.();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
console.log("[AuthProvider] useEffect token=%s serverUrl=%s", token, authConfig.serverUrl);
|
||||||
|
if (authConfig.serverUrl) {
|
||||||
fetchCurrentUser();
|
fetchCurrentUser();
|
||||||
}, [token]);
|
}
|
||||||
|
}, [token, authConfig.serverUrl]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = () => {
|
||||||
|
console.log("[AuthProvider] auth:unauthorized event received");
|
||||||
|
tokenStore.clear();
|
||||||
|
setToken(null);
|
||||||
|
setCurrentUser(null);
|
||||||
|
onUnauthorized?.();
|
||||||
|
};
|
||||||
|
console.log("[AuthProvider] adding auth:unauthorized listener");
|
||||||
|
window.addEventListener("auth:unauthorized", handler);
|
||||||
|
return () => {
|
||||||
|
console.log("[AuthProvider] removing auth:unauthorized listener");
|
||||||
|
window.removeEventListener("auth:unauthorized", handler);
|
||||||
|
};
|
||||||
|
}, [onUnauthorized]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider
|
<AuthContext.Provider
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useEffect, useState } from "react";
|
import React, { useEffect, useState } from "react";
|
||||||
import { Routes, Route, Navigate } from "react-router-dom";
|
import { Routes, Route, Navigate, useLocation, useNavigate } from "react-router-dom";
|
||||||
import { Box, CircularProgress, Alert } from "@mui/material";
|
import { Box, CircularProgress, Alert } from "@mui/material";
|
||||||
import { useAppContext } from "../context/AppContext";
|
import { useAppContext } from "../context/AppContext";
|
||||||
import { Layout } from "./Layout";
|
import { Layout } from "./Layout";
|
||||||
@@ -80,46 +80,49 @@ export function ProfileRoutes() {
|
|||||||
const { profileOperations, profileComponents } = useAppContext();
|
const { profileOperations, profileComponents } = useAppContext();
|
||||||
const ops = profileOperations;
|
const ops = profileOperations;
|
||||||
const getOp = ops.find((o) => o.method === "GET");
|
const getOp = ops.find((o) => o.method === "GET");
|
||||||
|
const location = useLocation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
return (
|
console.log("[ProfileRoutes] render pathname=%s ops=%o", location.pathname, ops.map(o => o.path));
|
||||||
<Routes>
|
|
||||||
<Route path=":username" element={<Navigate to="me" replace />} />
|
|
||||||
{ops.map((op) => {
|
|
||||||
const basePath = friendlyProfilePath(op.path);
|
|
||||||
let Component: React.ComponentType<any> | undefined;
|
|
||||||
let mode: "view" | "create" | "edit" | undefined;
|
|
||||||
|
|
||||||
if (op.method === "GET" && profileComponents.view) {
|
// Redirect /:username to /me (only "me" and "me/edit" are valid)
|
||||||
Component = profileComponents.view;
|
const match = location.pathname.match(/^\/profile\/(.+)$/);
|
||||||
mode = "view";
|
const username = match ? match[1] : "";
|
||||||
} else if (op.method === "POST" && profileComponents.create) {
|
console.log("[ProfileRoutes] match=%o username=%s", match && match[1], username);
|
||||||
Component = profileComponents.create;
|
if (username !== "me" && username !== "me/edit") {
|
||||||
mode = "create";
|
console.log("[ProfileRoutes] redirecting to /profile/me");
|
||||||
} else if ((op.method === "PUT" || op.method === "PATCH") && profileComponents.edit) {
|
navigate("/profile/me", { replace: true });
|
||||||
Component = profileComponents.edit;
|
return null;
|
||||||
mode = "edit";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!Component || !mode) return null;
|
const isEdit = username === "me/edit";
|
||||||
|
const mode = isEdit ? "edit" as const : "view" as const;
|
||||||
|
console.log("[ProfileRoutes] mode=%s", mode);
|
||||||
|
|
||||||
const routePath = mode === "view" ? basePath : `${basePath}/edit`;
|
const op = ops.find((o) => {
|
||||||
|
if (isEdit && (o.method === "PUT" || o.method === "PATCH")) return true;
|
||||||
|
if (!isEdit && o.method === "GET") return true;
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!op) return null;
|
||||||
|
|
||||||
|
let Component: React.ComponentType<any> | undefined;
|
||||||
|
if (mode === "view" && profileComponents.view) {
|
||||||
|
Component = profileComponents.view;
|
||||||
|
} else if (mode === "edit" && profileComponents.edit) {
|
||||||
|
Component = profileComponents.edit;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Component) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Route
|
|
||||||
key={op.operationId}
|
|
||||||
path={routePath}
|
|
||||||
element={
|
|
||||||
<ProfileComponentWrapper
|
<ProfileComponentWrapper
|
||||||
Component={Component}
|
Component={Component}
|
||||||
mode={mode}
|
mode={mode}
|
||||||
operation={op}
|
operation={op}
|
||||||
getOperation={getOp}
|
getOperation={getOp}
|
||||||
/>
|
/>
|
||||||
}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Routes>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,19 +137,24 @@ function ProfileComponentWrapper({
|
|||||||
operation: { path: string; method: string };
|
operation: { path: string; method: string };
|
||||||
getOperation?: { path: string };
|
getOperation?: { path: string };
|
||||||
}) {
|
}) {
|
||||||
|
const navigate = useNavigate();
|
||||||
const [data, setData] = useState<any>(null);
|
const [data, setData] = useState<any>(null);
|
||||||
const [loading, setLoading] = useState(mode !== "create");
|
const [loading, setLoading] = useState(mode !== "create");
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
console.log("[ProfileComponentWrapper] render mode=%s fetchPath=%s", mode, getOperation?.path ?? operation.path);
|
||||||
|
|
||||||
const fetchPath = getOperation?.path ?? operation.path;
|
const fetchPath = getOperation?.path ?? operation.path;
|
||||||
|
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
|
console.log("[ProfileComponentWrapper] fetchData START path=%s", fetchPath);
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const res = await getApi().get(fetchPath);
|
const res = await getApi().get(fetchPath);
|
||||||
|
console.log("[ProfileComponentWrapper] fetchData SUCCESS", res.data);
|
||||||
setData(res.data);
|
setData(res.data);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
|
console.log("[ProfileComponentWrapper] fetchData ERROR", e.message, e.response?.status);
|
||||||
setError(e.response?.data?.detail ?? e.message ?? "Failed to load profile");
|
setError(e.response?.data?.detail ?? e.message ?? "Failed to load profile");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@@ -155,11 +163,13 @@ function ProfileComponentWrapper({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (mode !== "create") {
|
if (mode !== "create") {
|
||||||
|
console.log("[ProfileComponentWrapper] useEffect calling fetchData");
|
||||||
fetchData();
|
fetchData();
|
||||||
}
|
}
|
||||||
}, [fetchPath, mode]);
|
}, [fetchPath, mode]);
|
||||||
|
|
||||||
const handleSubmit = async (formData: Record<string, any>) => {
|
const handleSubmit = async (formData: Record<string, any>) => {
|
||||||
|
console.log("[ProfileComponentWrapper] handleSubmit START");
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
@@ -168,11 +178,11 @@ function ProfileComponentWrapper({
|
|||||||
} else {
|
} else {
|
||||||
await getApi()({ method: operation.method.toLowerCase(), url: operation.path, data: formData });
|
await getApi()({ method: operation.method.toLowerCase(), url: operation.path, data: formData });
|
||||||
}
|
}
|
||||||
// Navigate back to the base profile view path
|
console.log("[ProfileComponentWrapper] handleSubmit SUCCESS, navigating to /profile/me");
|
||||||
const base = friendlyProfilePath(operation.path);
|
const base = friendlyProfilePath(operation.path);
|
||||||
window.history.pushState(null, "", `/${base}`);
|
navigate(`/profile/${base}`, { replace: true });
|
||||||
window.location.reload();
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
|
console.log("[ProfileComponentWrapper] handleSubmit ERROR", e.message, e.response?.status);
|
||||||
setError(e.response?.data?.detail ?? e.message ?? "Operation failed");
|
setError(e.response?.data?.detail ?? e.message ?? "Operation failed");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@@ -203,10 +213,7 @@ function ProfileComponentWrapper({
|
|||||||
props.username = data.username;
|
props.username = data.username;
|
||||||
props.email = data.email;
|
props.email = data.email;
|
||||||
}
|
}
|
||||||
props.onEdit = () => {
|
props.onEdit = () => navigate("/profile/me/edit");
|
||||||
window.history.pushState(null, "", `/profile/me/edit`);
|
|
||||||
window.location.reload();
|
|
||||||
};
|
|
||||||
props.loading = loading;
|
props.loading = loading;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
import axios, { AxiosInstance } from "axios";
|
import axios, { AxiosInstance } from "axios";
|
||||||
|
|
||||||
let apiClient: AxiosInstance | null = null;
|
let apiClient: AxiosInstance | null = null;
|
||||||
|
let _onUnauthorized: (() => void) | undefined;
|
||||||
|
|
||||||
export function initApi(baseUrl: string, getToken?: () => string | null): AxiosInstance {
|
export function initApi(baseUrl: string, getToken?: () => string | null, onUnauthorized?: () => void): AxiosInstance {
|
||||||
if (apiClient && apiClient.defaults.baseURL === baseUrl) {
|
if (apiClient && apiClient.defaults.baseURL === baseUrl) {
|
||||||
|
_onUnauthorized = onUnauthorized;
|
||||||
return apiClient;
|
return apiClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_onUnauthorized = onUnauthorized;
|
||||||
|
|
||||||
apiClient = axios.create({
|
apiClient = axios.create({
|
||||||
baseURL: baseUrl,
|
baseURL: baseUrl,
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
@@ -20,6 +24,20 @@ export function initApi(baseUrl: string, getToken?: () => string | null): AxiosI
|
|||||||
return config;
|
return config;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
apiClient.interceptors.response.use(
|
||||||
|
(res) => res,
|
||||||
|
(error) => {
|
||||||
|
if (error.response?.status === 401) {
|
||||||
|
console.log("[useApi] 401 from %s %s - dispatching auth:unauthorized", error.config?.method, error.config?.url);
|
||||||
|
window.dispatchEvent(new CustomEvent("auth:unauthorized"));
|
||||||
|
_onUnauthorized?.();
|
||||||
|
} else {
|
||||||
|
console.log("[useApi] non-401 error %s from %s %s", error.response?.status, error.config?.method, error.config?.url);
|
||||||
|
}
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
return apiClient;
|
return apiClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user