auth-fixes (#12)
## Summary
Wire spec-driven auth into the frontend. Auth config (server URL, paths) is extracted from the served OpenAPI spec by `AppProvider`. `AuthProvider` receives the config as a prop. 401 responses from both the main API and the auth server dispatch an `auth:unauthorized` event that triggers redirect to `/login`. Fix `ProfileRoutes` URL duplication bug.
## Changes
### Auth config from spec
- **`main.jsx`** — `AppProvider` wraps everything, loads spec, exposes `authConfig`. `AuthProvider` receives `authConfig` from `useAppContext()`. `onUnauthorized` passed to both `AppProvider` and `AuthProvider` wires `navigate("/login")`.
### 401 handling
- **`AppProvider.tsx`** — remove `onUnauthorized` prop (handled by `AuthProvider`'s event listener instead, avoiding double-navigation).
- **`useApi.ts`** — 401 response interceptor dispatches `auth:unauthorized` CustomEvent on `window`.
### Profile routing fix
- **`Admin.tsx:ProfileRoutes`** — replace nested `<Routes>` (which caused `/profile/me/me` URL duplication with React Router v6) with `useLocation()`/`useNavigate()` conditional rendering. Only allows `/profile/me` and `/profile/me/edit`.
- **`Admin.tsx:ProfileComponentWrapper`** — replace `pushState() + reload()` with React Router `navigate()` for both `onEdit` and `handleSubmit`.
### Debug logging
- Temporary console logs at every navigation point for diagnosing remaining issues.
Reviewed-on: #12
Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
This commit is contained in:
122
react-auth/ProfileCreate.tsx
Normal file
122
react-auth/ProfileCreate.tsx
Normal file
@@ -0,0 +1,122 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
Box,
|
||||
TextField,
|
||||
Button,
|
||||
Typography,
|
||||
CircularProgress,
|
||||
} from "@mui/material";
|
||||
|
||||
export interface ProfileCreateProps {
|
||||
defaultUsername?: string;
|
||||
defaultEmail?: string;
|
||||
onSubmit: (data: { name: string; email: string }) => Promise<void>;
|
||||
onBack?: () => void;
|
||||
loading?: boolean;
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
export function ProfileCreate({
|
||||
defaultUsername,
|
||||
defaultEmail,
|
||||
onSubmit,
|
||||
onBack,
|
||||
loading = false,
|
||||
error = null,
|
||||
}: ProfileCreateProps) {
|
||||
const [name, setName] = React.useState("");
|
||||
const [email, setEmail] = React.useState(defaultEmail ?? "");
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
await onSubmit({ name: name || defaultUsername || "", email });
|
||||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
maxWidth: 480,
|
||||
mx: "auto",
|
||||
mt: 4,
|
||||
p: 4,
|
||||
borderRadius: 3,
|
||||
boxShadow: 3,
|
||||
bgcolor: "background.paper",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h5" fontWeight="bold" gutterBottom>
|
||||
Complete Your Profile
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
|
||||
{defaultUsername && (
|
||||
<span>
|
||||
Welcome <strong>{defaultUsername}</strong>!{" "}
|
||||
</span>
|
||||
)}
|
||||
Fill in your details to get started.
|
||||
</Typography>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
{defaultUsername && (
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Username"
|
||||
value={defaultUsername}
|
||||
margin="normal"
|
||||
disabled
|
||||
/>
|
||||
)}
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Full Name"
|
||||
margin="normal"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={defaultUsername ?? "Your name"}
|
||||
required
|
||||
autoFocus={!defaultUsername}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Email"
|
||||
type="email"
|
||||
margin="normal"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder={defaultEmail ?? "you@example.com"}
|
||||
required
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<Typography color="error" variant="body2" sx={{ mt: 1 }}>
|
||||
{error}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Box sx={{ display: "flex", gap: 2, mt: 3 }}>
|
||||
{onBack && (
|
||||
<Button
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
onClick={onBack}
|
||||
disabled={loading}
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
fullWidth
|
||||
type="submit"
|
||||
variant="contained"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? <CircularProgress size={24} /> : "Create Profile"}
|
||||
</Button>
|
||||
</Box>
|
||||
</form>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
111
react-auth/ProfileEdit.tsx
Normal file
111
react-auth/ProfileEdit.tsx
Normal file
@@ -0,0 +1,111 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
Box,
|
||||
TextField,
|
||||
Button,
|
||||
Typography,
|
||||
CircularProgress,
|
||||
} from "@mui/material";
|
||||
|
||||
export interface ProfileEditProps {
|
||||
name: string;
|
||||
username: string;
|
||||
email: string;
|
||||
onSubmit: (data: { name: string; email: string }) => Promise<void>;
|
||||
onBack?: () => void;
|
||||
loading?: boolean;
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
export function ProfileEdit({
|
||||
name: initialName,
|
||||
username,
|
||||
email: initialEmail,
|
||||
onSubmit,
|
||||
onBack,
|
||||
loading = false,
|
||||
error = null,
|
||||
}: ProfileEditProps) {
|
||||
const [name, setName] = React.useState(initialName);
|
||||
const [email, setEmail] = React.useState(initialEmail);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
await onSubmit({ name, email });
|
||||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
maxWidth: 480,
|
||||
mx: "auto",
|
||||
mt: 4,
|
||||
p: 4,
|
||||
borderRadius: 3,
|
||||
boxShadow: 3,
|
||||
bgcolor: "background.paper",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h5" fontWeight="bold" gutterBottom>
|
||||
Edit Profile
|
||||
</Typography>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Username"
|
||||
value={username}
|
||||
margin="normal"
|
||||
disabled
|
||||
/>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Full Name"
|
||||
margin="normal"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Email"
|
||||
type="email"
|
||||
margin="normal"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<Typography color="error" variant="body2" sx={{ mt: 1 }}>
|
||||
{error}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Box sx={{ display: "flex", gap: 2, mt: 3 }}>
|
||||
{onBack && (
|
||||
<Button
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
onClick={onBack}
|
||||
disabled={loading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
fullWidth
|
||||
type="submit"
|
||||
variant="contained"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? <CircularProgress size={24} /> : "Save Changes"}
|
||||
</Button>
|
||||
</Box>
|
||||
</form>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
85
react-auth/ProfileView.tsx
Normal file
85
react-auth/ProfileView.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Button,
|
||||
Avatar,
|
||||
Paper,
|
||||
CircularProgress,
|
||||
} from "@mui/material";
|
||||
|
||||
export interface ProfileViewProps {
|
||||
name: string;
|
||||
username: string;
|
||||
email: string;
|
||||
onEdit?: () => void;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
export function ProfileView({
|
||||
name,
|
||||
username,
|
||||
email,
|
||||
onEdit,
|
||||
loading = false,
|
||||
}: ProfileViewProps) {
|
||||
const initials = (name || username)
|
||||
.split(" ")
|
||||
.map((s) => s[0])
|
||||
.join("")
|
||||
.toUpperCase()
|
||||
.slice(0, 2);
|
||||
|
||||
return (
|
||||
<Paper
|
||||
sx={{
|
||||
maxWidth: 480,
|
||||
mx: "auto",
|
||||
mt: 4,
|
||||
p: 4,
|
||||
borderRadius: 3,
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 3, mb: 3 }}>
|
||||
<Avatar
|
||||
sx={{
|
||||
width: 64,
|
||||
height: 64,
|
||||
bgcolor: "primary.main",
|
||||
fontSize: 24,
|
||||
}}
|
||||
>
|
||||
{initials}
|
||||
</Avatar>
|
||||
|
||||
<Box>
|
||||
<Typography variant="h5" fontWeight="bold">
|
||||
{name || username}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
@{username}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Typography variant="overline" color="text.secondary" display="block">
|
||||
Email
|
||||
</Typography>
|
||||
<Typography variant="body1">{email}</Typography>
|
||||
</Box>
|
||||
|
||||
{onEdit && (
|
||||
<Button
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
onClick={onEdit}
|
||||
disabled={loading}
|
||||
sx={{ mt: 1 }}
|
||||
>
|
||||
{loading ? <CircularProgress size={20} /> : "Edit Profile"}
|
||||
</Button>
|
||||
)}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -17,7 +17,9 @@ export function attachAuthInterceptors(client: AxiosInstance) {
|
||||
(res) => res,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
console.log("[authAxios] 401 from %s %s", error.config?.method, error.config?.url);
|
||||
tokenStore.clear();
|
||||
window.dispatchEvent(new CustomEvent("auth:unauthorized"));
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,15 @@ import { tokenStore } from "./token";
|
||||
import { createApiClient } from "./axios";
|
||||
import { AuthUser } from "./models";
|
||||
|
||||
export interface AuthServerConfig {
|
||||
serverUrl: string;
|
||||
loginPath: string;
|
||||
registerPath: string;
|
||||
logoutPath: string;
|
||||
mePath: string;
|
||||
introspectPath: string;
|
||||
}
|
||||
|
||||
interface AuthContextModel {
|
||||
currentUser: AuthUser | null;
|
||||
token: string | null;
|
||||
@@ -17,24 +26,26 @@ const AuthContext = createContext<AuthContextModel | undefined>(undefined);
|
||||
|
||||
export function AuthProvider({
|
||||
children,
|
||||
authBaseUrl,
|
||||
authConfig,
|
||||
onUnauthorized,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
authBaseUrl: string;
|
||||
authConfig: AuthServerConfig;
|
||||
onUnauthorized?: () => void;
|
||||
}) {
|
||||
const [currentUser, setCurrentUser] = useState<AuthUser | null>(null);
|
||||
const [token, setToken] = useState<string | null>(tokenStore.get());
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const auth = createApiClient(authBaseUrl);
|
||||
const auth = createApiClient(authConfig.serverUrl);
|
||||
|
||||
const login = async (username: string, password: string) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const res = await auth.post("/login", { username, password });
|
||||
const res = await auth.post(authConfig.loginPath, { username, password });
|
||||
const { access_token, user } = res.data;
|
||||
|
||||
tokenStore.set(access_token);
|
||||
@@ -52,7 +63,7 @@ export function AuthProvider({
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
await auth.post("/register", { username, password });
|
||||
await auth.post(authConfig.registerPath, { username, password });
|
||||
await login(username, password);
|
||||
} catch (e: any) {
|
||||
setError(e.response?.data?.detail ?? "Registration failed");
|
||||
@@ -61,25 +72,55 @@ export function AuthProvider({
|
||||
}
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
const logout = async () => {
|
||||
try {
|
||||
await auth.post(authConfig.logoutPath);
|
||||
} catch {
|
||||
// Server logout is best-effort; clear token locally regardless
|
||||
}
|
||||
tokenStore.clear();
|
||||
setToken(null);
|
||||
setCurrentUser(null);
|
||||
};
|
||||
|
||||
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 {
|
||||
const me = await auth.get("/me");
|
||||
const me = await auth.get(authConfig.mePath);
|
||||
console.log("[AuthProvider] fetchCurrentUser SUCCESS", me.data);
|
||||
setCurrentUser({ ...me.data });
|
||||
} catch {
|
||||
logout();
|
||||
} catch (e: any) {
|
||||
console.log("[AuthProvider] fetchCurrentUser ERROR", e.message, e.response?.status);
|
||||
tokenStore.clear();
|
||||
setToken(null);
|
||||
setCurrentUser(null);
|
||||
onUnauthorized?.();
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchCurrentUser();
|
||||
}, [token]);
|
||||
console.log("[AuthProvider] useEffect token=%s serverUrl=%s", token, authConfig.serverUrl);
|
||||
if (authConfig.serverUrl) {
|
||||
fetchCurrentUser();
|
||||
}
|
||||
}, [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 (
|
||||
<AuthContext.Provider
|
||||
@@ -94,4 +135,4 @@ export function useAuth(): AuthContextModel {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error("useAuth must be used inside AuthProvider");
|
||||
return ctx;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,13 @@
|
||||
export { AuthProvider, useAuth } from "./contexts";
|
||||
export type { AuthServerConfig } from "./contexts";
|
||||
export { createApiClient } from "./axios";
|
||||
export { AuthPage } from "./AuthPage";
|
||||
export { ProfileCreate } from "./ProfileCreate";
|
||||
export { ProfileEdit } from "./ProfileEdit";
|
||||
export { ProfileView } from "./ProfileView";
|
||||
export type { AuthUser } from "./models";
|
||||
export type { AuthMode } from "./AuthPage";
|
||||
export type { ProfileCreateProps } from "./ProfileCreate";
|
||||
export type { ProfileEditProps } from "./ProfileEdit";
|
||||
export type { ProfileViewProps } from "./ProfileView";
|
||||
export { tokenStore } from "./token"
|
||||
|
||||
Reference in New Issue
Block a user