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:
2026-07-17 21:00:47 +05:30
parent 6c720c390c
commit 5d34c51e98
17 changed files with 616 additions and 45 deletions

View File

@@ -1,14 +1,15 @@
import React from "react";
import React, { useEffect, useState } from "react";
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 { Layout } from "./Layout";
import { ResourceList } from "./ResourceList";
import { ResourceForm } from "./ResourceForm";
import { ResourceDetail } from "./ResourceDetail";
import { ValidationAlert } from "./ValidationAlert";
import { getApi } from "../hooks/useApi";
interface AdminProps {
export interface AdminProps {
basePath: string;
}
@@ -42,7 +43,8 @@ export function Admin({ basePath }: AdminProps) {
{warnings.length > 0 && <ValidationAlert errors={[]} warnings={warnings} />}
<Layout resources={topLevel} basePath={basePath}>
<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) => (
<React.Fragment key={r.name}>
<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} />;
}

View File

@@ -39,4 +39,4 @@ export function Layout({ resources, basePath, children }: LayoutProps) {
</Box>
</Box>
);
}
}

View File

@@ -107,4 +107,4 @@ export function SideMenu({ resources, basePath, mobileOpen, onClose }: SideMenuP
);
}
export { drawerWidth };
export { drawerWidth };

View File

@@ -1,9 +1,11 @@
import { createContext, useContext } from "react";
import type { ResourceConfig, SpecConfiguration, ValidationMessage } from "../types";
import type { ProfileComponents, ProfileOperation, ResourceConfig, SpecConfiguration, ValidationMessage } from "../types";
export interface AppContextValue {
config: SpecConfiguration;
resources: ResourceConfig[];
profileOperations: ProfileOperation[];
profileComponents: ProfileComponents;
schemas: Record<string, any>;
loading: boolean;
errors: ValidationMessage[];

View File

@@ -1,5 +1,5 @@
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 { loadSpec } from "../spec-loader";
import { validateSpec } from "../spec-validator";
@@ -11,13 +11,35 @@ interface AppProviderProps {
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) {
const [loading, setLoading] = useState(true);
const [resources, setResources] = useState<ResourceConfig[]>([]);
const [profileOperations, setProfileOperations] = useState<ProfileOperation[]>([]);
const [schemas, setSchemas] = useState<Record<string, any>>({});
const [errors, setErrors] = useState<ValidationMessage[]>([]);
const [warnings, setWarnings] = useState<ValidationMessage[]>([]);
const profileComponents = specConfiguration.profileComponents ?? {};
useEffect(() => {
let cancelled = false;
@@ -36,6 +58,7 @@ export function AppProvider({ specConfiguration, children }: AppProviderProps) {
setErrors(errs);
setWarnings(warns);
setSchemas(spec.components?.schemas ?? {});
setProfileOperations(extractProfileOperations(spec));
}
if (errs.length === 0) {
@@ -72,12 +95,14 @@ export function AppProvider({ specConfiguration, children }: AppProviderProps) {
() => ({
config: specConfiguration,
resources,
profileOperations,
profileComponents,
schemas,
loading,
errors,
warnings,
}),
[specConfiguration, resources, schemas, loading, errors, warnings]
[specConfiguration, resources, profileOperations, profileComponents, schemas, loading, errors, warnings]
);
return React.createElement(AppContext.Provider, { value }, children);

View File

@@ -1,5 +1,4 @@
import axios, { AxiosInstance } from "axios";
import { tokenStore } from "../../../react-auth/token";
let apiClient: AxiosInstance | null = null;
@@ -21,19 +20,6 @@ export function initApi(baseUrl: string, getToken?: () => string | null): AxiosI
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;
}

View File

@@ -45,6 +45,11 @@ export function validateSpec(spec: OpenApiSpec, specConfig?: SpecConfiguration):
const hasSSE = pathObj?.get?.["x-sse"] === true;
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) {
const responseRef = getResponseSchemaRef(pathObj);
if (responseRef) {

View File

@@ -80,6 +80,13 @@ export function buildResourceConfigs(spec: OpenApiSpec): ResourceConfig[] {
for (const path of sortedPaths) {
const segments = getSegments(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 isItemPath = /^\{.*\}$/.test(lastSeg);
const paramIdx = segments.findIndex(

View File

@@ -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 {
specUrl: string;
baseApiUrl?: string;
title?: string;
getToken?: () => string | null;
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 {