wire profile components, login/register routes, spec-driven auth
- src/main.jsx: add /login, /register, /profile/* routes; wire profileComponents from react-auth; pass basePath to Admin - src/Header.tsx: profile button nav to /profile/me; Login to /login - src/openapi-config.ts: wire getToken and profileComponents - react-auth local: sync ProfileCreate, ProfileEdit, ProfileView - react-openapi local: sync all auth + x-profile changes (AppProvider, Admin, ProfileRoutes, SideMenu, types, hooks, etc.)
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,12 @@
|
|||||||
export { AuthProvider, useAuth } from "./contexts";
|
export { AuthProvider, useAuth } 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 } 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 } 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,174 @@ 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");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<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) {
|
||||||
|
Component = profileComponents.view;
|
||||||
|
mode = "view";
|
||||||
|
} else if (op.method === "POST" && profileComponents.create) {
|
||||||
|
Component = profileComponents.create;
|
||||||
|
mode = "create";
|
||||||
|
} else if ((op.method === "PUT" || op.method === "PATCH") && profileComponents.edit) {
|
||||||
|
Component = profileComponents.edit;
|
||||||
|
mode = "edit";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Component || !mode) return null;
|
||||||
|
|
||||||
|
const routePath = mode === "view" ? basePath : `${basePath}/edit`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Route
|
||||||
|
key={op.operationId}
|
||||||
|
path={routePath}
|
||||||
|
element={
|
||||||
|
<ProfileComponentWrapper
|
||||||
|
Component={Component}
|
||||||
|
mode={mode}
|
||||||
|
operation={op}
|
||||||
|
getOperation={getOp}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Routes>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProfileComponentWrapper({
|
||||||
|
Component,
|
||||||
|
mode,
|
||||||
|
operation,
|
||||||
|
getOperation,
|
||||||
|
}: {
|
||||||
|
Component: React.ComponentType<any>;
|
||||||
|
mode: "view" | "create" | "edit";
|
||||||
|
operation: { path: string; method: string };
|
||||||
|
getOperation?: { path: string };
|
||||||
|
}) {
|
||||||
|
const [data, setData] = useState<any>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const fetchPath = getOperation?.path ?? operation.path;
|
||||||
|
|
||||||
|
const fetchData = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await getApi().get(fetchPath);
|
||||||
|
setData(res.data);
|
||||||
|
} catch (e: any) {
|
||||||
|
setError(e.response?.data?.detail ?? e.message ?? "Failed to load profile");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (mode !== "create") {
|
||||||
|
fetchData();
|
||||||
|
}
|
||||||
|
}, [fetchPath, mode]);
|
||||||
|
|
||||||
|
const handleSubmit = async (formData: Record<string, any>) => {
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
// Navigate back to the base profile view path
|
||||||
|
const base = friendlyProfilePath(operation.path);
|
||||||
|
window.history.pushState(null, "", `/${base}`);
|
||||||
|
window.location.reload();
|
||||||
|
} catch (e: any) {
|
||||||
|
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 = () => {
|
||||||
|
window.history.pushState(null, "", `/profile/me/edit`);
|
||||||
|
window.location.reload();
|
||||||
|
};
|
||||||
|
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,11 @@
|
|||||||
import { createContext, useContext } from "react";
|
import { createContext, useContext } from "react";
|
||||||
import type { ResourceConfig, SpecConfiguration, ValidationMessage } from "../types";
|
import type { 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;
|
||||||
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 { 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,35 @@ interface AppProviderProps {
|
|||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
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 [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 +58,7 @@ 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));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (errs.length === 0) {
|
if (errs.length === 0) {
|
||||||
@@ -72,12 +95,14 @@ export function AppProvider({ specConfiguration, children }: AppProviderProps) {
|
|||||||
() => ({
|
() => ({
|
||||||
config: specConfiguration,
|
config: specConfiguration,
|
||||||
resources,
|
resources,
|
||||||
|
profileOperations,
|
||||||
|
profileComponents,
|
||||||
schemas,
|
schemas,
|
||||||
loading,
|
loading,
|
||||||
errors,
|
errors,
|
||||||
warnings,
|
warnings,
|
||||||
}),
|
}),
|
||||||
[specConfiguration, resources, schemas, loading, errors, warnings]
|
[specConfiguration, resources, profileOperations, profileComponents, schemas, loading, errors, warnings]
|
||||||
);
|
);
|
||||||
|
|
||||||
return React.createElement(AppContext.Provider, { value }, children);
|
return React.createElement(AppContext.Provider, { value }, children);
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
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;
|
||||||
|
|
||||||
@@ -21,19 +20,6 @@ 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 && getToken) {
|
|
||||||
const currentToken = getToken();
|
|
||||||
if (currentToken) {
|
|
||||||
tokenStore.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Promise.reject(error);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return apiClient;
|
return apiClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,27 @@ 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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
|
||||||
|
|||||||
65
src/main.jsx
65
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, 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,20 +24,61 @@ 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;
|
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" },
|
||||||
];
|
];
|
||||||
|
|
||||||
root.render(
|
root.render(
|
||||||
@@ -59,13 +98,7 @@ root.render(
|
|||||||
<Route
|
<Route
|
||||||
key={path}
|
key={path}
|
||||||
path={path}
|
path={path}
|
||||||
element={
|
element={<Component basePath={path.replace(/\/\*$/, "")} />}
|
||||||
path.startsWith("/admin") ? (
|
|
||||||
<RequireAuth><Component basePath="/admin" /></RequireAuth>
|
|
||||||
) : (
|
|
||||||
<Component />
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
@@ -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