Add admin role with user management (create/delete users)
First registered user becomes admin automatically. Admins see a "Manage Users" button in the dashboard header that opens a new /admin page for listing, creating, and deleting users. Backend enforces admin-only access on /admin/* routes. Startup migration adds the is_admin column to existing SQLite databases. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -3,11 +3,18 @@ import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
||||
import Login from './pages/Login';
|
||||
import Register from './pages/Register';
|
||||
import Dashboard from './pages/Dashboard';
|
||||
import AdminPage from './pages/AdminPage';
|
||||
|
||||
function PrivateRoute({ children }) {
|
||||
return localStorage.getItem('token') ? children : <Navigate to="/login" />;
|
||||
}
|
||||
|
||||
function AdminRoute({ children }) {
|
||||
if (!localStorage.getItem('token')) return <Navigate to="/login" />;
|
||||
if (localStorage.getItem('is_admin') !== 'true') return <Navigate to="/" />;
|
||||
return children;
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
@@ -15,6 +22,7 @@ export default function App() {
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/" element={<PrivateRoute><Dashboard /></PrivateRoute>} />
|
||||
<Route path="/admin" element={<AdminRoute><AdminPage /></AdminRoute>} />
|
||||
<Route path="*" element={<Navigate to="/" />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
const API = process.env.REACT_APP_API_URL || 'http://localhost:8000';
|
||||
|
||||
const styles = {
|
||||
app: { maxWidth: '900px', margin: '0 auto', padding: '1.5rem' },
|
||||
header: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' },
|
||||
title: { fontSize: '1.4rem', fontWeight: 700, color: '#f7931a' },
|
||||
backBtn: { background: 'none', border: '1px solid #555', color: '#aaa', borderRadius: '8px', padding: '0.4rem 1rem', cursor: 'pointer' },
|
||||
card: { background: '#1a1a1a', padding: '1.5rem', borderRadius: '12px', border: '1px solid #333', marginBottom: '1.5rem' },
|
||||
sectionTitle: { fontSize: '1rem', fontWeight: 700, color: '#f7931a', marginBottom: '1rem' },
|
||||
table: { width: '100%', borderCollapse: 'collapse' },
|
||||
th: { textAlign: 'left', color: '#888', fontSize: '0.8rem', paddingBottom: '0.5rem', borderBottom: '1px solid #333' },
|
||||
td: { padding: '0.6rem 0', borderBottom: '1px solid #222', color: '#e0e0e0', fontSize: '0.95rem' },
|
||||
adminBadge: { background: 'rgba(247,147,26,0.15)', color: '#f7931a', borderRadius: '4px', padding: '0.1rem 0.5rem', fontSize: '0.75rem', marginLeft: '0.5rem' },
|
||||
deleteBtn: { background: 'none', border: '1px solid #555', color: '#ff6b6b', borderRadius: '6px', padding: '0.25rem 0.75rem', cursor: 'pointer', fontSize: '0.85rem' },
|
||||
form: { display: 'flex', flexDirection: 'column', gap: '0.75rem' },
|
||||
row: { display: 'flex', gap: '0.75rem', flexWrap: 'wrap' },
|
||||
input: { flex: 1, minWidth: '140px', padding: '0.6rem 0.75rem', background: '#2a2a2a', border: '1px solid #444', borderRadius: '8px', color: '#e0e0e0', fontSize: '0.95rem' },
|
||||
checkLabel: { display: 'flex', alignItems: 'center', gap: '0.4rem', color: '#aaa', fontSize: '0.9rem', cursor: 'pointer' },
|
||||
submitBtn: { alignSelf: 'flex-start', padding: '0.6rem 1.5rem', background: '#f7931a', color: '#000', border: 'none', borderRadius: '8px', fontWeight: 700, cursor: 'pointer' },
|
||||
error: { color: '#ff6b6b', fontSize: '0.9rem' },
|
||||
success: { color: '#6bff8e', fontSize: '0.9rem' },
|
||||
};
|
||||
|
||||
export default function AdminPage() {
|
||||
const [users, setUsers] = useState([]);
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
const navigate = useNavigate();
|
||||
|
||||
const authHeaders = () => ({
|
||||
Authorization: `Bearer ${localStorage.getItem('token')}`,
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
|
||||
const fetchUsers = useCallback(async () => {
|
||||
const res = await fetch(`${API}/admin/users`, { headers: authHeaders() });
|
||||
if (res.status === 401 || res.status === 403) { navigate('/'); return; }
|
||||
setUsers(await res.json());
|
||||
}, [navigate]);
|
||||
|
||||
useEffect(() => { fetchUsers(); }, [fetchUsers]);
|
||||
|
||||
const handleCreate = async (e) => {
|
||||
e.preventDefault();
|
||||
setError(''); setSuccess('');
|
||||
const res = await fetch(`${API}/admin/users`, {
|
||||
method: 'POST',
|
||||
headers: authHeaders(),
|
||||
body: JSON.stringify({ username, password, is_admin: isAdmin }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
setError(data.detail || 'Failed to create user');
|
||||
return;
|
||||
}
|
||||
setSuccess(`User "${username}" created.`);
|
||||
setUsername(''); setPassword(''); setIsAdmin(false);
|
||||
fetchUsers();
|
||||
};
|
||||
|
||||
const handleDelete = async (id, name) => {
|
||||
if (!window.confirm(`Delete user "${name}"? This also deletes all their purchases.`)) return;
|
||||
await fetch(`${API}/admin/users/${id}`, { method: 'DELETE', headers: authHeaders() });
|
||||
fetchUsers();
|
||||
};
|
||||
|
||||
const currentUsername = (() => {
|
||||
try {
|
||||
const token = localStorage.getItem('token');
|
||||
return JSON.parse(atob(token.split('.')[1])).sub;
|
||||
} catch { return null; }
|
||||
})();
|
||||
|
||||
return (
|
||||
<div style={styles.app}>
|
||||
<div style={styles.header}>
|
||||
<div style={styles.title}>User Management</div>
|
||||
<button style={styles.backBtn} onClick={() => navigate('/')}>Back to Dashboard</button>
|
||||
</div>
|
||||
|
||||
<div style={styles.card}>
|
||||
<div style={styles.sectionTitle}>All Users</div>
|
||||
<table style={styles.table}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={styles.th}>Username</th>
|
||||
<th style={styles.th}>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map(u => (
|
||||
<tr key={u.id}>
|
||||
<td style={styles.td}>
|
||||
{u.username}
|
||||
{u.is_admin && <span style={styles.adminBadge}>admin</span>}
|
||||
</td>
|
||||
<td style={styles.td}>
|
||||
{u.username !== currentUsername && (
|
||||
<button style={styles.deleteBtn} onClick={() => handleDelete(u.id, u.username)}>Delete</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div style={styles.card}>
|
||||
<div style={styles.sectionTitle}>Create User</div>
|
||||
<form style={styles.form} onSubmit={handleCreate}>
|
||||
{error && <div style={styles.error}>{error}</div>}
|
||||
{success && <div style={styles.success}>{success}</div>}
|
||||
<div style={styles.row}>
|
||||
<input style={styles.input} placeholder="Username" value={username} onChange={e => setUsername(e.target.value)} required />
|
||||
<input style={styles.input} type="password" placeholder="Password" value={password} onChange={e => setPassword(e.target.value)} required />
|
||||
</div>
|
||||
<label style={styles.checkLabel}>
|
||||
<input type="checkbox" checked={isAdmin} onChange={e => setIsAdmin(e.target.checked)} />
|
||||
Admin
|
||||
</label>
|
||||
<button style={styles.submitBtn} type="submit">Create User</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import AddPurchase from '../components/AddPurchase';
|
||||
import PurchaseList from '../components/PurchaseList';
|
||||
import PortfolioChart from '../components/PortfolioChart';
|
||||
@@ -12,6 +12,8 @@ const styles = {
|
||||
header: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' },
|
||||
logo: { fontSize: '1.4rem', fontWeight: 700, color: '#f7931a' },
|
||||
logoutBtn: { background: 'none', border: '1px solid #555', color: '#aaa', borderRadius: '8px', padding: '0.4rem 1rem', cursor: 'pointer' },
|
||||
adminBtn: { background: 'none', border: '1px solid #f7931a', color: '#f7931a', borderRadius: '8px', padding: '0.4rem 1rem', cursor: 'pointer', textDecoration: 'none', fontSize: '1rem' },
|
||||
headerBtns: { display: 'flex', gap: '0.5rem', alignItems: 'center' },
|
||||
statsGrid: { display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '1rem', marginBottom: '1.5rem' },
|
||||
statCard: { background: '#1a1a1a', padding: '1rem', borderRadius: '12px', border: '1px solid #333' },
|
||||
statLabel: { color: '#888', fontSize: '0.8rem', marginBottom: '0.3rem' },
|
||||
@@ -68,8 +70,11 @@ export default function Dashboard() {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
const isAdmin = localStorage.getItem('is_admin') === 'true';
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('is_admin');
|
||||
navigate('/login');
|
||||
};
|
||||
|
||||
@@ -81,7 +86,10 @@ export default function Dashboard() {
|
||||
<div style={styles.app}>
|
||||
<div style={styles.header}>
|
||||
<div style={styles.logo}>₿ BTC Portfolio</div>
|
||||
<button style={styles.logoutBtn} onClick={handleLogout}>Logout</button>
|
||||
<div style={styles.headerBtns}>
|
||||
{isAdmin && <Link to="/admin" style={styles.adminBtn}>Manage Users</Link>}
|
||||
<button style={styles.logoutBtn} onClick={handleLogout}>Logout</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{stats && (
|
||||
|
||||
@@ -35,6 +35,7 @@ export default function Login() {
|
||||
}
|
||||
const data = await res.json();
|
||||
localStorage.setItem('token', data.access_token);
|
||||
localStorage.setItem('is_admin', data.is_admin ? 'true' : 'false');
|
||||
navigate('/');
|
||||
} catch {
|
||||
setError('Network error');
|
||||
|
||||
Reference in New Issue
Block a user