Add admin user management with role-gated access

Backend:
- schemas/user.py: is_admin (validation_alias=is_superuser) on UserOut and
  UserAdminOut; UserAdminCreate extends UserCreate with is_admin flag
- deps.py: get_current_admin dependency — 403 for non-superusers
- routers/admin.py: GET/POST /api/admin/users, DELETE and PATCH /active per
  user; self-delete and self-deactivate blocked
- main.py: register /api/admin router
- scripts/seed.py: seed test user with is_superuser=True; promotes existing
  user if already created without the flag

Frontend:
- api/client.ts: UserData type with is_admin, admin API functions
- components/Nav.tsx: Admin link visible only when user.is_admin is true
- pages/AdminPage.tsx: user table with add-user form, delete, toggle active
- App.tsx: AdminRoute guard (403-redirects non-admins to /); /admin route

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
curo1305
2026-04-13 18:40:05 +02:00
parent d46191789d
commit 456681fdfa
11 changed files with 359 additions and 8 deletions
+15
View File
@@ -1,16 +1,30 @@
import { Routes, Route, Navigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { useAuth } from "./hooks/useAuth";
import { getMe } from "./api/client";
import LoginPage from "./pages/LoginPage";
import DashboardPage from "./pages/DashboardPage";
import ProfilePage from "./pages/ProfilePage";
import AppsPage from "./pages/AppsPage";
import SettingsPage from "./pages/SettingsPage";
import AdminPage from "./pages/AdminPage";
function PrivateRoute({ children }: { children: React.ReactNode }) {
const { token } = useAuth();
return token ? <>{children}</> : <Navigate to="/login" replace />;
}
function AdminRoute({ children }: { children: React.ReactNode }) {
const { token } = useAuth();
const { data: user, isLoading } = useQuery({ queryKey: ["me"], queryFn: getMe });
if (!token) return <Navigate to="/login" replace />;
// Wait for the me query before deciding — prevents a flash redirect
if (isLoading) return null;
if (!user?.is_admin) return <Navigate to="/" replace />;
return <>{children}</>;
}
export default function App() {
return (
<Routes>
@@ -20,6 +34,7 @@ export default function App() {
<Route path="/apps" element={<PrivateRoute><AppsPage /></PrivateRoute>} />
<Route path="/settings" element={<PrivateRoute><SettingsPage /></PrivateRoute>} />
<Route path="/profile" element={<PrivateRoute><ProfilePage /></PrivateRoute>} />
<Route path="/admin" element={<AdminRoute><AdminPage /></AdminRoute>} />
{/* Catch-all */}
<Route path="*" element={<Navigate to="/" replace />} />
+29 -1
View File
@@ -20,7 +20,35 @@ export const register = (email: string, password: string, full_name?: string) =>
api.post("/auth/register", { email, password, full_name }).then((r) => r.data);
// --- Users ---
export const getMe = () => api.get("/users/me").then((r) => r.data);
export interface UserData {
id: string;
email: string;
full_name: string | null;
is_active: boolean;
is_admin: boolean;
}
export const getMe = () => api.get<UserData>("/users/me").then((r) => r.data);
// --- Admin ---
export interface AdminUserCreate {
email: string;
password: string;
full_name?: string;
is_admin?: boolean;
}
export const adminGetUsers = () =>
api.get<UserData[]>("/admin/users").then((r) => r.data);
export const adminCreateUser = (data: AdminUserCreate) =>
api.post<UserData>("/admin/users", data).then((r) => r.data);
export const adminDeleteUser = (userId: string) =>
api.delete(`/admin/users/${userId}`);
export const adminToggleActive = (userId: string) =>
api.patch<UserData>(`/admin/users/${userId}/active`).then((r) => r.data);
// --- Profile ---
export interface ProfileData {
+4
View File
@@ -1,8 +1,11 @@
import { Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { useAuth } from "../hooks/useAuth";
import { getMe } from "../api/client";
export default function Nav() {
const { logout } = useAuth();
const { data: user } = useQuery({ queryKey: ["me"], queryFn: getMe });
return (
<nav style={{
@@ -15,6 +18,7 @@ export default function Nav() {
<Link to="/">Home</Link>
<Link to="/apps">Apps</Link>
<Link to="/settings">Settings</Link>
{user?.is_admin && <Link to="/admin">Admin</Link>}
<button
onClick={logout}
style={{ marginLeft: "auto", cursor: "pointer" }}
+177
View File
@@ -0,0 +1,177 @@
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
adminCreateUser,
adminDeleteUser,
adminGetUsers,
adminToggleActive,
getMe,
type AdminUserCreate,
type UserData,
} from "../api/client";
import Nav from "../components/Nav";
export default function AdminPage() {
const queryClient = useQueryClient();
const { data: me } = useQuery({ queryKey: ["me"], queryFn: getMe });
const { data: users = [], isLoading } = useQuery({
queryKey: ["admin-users"],
queryFn: adminGetUsers,
});
const [showForm, setShowForm] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
const [form, setForm] = useState<AdminUserCreate>({
email: "",
password: "",
full_name: "",
is_admin: false,
});
const createMutation = useMutation({
mutationFn: adminCreateUser,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["admin-users"] });
setShowForm(false);
setForm({ email: "", password: "", full_name: "", is_admin: false });
setFormError(null);
},
onError: (err: any) => {
const detail = err?.response?.data?.detail;
if (Array.isArray(detail)) {
setFormError(detail.map((d: any) => d.msg).join("; "));
} else {
setFormError(detail ?? "Failed to create user");
}
},
});
const deleteMutation = useMutation({
mutationFn: adminDeleteUser,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["admin-users"] }),
});
const toggleActiveMutation = useMutation({
mutationFn: adminToggleActive,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["admin-users"] }),
});
const handleDelete = (user: UserData) => {
if (!window.confirm(`Delete user "${user.email}"? This cannot be undone.`)) return;
deleteMutation.mutate(user.id);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
createMutation.mutate(form);
};
return (
<>
<Nav />
<div style={{ padding: 32, maxWidth: 800 }}>
<h1>User Management</h1>
{isLoading ? (
<p>Loading</p>
) : (
<table style={{ width: "100%", borderCollapse: "collapse", marginBottom: 24 }}>
<thead>
<tr style={{ borderBottom: "2px solid #ccc", textAlign: "left" }}>
<th style={{ padding: "8px 12px 8px 0" }}>Email</th>
<th style={{ padding: "8px 12px 8px 0" }}>Name</th>
<th style={{ padding: "8px 12px 8px 0" }}>Status</th>
<th style={{ padding: "8px 12px 8px 0" }}>Role</th>
<th style={{ padding: "8px 0" }}>Actions</th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id} style={{ borderBottom: "1px solid #eee" }}>
<td style={{ padding: "8px 12px 8px 0" }}>{u.email}</td>
<td style={{ padding: "8px 12px 8px 0" }}>{u.full_name ?? "—"}</td>
<td style={{ padding: "8px 12px 8px 0" }}>
{u.is_active ? "Active" : "Inactive"}
</td>
<td style={{ padding: "8px 12px 8px 0" }}>
{u.is_admin ? "Admin" : "User"}
</td>
<td style={{ padding: "8px 0", display: "flex", gap: 8 }}>
{u.id !== me?.id && (
<>
<button onClick={() => toggleActiveMutation.mutate(u.id)}>
{u.is_active ? "Deactivate" : "Activate"}
</button>
<button
onClick={() => handleDelete(u)}
style={{ color: "red" }}
>
Delete
</button>
</>
)}
{u.id === me?.id && (
<span style={{ color: "#999", fontSize: 13 }}>you</span>
)}
</td>
</tr>
))}
</tbody>
</table>
)}
{!showForm ? (
<button onClick={() => setShowForm(true)}>+ Add User</button>
) : (
<form onSubmit={handleSubmit} style={{ maxWidth: 400 }}>
<h2 style={{ marginTop: 0 }}>New User</h2>
<FormField label="Email" type="email" value={form.email}
onChange={(v) => setForm((f) => ({ ...f, email: v }))} required />
<FormField label="Full name" value={form.full_name ?? ""}
onChange={(v) => setForm((f) => ({ ...f, full_name: v }))} />
<FormField label="Password" type="password" value={form.password}
onChange={(v) => setForm((f) => ({ ...f, password: v }))} required />
<div style={{ marginBottom: 12, display: "flex", alignItems: "center", gap: 8 }}>
<input
id="is_admin"
type="checkbox"
checked={form.is_admin ?? false}
onChange={(e) => setForm((f) => ({ ...f, is_admin: e.target.checked }))}
/>
<label htmlFor="is_admin">Grant admin access</label>
</div>
{formError && <p style={{ color: "red" }}>{formError}</p>}
<div style={{ display: "flex", gap: 8 }}>
<button type="submit" disabled={createMutation.isPending}>
{createMutation.isPending ? "Creating…" : "Create"}
</button>
<button type="button" onClick={() => { setShowForm(false); setFormError(null); }}>
Cancel
</button>
</div>
</form>
)}
</div>
</>
);
}
function FormField({
label, value, onChange, type = "text", required = false,
}: {
label: string; value: string; onChange: (v: string) => void;
type?: string; required?: boolean;
}) {
return (
<div style={{ marginBottom: 12 }}>
<label style={{ display: "block", marginBottom: 4 }}>{label}</label>
<input
type={type}
value={value}
onChange={(e) => onChange(e.target.value)}
required={required}
style={{ width: "100%", padding: "6px 8px", boxSizing: "border-box" }}
/>
</div>
);
}