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
+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>
);
}