381 lines
19 KiB
JavaScript
381 lines
19 KiB
JavaScript
import React, { useState, useEffect } from 'react';
|
|
import { X, Plus, Edit2, Trash2, Loader, AlertCircle, CheckCircle, User, Mail, Shield } from 'lucide-react';
|
|
import { useAuth } from '../contexts/AuthContext';
|
|
|
|
const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';
|
|
|
|
export default function UserManagement({ onClose }) {
|
|
const { user: currentUser } = useAuth();
|
|
const [users, setUsers] = useState([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState(null);
|
|
const [showAddUser, setShowAddUser] = useState(false);
|
|
const [editingUser, setEditingUser] = useState(null);
|
|
const [formData, setFormData] = useState({
|
|
username: '',
|
|
email: '',
|
|
password: '',
|
|
role: 'viewer'
|
|
});
|
|
const [formError, setFormError] = useState('');
|
|
const [formSuccess, setFormSuccess] = useState('');
|
|
|
|
useEffect(() => {
|
|
fetchUsers();
|
|
}, []);
|
|
|
|
const fetchUsers = async () => {
|
|
try {
|
|
const response = await fetch(`${API_BASE}/users`, {
|
|
credentials: 'include'
|
|
});
|
|
if (!response.ok) throw new Error('Failed to fetch users');
|
|
const data = await response.json();
|
|
setUsers(data);
|
|
} catch (err) {
|
|
setError(err.message);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleSubmit = async (e) => {
|
|
e.preventDefault();
|
|
setFormError('');
|
|
setFormSuccess('');
|
|
|
|
try {
|
|
const url = editingUser
|
|
? `${API_BASE}/users/${editingUser.id}`
|
|
: `${API_BASE}/users`;
|
|
|
|
const method = editingUser ? 'PATCH' : 'POST';
|
|
|
|
const body = { ...formData };
|
|
if (editingUser && !body.password) {
|
|
delete body.password;
|
|
}
|
|
|
|
const response = await fetch(url, {
|
|
method,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
credentials: 'include',
|
|
body: JSON.stringify(body)
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (!response.ok) {
|
|
throw new Error(data.error || 'Operation failed');
|
|
}
|
|
|
|
setFormSuccess(editingUser ? 'User updated successfully' : 'User created successfully');
|
|
fetchUsers();
|
|
|
|
setTimeout(() => {
|
|
setShowAddUser(false);
|
|
setEditingUser(null);
|
|
setFormData({ username: '', email: '', password: '', role: 'viewer' });
|
|
setFormSuccess('');
|
|
}, 1500);
|
|
} catch (err) {
|
|
setFormError(err.message);
|
|
}
|
|
};
|
|
|
|
const handleEdit = (user) => {
|
|
setEditingUser(user);
|
|
setFormData({
|
|
username: user.username,
|
|
email: user.email,
|
|
password: '',
|
|
role: user.role
|
|
});
|
|
setShowAddUser(true);
|
|
setFormError('');
|
|
setFormSuccess('');
|
|
};
|
|
|
|
const handleDelete = async (userId) => {
|
|
if (!window.confirm('Are you sure you want to delete this user?')) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(`${API_BASE}/users/${userId}`, {
|
|
method: 'DELETE',
|
|
credentials: 'include'
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (!response.ok) {
|
|
throw new Error(data.error || 'Delete failed');
|
|
}
|
|
|
|
fetchUsers();
|
|
} catch (err) {
|
|
alert(err.message);
|
|
}
|
|
};
|
|
|
|
const handleToggleActive = async (user) => {
|
|
try {
|
|
const response = await fetch(`${API_BASE}/users/${user.id}`, {
|
|
method: 'PATCH',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
credentials: 'include',
|
|
body: JSON.stringify({ is_active: !user.is_active })
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (!response.ok) {
|
|
throw new Error(data.error || 'Update failed');
|
|
}
|
|
|
|
fetchUsers();
|
|
} catch (err) {
|
|
alert(err.message);
|
|
}
|
|
};
|
|
|
|
const getRoleBadgeColor = (role) => {
|
|
switch (role) {
|
|
case 'admin':
|
|
return 'bg-red-100 text-red-800';
|
|
case 'editor':
|
|
return 'bg-blue-100 text-blue-800';
|
|
default:
|
|
return 'bg-gray-100 text-gray-800';
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
|
|
<div className="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
|
|
<div className="p-6 border-b border-gray-200 flex justify-between items-center">
|
|
<div>
|
|
<h2 className="text-2xl font-bold text-gray-900">User Management</h2>
|
|
<p className="text-gray-600">Manage user accounts and permissions</p>
|
|
</div>
|
|
<button
|
|
onClick={onClose}
|
|
className="text-gray-400 hover:text-gray-600 p-2"
|
|
>
|
|
<X className="w-6 h-6" />
|
|
</button>
|
|
</div>
|
|
|
|
<div className="p-6 overflow-y-auto flex-1">
|
|
{!showAddUser && (
|
|
<button
|
|
onClick={() => {
|
|
setShowAddUser(true);
|
|
setEditingUser(null);
|
|
setFormData({ username: '', email: '', password: '', role: 'viewer' });
|
|
setFormError('');
|
|
setFormSuccess('');
|
|
}}
|
|
className="mb-6 px-4 py-2 bg-[#0476D9] text-white rounded-lg hover:bg-[#0360B8] transition-colors flex items-center gap-2 shadow-md"
|
|
>
|
|
<Plus className="w-5 h-5" />
|
|
Add User
|
|
</button>
|
|
)}
|
|
|
|
{showAddUser && (
|
|
<div className="mb-6 p-6 bg-gray-50 rounded-lg border border-gray-200">
|
|
<h3 className="text-lg font-semibold mb-4">
|
|
{editingUser ? 'Edit User' : 'Add New User'}
|
|
</h3>
|
|
|
|
{formError && (
|
|
<div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2">
|
|
<AlertCircle className="w-5 h-5 text-red-600" />
|
|
<span className="text-sm text-red-700">{formError}</span>
|
|
</div>
|
|
)}
|
|
|
|
{formSuccess && (
|
|
<div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg flex items-center gap-2">
|
|
<CheckCircle className="w-5 h-5 text-green-600" />
|
|
<span className="text-sm text-green-700">{formSuccess}</span>
|
|
</div>
|
|
)}
|
|
|
|
<form onSubmit={handleSubmit} className="space-y-4">
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
Username *
|
|
</label>
|
|
<div className="relative">
|
|
<User className="w-5 h-5 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2" />
|
|
<input
|
|
type="text"
|
|
required
|
|
value={formData.username}
|
|
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
|
|
className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0476D9] focus:border-transparent"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
Email *
|
|
</label>
|
|
<div className="relative">
|
|
<Mail className="w-5 h-5 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2" />
|
|
<input
|
|
type="email"
|
|
required
|
|
value={formData.email}
|
|
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
|
|
className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0476D9] focus:border-transparent"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
Password {editingUser ? '(leave blank to keep current)' : '*'}
|
|
</label>
|
|
<input
|
|
type="password"
|
|
required={!editingUser}
|
|
value={formData.password}
|
|
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
|
|
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0476D9] focus:border-transparent"
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
Role *
|
|
</label>
|
|
<div className="relative">
|
|
<Shield className="w-5 h-5 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2" />
|
|
<select
|
|
value={formData.role}
|
|
onChange={(e) => setFormData({ ...formData, role: e.target.value })}
|
|
className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0476D9] focus:border-transparent"
|
|
>
|
|
<option value="viewer">Viewer (read-only)</option>
|
|
<option value="editor">Editor (can add CVEs, upload docs)</option>
|
|
<option value="admin">Admin (full access)</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex gap-3 pt-2">
|
|
<button
|
|
type="submit"
|
|
className="px-4 py-2 bg-[#0476D9] text-white rounded-lg hover:bg-[#0360B8] transition-colors"
|
|
>
|
|
{editingUser ? 'Update User' : 'Create User'}
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setShowAddUser(false);
|
|
setEditingUser(null);
|
|
}}
|
|
className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
|
|
>
|
|
Cancel
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
)}
|
|
|
|
{loading ? (
|
|
<div className="text-center py-12">
|
|
<Loader className="w-8 h-8 text-[#0476D9] mx-auto animate-spin" />
|
|
<p className="text-gray-600 mt-2">Loading users...</p>
|
|
</div>
|
|
) : error ? (
|
|
<div className="text-center py-12">
|
|
<AlertCircle className="w-8 h-8 text-red-500 mx-auto" />
|
|
<p className="text-red-600 mt-2">{error}</p>
|
|
</div>
|
|
) : (
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full">
|
|
<thead>
|
|
<tr className="border-b border-gray-200">
|
|
<th className="text-left py-3 px-4 text-sm font-medium text-gray-700">User</th>
|
|
<th className="text-left py-3 px-4 text-sm font-medium text-gray-700">Role</th>
|
|
<th className="text-left py-3 px-4 text-sm font-medium text-gray-700">Status</th>
|
|
<th className="text-left py-3 px-4 text-sm font-medium text-gray-700">Last Login</th>
|
|
<th className="text-right py-3 px-4 text-sm font-medium text-gray-700">Actions</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{users.map((user) => (
|
|
<tr key={user.id} className="border-b border-gray-100 hover:bg-gray-50">
|
|
<td className="py-3 px-4">
|
|
<div>
|
|
<p className="font-medium text-gray-900">{user.username}</p>
|
|
<p className="text-sm text-gray-500">{user.email}</p>
|
|
</div>
|
|
</td>
|
|
<td className="py-3 px-4">
|
|
<span className={`px-2 py-1 rounded text-xs font-medium ${getRoleBadgeColor(user.role)}`}>
|
|
{user.role.charAt(0).toUpperCase() + user.role.slice(1)}
|
|
</span>
|
|
</td>
|
|
<td className="py-3 px-4">
|
|
<button
|
|
onClick={() => handleToggleActive(user)}
|
|
disabled={user.id === currentUser.id}
|
|
className={`px-2 py-1 rounded text-xs font-medium ${
|
|
user.is_active
|
|
? 'bg-green-100 text-green-800'
|
|
: 'bg-red-100 text-red-800'
|
|
} ${user.id === currentUser.id ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:opacity-80'}`}
|
|
>
|
|
{user.is_active ? 'Active' : 'Inactive'}
|
|
</button>
|
|
</td>
|
|
<td className="py-3 px-4 text-sm text-gray-500">
|
|
{user.last_login
|
|
? new Date(user.last_login).toLocaleString()
|
|
: 'Never'}
|
|
</td>
|
|
<td className="py-3 px-4">
|
|
<div className="flex justify-end gap-2">
|
|
<button
|
|
onClick={() => handleEdit(user)}
|
|
className="p-2 text-gray-600 hover:bg-gray-100 rounded"
|
|
title="Edit user"
|
|
>
|
|
<Edit2 className="w-4 h-4" />
|
|
</button>
|
|
<button
|
|
onClick={() => handleDelete(user.id)}
|
|
disabled={user.id === currentUser.id}
|
|
className={`p-2 text-red-600 hover:bg-red-50 rounded ${
|
|
user.id === currentUser.id ? 'opacity-50 cursor-not-allowed' : ''
|
|
}`}
|
|
title="Delete user"
|
|
>
|
|
<Trash2 className="w-4 h-4" />
|
|
</button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|