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:
@@ -1,6 +1,6 @@
|
|||||||
<component name="ProjectRunConfigurationManager">
|
<component name="ProjectRunConfigurationManager">
|
||||||
<configuration default="false" name="Install Deps" type="js.build_tools.npm">
|
<configuration default="false" name="Install Deps" type="js.build_tools.npm">
|
||||||
<package-json value="$PROJECT_DIR$/package.json" />
|
<package-json value="$PROJECT_DIR$/../khata-ui/package.json" />
|
||||||
<command value="install" />
|
<command value="install" />
|
||||||
<node-interpreter value="$APPLICATION_CONFIG_DIR$/node/versions/20.19.5/node" />
|
<node-interpreter value="$APPLICATION_CONFIG_DIR$/node/versions/20.19.5/node" />
|
||||||
<envs />
|
<envs />
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
<component name="ProjectRunConfigurationManager">
|
<component name="ProjectRunConfigurationManager">
|
||||||
<configuration default="false" name="Run Dev" type="js.build_tools.npm">
|
<configuration default="false" name="Run Dev" type="js.build_tools.npm">
|
||||||
<package-json value="$PROJECT_DIR$/package.json" />
|
<package-json value="$PROJECT_DIR$/../khata-ui/package.json" />
|
||||||
<command value="run" />
|
<command value="run" />
|
||||||
<scripts>
|
<scripts>
|
||||||
<script value="dev" />
|
<script value="dev" />
|
||||||
</scripts>
|
</scripts>
|
||||||
<node-interpreter value="$APPLICATION_CONFIG_DIR$/node/versions/20.19.5/node" />
|
<node-interpreter value="$APPLICATION_CONFIG_DIR$/node/versions/20.19.5/node" />
|
||||||
<envs />
|
<envs />
|
||||||
|
<EXTENSION ID="com.intellij.lang.javascript.buildTools.npm.rc.StartBrowserRunConfigurationExtension">
|
||||||
|
<browser name="98ca6316-2f89-46d9-a9e5-fa9e2b0625b3" />
|
||||||
|
</EXTENSION>
|
||||||
<method v="2" />
|
<method v="2" />
|
||||||
</configuration>
|
</configuration>
|
||||||
</component>
|
</component>
|
||||||
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,
|
(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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,15 @@ import { tokenStore } from "./token";
|
|||||||
import { createApiClient } from "./axios";
|
import { createApiClient } from "./axios";
|
||||||
import { AuthUser } from "./models";
|
import { AuthUser } from "./models";
|
||||||
|
|
||||||
|
export interface AuthServerConfig {
|
||||||
|
serverUrl: string;
|
||||||
|
loginPath: string;
|
||||||
|
registerPath: string;
|
||||||
|
logoutPath: string;
|
||||||
|
mePath: string;
|
||||||
|
introspectPath: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface AuthContextModel {
|
interface AuthContextModel {
|
||||||
currentUser: AuthUser | null;
|
currentUser: AuthUser | null;
|
||||||
token: string | null;
|
token: string | null;
|
||||||
@@ -17,24 +26,26 @@ const AuthContext = createContext<AuthContextModel | undefined>(undefined);
|
|||||||
|
|
||||||
export function AuthProvider({
|
export function AuthProvider({
|
||||||
children,
|
children,
|
||||||
authBaseUrl,
|
authConfig,
|
||||||
|
onUnauthorized,
|
||||||
}: {
|
}: {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
authBaseUrl: string;
|
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());
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const auth = createApiClient(authBaseUrl);
|
const auth = createApiClient(authConfig.serverUrl);
|
||||||
|
|
||||||
const login = async (username: string, password: string) => {
|
const login = async (username: string, password: string) => {
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
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;
|
const { access_token, user } = res.data;
|
||||||
|
|
||||||
tokenStore.set(access_token);
|
tokenStore.set(access_token);
|
||||||
@@ -52,7 +63,7 @@ export function AuthProvider({
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
await auth.post("/register", { username, password });
|
await auth.post(authConfig.registerPath, { username, password });
|
||||||
await login(username, password);
|
await login(username, password);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e.response?.data?.detail ?? "Registration failed");
|
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();
|
tokenStore.clear();
|
||||||
setToken(null);
|
setToken(null);
|
||||||
setCurrentUser(null);
|
setCurrentUser(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
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("/me");
|
const me = await auth.get(authConfig.mePath);
|
||||||
|
console.log("[AuthProvider] fetchCurrentUser SUCCESS", me.data);
|
||||||
setCurrentUser({ ...me.data });
|
setCurrentUser({ ...me.data });
|
||||||
} catch {
|
} catch (e: any) {
|
||||||
logout();
|
console.log("[AuthProvider] fetchCurrentUser ERROR", e.message, e.response?.status);
|
||||||
|
tokenStore.clear();
|
||||||
|
setToken(null);
|
||||||
|
setCurrentUser(null);
|
||||||
|
onUnauthorized?.();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchCurrentUser();
|
console.log("[AuthProvider] useEffect token=%s serverUrl=%s", token, authConfig.serverUrl);
|
||||||
}, [token]);
|
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 (
|
return (
|
||||||
<AuthContext.Provider
|
<AuthContext.Provider
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
export { AuthProvider, useAuth } from "./contexts";
|
export { AuthProvider, useAuth } from "./contexts";
|
||||||
|
export type { AuthServerConfig } from "./contexts";
|
||||||
export { createApiClient } from "./axios";
|
export { createApiClient } from "./axios";
|
||||||
export { AuthPage } from "./AuthPage";
|
export { AuthPage } from "./AuthPage";
|
||||||
|
export { ProfileCreate } from "./ProfileCreate";
|
||||||
|
export { ProfileEdit } from "./ProfileEdit";
|
||||||
|
export { ProfileView } from "./ProfileView";
|
||||||
export type { AuthUser } from "./models";
|
export type { AuthUser } from "./models";
|
||||||
export type { AuthMode } from "./AuthPage";
|
export type { AuthMode } from "./AuthPage";
|
||||||
|
export type { ProfileCreateProps } from "./ProfileCreate";
|
||||||
|
export type { ProfileEditProps } from "./ProfileEdit";
|
||||||
|
export type { ProfileViewProps } from "./ProfileView";
|
||||||
export { tokenStore } from "./token"
|
export { tokenStore } from "./token"
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
export { AppProvider } from "./src/context/AppProvider";
|
export { AppProvider } from "./src/context/AppProvider";
|
||||||
export { Admin } from "./src/components/Admin";
|
export { Admin, ProfileRoutes } from "./src/components/Admin";
|
||||||
|
export type { AdminProps, ProfileRoute } from "./src/components/Admin";
|
||||||
export { useAppContext } from "./src/context/AppContext";
|
export { useAppContext } from "./src/context/AppContext";
|
||||||
export { useResource } from "./src/context/useResource";
|
export { useResource } from "./src/context/useResource";
|
||||||
export { ListCellRenderer, DetailFieldRenderer, applyDisplayFormat } from "./src/components/fields";
|
export { ListCellRenderer, DetailFieldRenderer, applyDisplayFormat } from "./src/components/fields";
|
||||||
@@ -11,4 +12,4 @@ export { useItemSse } from "./src/hooks/useItemSse";
|
|||||||
export { sanitizePayload } from "./src/utils/sanitize-payload";
|
export { sanitizePayload } from "./src/utils/sanitize-payload";
|
||||||
export type { FkResolver } from "./src/utils/sanitize-payload";
|
export type { FkResolver } from "./src/utils/sanitize-payload";
|
||||||
export type { FilterComponentProps } from "./src/context/useResource";
|
export type { FilterComponentProps } from "./src/context/useResource";
|
||||||
export type { SpecConfiguration, ResourceConfig, FieldConfig, FKFieldConfig, ResourceRelationship } from "./src/types";
|
export type { SpecConfiguration, ResourceConfig, FieldConfig, FKFieldConfig, ResourceRelationship, ProfileOperation, ProfileComponents, AuthConfig } from "./src/types";
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
import React 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 } 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";
|
||||||
import { ResourceList } from "./ResourceList";
|
import { ResourceList } from "./ResourceList";
|
||||||
import { ResourceForm } from "./ResourceForm";
|
import { ResourceForm } from "./ResourceForm";
|
||||||
import { ResourceDetail } from "./ResourceDetail";
|
import { ResourceDetail } from "./ResourceDetail";
|
||||||
import { ValidationAlert } from "./ValidationAlert";
|
import { ValidationAlert } from "./ValidationAlert";
|
||||||
|
import { getApi } from "../hooks/useApi";
|
||||||
|
|
||||||
interface AdminProps {
|
export interface AdminProps {
|
||||||
basePath: string;
|
basePath: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,7 +43,8 @@ export function Admin({ basePath }: AdminProps) {
|
|||||||
{warnings.length > 0 && <ValidationAlert errors={[]} warnings={warnings} />}
|
{warnings.length > 0 && <ValidationAlert errors={[]} warnings={warnings} />}
|
||||||
<Layout resources={topLevel} basePath={basePath}>
|
<Layout resources={topLevel} basePath={basePath}>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route index element={<Navigate to={`${basePath}/${topLevel[0].name}`} replace />} />
|
<Route index element={<Navigate to={`${basePath}/${topLevel[0]?.name ?? "profile"}`} replace />} />
|
||||||
|
|
||||||
{topLevel.map((r) => (
|
{topLevel.map((r) => (
|
||||||
<React.Fragment key={r.name}>
|
<React.Fragment key={r.name}>
|
||||||
<Route path={r.name} element={<ResourceList resource={r} basePath={basePath} />} />
|
<Route path={r.name} element={<ResourceList resource={r} basePath={basePath} />} />
|
||||||
@@ -60,3 +62,181 @@ export function Admin({ basePath }: AdminProps) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ProfileRoute {
|
||||||
|
path: string;
|
||||||
|
method: string;
|
||||||
|
operationId: string;
|
||||||
|
summary?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Derive a friendly profile route path from the operation's spec path.
|
||||||
|
* e.g. "/users/me" → "me", "/users/me/" → "me" */
|
||||||
|
function friendlyProfilePath(specPath: string): string {
|
||||||
|
return specPath.replace(/^\/[^/]+\/?/, "").replace(/\/+$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProfileRoutes() {
|
||||||
|
const { profileOperations, profileComponents } = useAppContext();
|
||||||
|
const ops = profileOperations;
|
||||||
|
const getOp = ops.find((o) => o.method === "GET");
|
||||||
|
const location = useLocation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
console.log("[ProfileRoutes] render pathname=%s ops=%o", location.pathname, ops.map(o => o.path));
|
||||||
|
|
||||||
|
// Redirect /:username to /me (only "me" and "me/edit" are valid)
|
||||||
|
const match = location.pathname.match(/^\/profile\/(.+)$/);
|
||||||
|
const username = match ? match[1] : "";
|
||||||
|
console.log("[ProfileRoutes] match=%o username=%s", match && match[1], username);
|
||||||
|
if (username !== "me" && username !== "me/edit") {
|
||||||
|
console.log("[ProfileRoutes] redirecting to /profile/me");
|
||||||
|
navigate("/profile/me", { replace: true });
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isEdit = username === "me/edit";
|
||||||
|
const mode = isEdit ? "edit" as const : "view" as const;
|
||||||
|
console.log("[ProfileRoutes] mode=%s", mode);
|
||||||
|
|
||||||
|
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 (
|
||||||
|
<ProfileComponentWrapper
|
||||||
|
Component={Component}
|
||||||
|
mode={mode}
|
||||||
|
operation={op}
|
||||||
|
getOperation={getOp}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProfileComponentWrapper({
|
||||||
|
Component,
|
||||||
|
mode,
|
||||||
|
operation,
|
||||||
|
getOperation,
|
||||||
|
}: {
|
||||||
|
Component: React.ComponentType<any>;
|
||||||
|
mode: "view" | "create" | "edit";
|
||||||
|
operation: { path: string; method: string };
|
||||||
|
getOperation?: { path: string };
|
||||||
|
}) {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [data, setData] = useState<any>(null);
|
||||||
|
const [loading, setLoading] = useState(mode !== "create");
|
||||||
|
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 fetchData = async () => {
|
||||||
|
console.log("[ProfileComponentWrapper] fetchData START path=%s", fetchPath);
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await getApi().get(fetchPath);
|
||||||
|
console.log("[ProfileComponentWrapper] fetchData SUCCESS", res.data);
|
||||||
|
setData(res.data);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.log("[ProfileComponentWrapper] fetchData ERROR", e.message, e.response?.status);
|
||||||
|
setError(e.response?.data?.detail ?? e.message ?? "Failed to load profile");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (mode !== "create") {
|
||||||
|
console.log("[ProfileComponentWrapper] useEffect calling fetchData");
|
||||||
|
fetchData();
|
||||||
|
}
|
||||||
|
}, [fetchPath, mode]);
|
||||||
|
|
||||||
|
const handleSubmit = async (formData: Record<string, any>) => {
|
||||||
|
console.log("[ProfileComponentWrapper] handleSubmit START");
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
if (mode === "create") {
|
||||||
|
await getApi().post(operation.path, formData);
|
||||||
|
} else {
|
||||||
|
await getApi()({ method: operation.method.toLowerCase(), url: operation.path, data: formData });
|
||||||
|
}
|
||||||
|
console.log("[ProfileComponentWrapper] handleSubmit SUCCESS, navigating to /profile/me");
|
||||||
|
const base = friendlyProfilePath(operation.path);
|
||||||
|
navigate(`/profile/${base}`, { replace: true });
|
||||||
|
} catch (e: any) {
|
||||||
|
console.log("[ProfileComponentWrapper] handleSubmit ERROR", e.message, e.response?.status);
|
||||||
|
setError(e.response?.data?.detail ?? e.message ?? "Operation failed");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading && !data && mode !== "create") {
|
||||||
|
return (
|
||||||
|
<Box sx={{ display: "flex", justifyContent: "center", mt: 4 }}>
|
||||||
|
<CircularProgress />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error && !data && mode !== "create") {
|
||||||
|
return (
|
||||||
|
<Box sx={{ maxWidth: 480, mx: "auto", mt: 4 }}>
|
||||||
|
<Alert severity="error">{error}</Alert>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const props: Record<string, any> = {};
|
||||||
|
|
||||||
|
if (mode === "view") {
|
||||||
|
if (data) {
|
||||||
|
props.name = data.name;
|
||||||
|
props.username = data.username;
|
||||||
|
props.email = data.email;
|
||||||
|
}
|
||||||
|
props.onEdit = () => navigate("/profile/me/edit");
|
||||||
|
props.loading = loading;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode === "create") {
|
||||||
|
props.defaultUsername = data?.username;
|
||||||
|
props.defaultEmail = data?.email;
|
||||||
|
props.onBack = () => window.history.back();
|
||||||
|
props.onSubmit = handleSubmit;
|
||||||
|
props.loading = loading;
|
||||||
|
props.error = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode === "edit") {
|
||||||
|
if (data) {
|
||||||
|
props.name = data.name;
|
||||||
|
props.username = data.username;
|
||||||
|
props.email = data.email;
|
||||||
|
}
|
||||||
|
props.onBack = () => window.history.back();
|
||||||
|
props.onSubmit = handleSubmit;
|
||||||
|
props.loading = loading;
|
||||||
|
props.error = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Component {...props} />;
|
||||||
|
}
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import { createContext, useContext } from "react";
|
import { createContext, useContext } from "react";
|
||||||
import type { ResourceConfig, SpecConfiguration, ValidationMessage } from "../types";
|
import type { AuthConfig, ProfileComponents, ProfileOperation, ResourceConfig, SpecConfiguration, ValidationMessage } from "../types";
|
||||||
|
|
||||||
export interface AppContextValue {
|
export interface AppContextValue {
|
||||||
config: SpecConfiguration;
|
config: SpecConfiguration;
|
||||||
resources: ResourceConfig[];
|
resources: ResourceConfig[];
|
||||||
|
profileOperations: ProfileOperation[];
|
||||||
|
profileComponents: ProfileComponents;
|
||||||
|
authConfig: AuthConfig;
|
||||||
schemas: Record<string, any>;
|
schemas: Record<string, any>;
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
errors: ValidationMessage[];
|
errors: ValidationMessage[];
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useEffect, useState, useMemo } from "react";
|
import React, { useEffect, useState, useMemo } from "react";
|
||||||
import type { SpecConfiguration, ResourceConfig, ValidationMessage } from "../types";
|
import type { AuthConfig, ProfileOperation, SpecConfiguration, ResourceConfig, ValidationMessage } from "../types";
|
||||||
import { AppContext } from "./AppContext";
|
import { AppContext } from "./AppContext";
|
||||||
import { loadSpec } from "../spec-loader";
|
import { loadSpec } from "../spec-loader";
|
||||||
import { validateSpec } from "../spec-validator";
|
import { validateSpec } from "../spec-validator";
|
||||||
@@ -11,13 +11,58 @@ interface AppProviderProps {
|
|||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function extractAuthConfig(spec: any): AuthConfig {
|
||||||
|
const bearer: Record<string, any> =
|
||||||
|
spec?.components?.securitySchemes?.bearerAuth ?? {};
|
||||||
|
return {
|
||||||
|
serverUrl: bearer["x-server-url"] ?? "",
|
||||||
|
loginPath: bearer["x-login-path"] ?? "/login",
|
||||||
|
registerPath: bearer["x-register-path"] ?? "/register",
|
||||||
|
logoutPath: bearer["x-logout-path"] ?? "/logout",
|
||||||
|
mePath: bearer["x-me-path"] ?? "/me",
|
||||||
|
introspectPath: bearer["x-introspect-path"] ?? "/introspect",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractProfileOperations(spec: any): ProfileOperation[] {
|
||||||
|
const ops: ProfileOperation[] = [];
|
||||||
|
const paths = spec.paths ?? {};
|
||||||
|
for (const [path, methods] of Object.entries<Record<string, any>>(paths)) {
|
||||||
|
for (const [method, operation] of Object.entries(methods)) {
|
||||||
|
if (method.startsWith("x-")) continue;
|
||||||
|
if (operation["x-profile"] === true) {
|
||||||
|
ops.push({
|
||||||
|
path,
|
||||||
|
method: method.toUpperCase(),
|
||||||
|
operationId: operation.operationId ?? "",
|
||||||
|
summary: operation.summary,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ops;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_AUTH_CONFIG: AuthConfig = {
|
||||||
|
serverUrl: "",
|
||||||
|
loginPath: "/login",
|
||||||
|
registerPath: "/register",
|
||||||
|
logoutPath: "/logout",
|
||||||
|
mePath: "/me",
|
||||||
|
introspectPath: "/introspect",
|
||||||
|
};
|
||||||
|
|
||||||
export function AppProvider({ specConfiguration, children }: AppProviderProps) {
|
export function AppProvider({ specConfiguration, children }: AppProviderProps) {
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [resources, setResources] = useState<ResourceConfig[]>([]);
|
const [resources, setResources] = useState<ResourceConfig[]>([]);
|
||||||
|
const [profileOperations, setProfileOperations] = useState<ProfileOperation[]>([]);
|
||||||
|
const [authConfig, setAuthConfig] = useState<AuthConfig>(DEFAULT_AUTH_CONFIG);
|
||||||
const [schemas, setSchemas] = useState<Record<string, any>>({});
|
const [schemas, setSchemas] = useState<Record<string, any>>({});
|
||||||
const [errors, setErrors] = useState<ValidationMessage[]>([]);
|
const [errors, setErrors] = useState<ValidationMessage[]>([]);
|
||||||
const [warnings, setWarnings] = useState<ValidationMessage[]>([]);
|
const [warnings, setWarnings] = useState<ValidationMessage[]>([]);
|
||||||
|
|
||||||
|
const profileComponents = specConfiguration.profileComponents ?? {};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
|
||||||
@@ -36,6 +81,8 @@ export function AppProvider({ specConfiguration, children }: AppProviderProps) {
|
|||||||
setErrors(errs);
|
setErrors(errs);
|
||||||
setWarnings(warns);
|
setWarnings(warns);
|
||||||
setSchemas(spec.components?.schemas ?? {});
|
setSchemas(spec.components?.schemas ?? {});
|
||||||
|
setProfileOperations(extractProfileOperations(spec));
|
||||||
|
setAuthConfig(extractAuthConfig(spec));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (errs.length === 0) {
|
if (errs.length === 0) {
|
||||||
@@ -72,12 +119,15 @@ export function AppProvider({ specConfiguration, children }: AppProviderProps) {
|
|||||||
() => ({
|
() => ({
|
||||||
config: specConfiguration,
|
config: specConfiguration,
|
||||||
resources,
|
resources,
|
||||||
|
profileOperations,
|
||||||
|
profileComponents,
|
||||||
|
authConfig,
|
||||||
schemas,
|
schemas,
|
||||||
loading,
|
loading,
|
||||||
errors,
|
errors,
|
||||||
warnings,
|
warnings,
|
||||||
}),
|
}),
|
||||||
[specConfiguration, resources, schemas, loading, errors, warnings]
|
[specConfiguration, resources, profileOperations, profileComponents, authConfig, schemas, loading, errors, warnings]
|
||||||
);
|
);
|
||||||
|
|
||||||
return React.createElement(AppContext.Provider, { value }, children);
|
return React.createElement(AppContext.Provider, { value }, children);
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
import axios, { AxiosInstance } from "axios";
|
import axios, { AxiosInstance } from "axios";
|
||||||
import { tokenStore } from "../../../react-auth/token";
|
|
||||||
|
|
||||||
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" },
|
||||||
@@ -24,11 +27,12 @@ export function initApi(baseUrl: string, getToken?: () => string | null): AxiosI
|
|||||||
apiClient.interceptors.response.use(
|
apiClient.interceptors.response.use(
|
||||||
(res) => res,
|
(res) => res,
|
||||||
(error) => {
|
(error) => {
|
||||||
if (error.response?.status === 401 && getToken) {
|
if (error.response?.status === 401) {
|
||||||
const currentToken = getToken();
|
console.log("[useApi] 401 from %s %s - dispatching auth:unauthorized", error.config?.method, error.config?.url);
|
||||||
if (currentToken) {
|
window.dispatchEvent(new CustomEvent("auth:unauthorized"));
|
||||||
tokenStore.clear();
|
_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 Promise.reject(error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,6 +45,11 @@ export function validateSpec(spec: OpenApiSpec, specConfig?: SpecConfiguration):
|
|||||||
const hasSSE = pathObj?.get?.["x-sse"] === true;
|
const hasSSE = pathObj?.get?.["x-sse"] === true;
|
||||||
if (hasSSE) continue;
|
if (hasSSE) continue;
|
||||||
|
|
||||||
|
// Skip paths where all operations are profile-only (x-profile: true).
|
||||||
|
const pathMethods = Object.entries(pathObj).filter(([k]) => !k.startsWith("x-") && k !== "parameters");
|
||||||
|
const allProfile = pathMethods.length > 0 && pathMethods.every(([, op]: any) => op["x-profile"] === true);
|
||||||
|
if (allProfile) continue;
|
||||||
|
|
||||||
if (isItemPath || isSubResource) {
|
if (isItemPath || isSubResource) {
|
||||||
const responseRef = getResponseSchemaRef(pathObj);
|
const responseRef = getResponseSchemaRef(pathObj);
|
||||||
if (responseRef) {
|
if (responseRef) {
|
||||||
|
|||||||
@@ -80,6 +80,13 @@ export function buildResourceConfigs(spec: OpenApiSpec): ResourceConfig[] {
|
|||||||
for (const path of sortedPaths) {
|
for (const path of sortedPaths) {
|
||||||
const segments = getSegments(path);
|
const segments = getSegments(path);
|
||||||
const pathObj = paths[path];
|
const pathObj = paths[path];
|
||||||
|
|
||||||
|
// Skip paths where ALL non-parameter operations are profile-only (x-profile: true).
|
||||||
|
// These are handled by Admin.tsx profile routes, not as CRUD resources.
|
||||||
|
const pathMethods = Object.entries(pathObj).filter(([k]) => !k.startsWith("x-") && k !== "parameters");
|
||||||
|
const allProfile = pathMethods.length > 0 && pathMethods.every(([, op]: any) => op["x-profile"] === true);
|
||||||
|
if (allProfile) continue;
|
||||||
|
|
||||||
const lastSeg = segments[segments.length - 1];
|
const lastSeg = segments[segments.length - 1];
|
||||||
const isItemPath = /^\{.*\}$/.test(lastSeg);
|
const isItemPath = /^\{.*\}$/.test(lastSeg);
|
||||||
const paramIdx = segments.findIndex(
|
const paramIdx = segments.findIndex(
|
||||||
|
|||||||
@@ -6,12 +6,37 @@ export interface ResourceConfiguration {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ProfileComponents {
|
||||||
|
create?: React.ComponentType<any>;
|
||||||
|
edit?: React.ComponentType<any>;
|
||||||
|
view?: React.ComponentType<any>;
|
||||||
|
}
|
||||||
|
|
||||||
export interface SpecConfiguration {
|
export interface SpecConfiguration {
|
||||||
specUrl: string;
|
specUrl: string;
|
||||||
baseApiUrl?: string;
|
baseApiUrl?: string;
|
||||||
title?: string;
|
title?: string;
|
||||||
getToken?: () => string | null;
|
getToken?: () => string | null;
|
||||||
resourceConfig?: Record<string, ResourceConfiguration>;
|
resourceConfig?: Record<string, ResourceConfiguration>;
|
||||||
|
profileComponents?: ProfileComponents;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Auth server config extracted from securitySchemes extensions. */
|
||||||
|
export interface AuthConfig {
|
||||||
|
serverUrl: string;
|
||||||
|
loginPath: string;
|
||||||
|
registerPath: string;
|
||||||
|
logoutPath: string;
|
||||||
|
mePath: string;
|
||||||
|
introspectPath: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Represents a single operation marked with `x-profile: true` in the spec. */
|
||||||
|
export interface ProfileOperation {
|
||||||
|
path: string;
|
||||||
|
method: string;
|
||||||
|
operationId: string;
|
||||||
|
summary?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ValidationMessage {
|
export interface ValidationMessage {
|
||||||
|
|||||||
@@ -134,7 +134,7 @@ export default function Header({
|
|||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
color="inherit"
|
color="inherit"
|
||||||
onClick={() => navigate("/admin/profile")}
|
onClick={() => navigate("/profile/me")}
|
||||||
sx={{ textTransform: "none", fontWeight: 500 }}
|
sx={{ textTransform: "none", fontWeight: 500 }}
|
||||||
>
|
>
|
||||||
{currentUser.username}
|
{currentUser.username}
|
||||||
@@ -151,7 +151,7 @@ export default function Header({
|
|||||||
<Button
|
<Button
|
||||||
color="inherit"
|
color="inherit"
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
onClick={() => navigate("/admin")}
|
onClick={() => navigate("/login")}
|
||||||
sx={{ textTransform: "none" }}
|
sx={{ textTransform: "none" }}
|
||||||
>
|
>
|
||||||
Login
|
Login
|
||||||
|
|||||||
131
src/main.jsx
131
src/main.jsx
@@ -4,7 +4,8 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|||||||
import {
|
import {
|
||||||
BrowserRouter,
|
BrowserRouter,
|
||||||
Routes,
|
Routes,
|
||||||
Route
|
Route,
|
||||||
|
useNavigate
|
||||||
} from "react-router-dom";
|
} from "react-router-dom";
|
||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
@@ -14,11 +15,8 @@ import {
|
|||||||
import Home from './Home';
|
import Home from './Home';
|
||||||
import FetchRequests from './FetchRequest/FetchRequestCreate';
|
import FetchRequests from './FetchRequest/FetchRequestCreate';
|
||||||
import FetchRequestDetail from './FetchRequest/FetchRequestDetail';
|
import FetchRequestDetail from './FetchRequest/FetchRequestDetail';
|
||||||
import { RequireAuth } from './RequireAuth';
|
import { AppProvider, useAppContext, Admin, ProfileRoutes } from '../react-openapi';
|
||||||
import { AppProvider, Admin } from '../react-openapi';
|
import { AuthProvider, AuthPage, useAuth, ProfileCreate, ProfileEdit, ProfileView } from "../react-auth";
|
||||||
import { Buffer } from 'buffer';
|
|
||||||
import process from 'process';
|
|
||||||
import { AuthProvider } from "../react-auth";
|
|
||||||
import Header from './Header';
|
import Header from './Header';
|
||||||
import Footer from './Footer';
|
import Footer from './Footer';
|
||||||
import AppTheme from './shared-theme/AppTheme';
|
import AppTheme from './shared-theme/AppTheme';
|
||||||
@@ -26,55 +24,104 @@ import { specConfiguration } from './openapi-config';
|
|||||||
|
|
||||||
const queryClient = new QueryClient();
|
const queryClient = new QueryClient();
|
||||||
|
|
||||||
window.Buffer = Buffer;
|
|
||||||
window.process = process;
|
|
||||||
|
|
||||||
const rootElement = document.getElementById('root');
|
const rootElement = document.getElementById('root');
|
||||||
const root = createRoot(rootElement);
|
const root = createRoot(rootElement);
|
||||||
|
|
||||||
const AUTH_BASE = import.meta.env.VITE_AUTH_BASE_URL;
|
// Wire profile components from react-auth into the spec-driven admin
|
||||||
|
specConfiguration.profileComponents = {
|
||||||
|
create: ProfileCreate,
|
||||||
|
edit: ProfileEdit,
|
||||||
|
view: ProfileView,
|
||||||
|
};
|
||||||
|
|
||||||
|
function LoginPage() {
|
||||||
|
const { login, register, loading, error, currentUser } = useAuth();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
return (
|
||||||
|
<AuthPage
|
||||||
|
mode="login"
|
||||||
|
onBack={() => navigate("/")}
|
||||||
|
onSwitchMode={() => navigate("/register")}
|
||||||
|
login={login}
|
||||||
|
register={register}
|
||||||
|
loading={loading}
|
||||||
|
error={error}
|
||||||
|
currentUser={currentUser}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function RegisterPage() {
|
||||||
|
const { login, register, loading, error, currentUser } = useAuth();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
return (
|
||||||
|
<AuthPage
|
||||||
|
mode="register"
|
||||||
|
onBack={() => navigate("/")}
|
||||||
|
onSwitchMode={() => navigate("/login")}
|
||||||
|
login={login}
|
||||||
|
register={register}
|
||||||
|
loading={loading}
|
||||||
|
error={error}
|
||||||
|
currentUser={currentUser}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const routerMapping = [
|
const routerMapping = [
|
||||||
{ path: "/", component: Home, headerTitle: "Home" },
|
{ path: "/", component: Home, headerTitle: "Home" },
|
||||||
{ path: "/home", component: Home, headerTitle: "Home" },
|
{ path: "/home", component: Home, headerTitle: "Home" },
|
||||||
|
{ path: "/login", component: LoginPage, headerTitle: "Login" },
|
||||||
|
{ path: "/register", component: RegisterPage, headerTitle: "Register" },
|
||||||
{ path: "/fetch-requests", component: FetchRequests, headerTitle: "Fetch Requests" },
|
{ path: "/fetch-requests", component: FetchRequests, headerTitle: "Fetch Requests" },
|
||||||
{ path: "/fetch-requests/:id", component: FetchRequestDetail, headerTitle: "Fetch Request" },
|
{ path: "/fetch-requests/:id", component: FetchRequestDetail, headerTitle: "Fetch Request" },
|
||||||
{ path: "/admin/*", component: Admin, headerTitle: "Admin" },
|
{ path: "/admin/*", component: Admin, headerTitle: "Admin" },
|
||||||
|
{ path: "/profile/*", component: ProfileRoutes, headerTitle: "Profile" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** Reads authConfig from AppProvider context and passes it to AuthProvider. */
|
||||||
|
function AppContent() {
|
||||||
|
const { authConfig } = useAppContext();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
return (
|
||||||
|
<AuthProvider authConfig={authConfig} onUnauthorized={() => navigate("/login")}>
|
||||||
|
<AppTheme>
|
||||||
|
<CssBaseline enableColorScheme />
|
||||||
|
<Header routerMapping={routerMapping} />
|
||||||
|
|
||||||
|
<Box sx={{ pb: 8 }}>
|
||||||
|
<Toolbar />
|
||||||
|
|
||||||
|
<Routes>
|
||||||
|
{routerMapping.map(({ path, component: Component }) => (
|
||||||
|
<Route
|
||||||
|
key={path}
|
||||||
|
path={path}
|
||||||
|
element={<Component basePath={path.replace(/\/\*$/, "")} />}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Routes>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Footer />
|
||||||
|
</AppTheme>
|
||||||
|
</AuthProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AppWithAuth() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
return (
|
||||||
|
<AppProvider specConfiguration={specConfiguration} onUnauthorized={() => navigate("/login")}>
|
||||||
|
<AppContent />
|
||||||
|
</AppProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
root.render(
|
root.render(
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<AppProvider specConfiguration={specConfiguration}>
|
<BrowserRouter>
|
||||||
<BrowserRouter>
|
<AppWithAuth />
|
||||||
<AuthProvider authBaseUrl={AUTH_BASE}>
|
</BrowserRouter>
|
||||||
<AppTheme>
|
|
||||||
<CssBaseline enableColorScheme />
|
|
||||||
<Header routerMapping={routerMapping} />
|
|
||||||
|
|
||||||
<Box sx={{ pb: 8 }}>
|
|
||||||
<Toolbar />
|
|
||||||
|
|
||||||
<Routes>
|
|
||||||
{routerMapping.map(({ path, component: Component }) => (
|
|
||||||
<Route
|
|
||||||
key={path}
|
|
||||||
path={path}
|
|
||||||
element={
|
|
||||||
path.startsWith("/admin") ? (
|
|
||||||
<RequireAuth><Component basePath="/admin" /></RequireAuth>
|
|
||||||
) : (
|
|
||||||
<Component />
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Routes>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Footer />
|
|
||||||
</AppTheme>
|
|
||||||
</AuthProvider>
|
|
||||||
</BrowserRouter>
|
|
||||||
</AppProvider>
|
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
);
|
);
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { SpecConfiguration } from "../react-openapi";
|
import type { SpecConfiguration } from "../react-openapi";
|
||||||
// import { tokenStore } from "../react-auth";
|
import { tokenStore } from "../react-auth";
|
||||||
|
|
||||||
const apiBase = import.meta.env.VITE_API_BASE_URL;
|
const apiBase = import.meta.env.VITE_API_BASE_URL;
|
||||||
|
|
||||||
@@ -7,10 +7,10 @@ export const specConfiguration: SpecConfiguration = {
|
|||||||
specUrl: `${apiBase}/openapi.json`,
|
specUrl: `${apiBase}/openapi.json`,
|
||||||
baseApiUrl: apiBase,
|
baseApiUrl: apiBase,
|
||||||
title: "Khata",
|
title: "Khata",
|
||||||
|
getToken: () => tokenStore.get(),
|
||||||
resourceConfig: {
|
resourceConfig: {
|
||||||
expenses: {
|
expenses: {
|
||||||
filterOptions: { mode: "client" },
|
filterOptions: { mode: "client" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
// getToken: () => tokenStore.get(),
|
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user