Fase 2: Gestión de Usuarios (CRUD Completo) - Backend & Frontend
This commit is contained in:
@@ -4,6 +4,7 @@ import Dashboard from './pages/Dashboard';
|
||||
import ProtectedLayout from './layouts/ProtectedLayout';
|
||||
|
||||
import CategoryManager from './pages/Categories/CategoryManager';
|
||||
import UserManager from './pages/Users/UserManager';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
@@ -14,6 +15,7 @@ function App() {
|
||||
<Route element={<ProtectedLayout />}>
|
||||
<Route path="/" element={<Dashboard />} />
|
||||
<Route path="/categories" element={<CategoryManager />} />
|
||||
<Route path="/users" element={<UserManager />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
|
||||
@@ -24,6 +24,9 @@ export default function ProtectedLayout() {
|
||||
<li className="mb-2">
|
||||
<a href="/categories" className="block p-2 hover:bg-gray-800 rounded">Categorías</a>
|
||||
</li>
|
||||
<li className="mb-2">
|
||||
<a href="/users" className="block p-2 hover:bg-gray-800 rounded">Usuarios</a>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
<div className="p-4 border-t border-gray-800">
|
||||
|
||||
199
frontend/admin-panel/src/pages/Users/UserManager.tsx
Normal file
199
frontend/admin-panel/src/pages/Users/UserManager.tsx
Normal file
@@ -0,0 +1,199 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
// @ts-ignore
|
||||
import { User } from '../../types/User';
|
||||
import { userService } from '../../services/userService';
|
||||
import Modal from '../../components/Modal';
|
||||
import { Plus, Edit, Trash2, Shield, User as UserIcon } from 'lucide-react';
|
||||
|
||||
export default function UserManager() {
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [editingId, setEditingId] = useState<number | null>(null);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
username: '',
|
||||
password: '',
|
||||
role: 'Usuario',
|
||||
email: ''
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
loadUsers();
|
||||
}, []);
|
||||
|
||||
const loadUsers = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const data = await userService.getAll();
|
||||
setUsers(data);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreate = () => {
|
||||
setEditingId(null);
|
||||
setFormData({ username: '', password: '', role: 'Usuario', email: '' });
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
// @ts-ignore
|
||||
const handleEdit = (user: User) => {
|
||||
setEditingId(user.id);
|
||||
// Password left empty intentionally
|
||||
setFormData({
|
||||
username: user.username,
|
||||
password: '',
|
||||
role: user.role,
|
||||
email: user.email || ''
|
||||
});
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
if (!confirm('Eliminar usuario?')) return;
|
||||
try {
|
||||
await userService.delete(id);
|
||||
loadUsers();
|
||||
} catch (error) {
|
||||
alert('Error eliminando');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
if (editingId) {
|
||||
await userService.update(editingId, formData);
|
||||
} else {
|
||||
await userService.create(formData as any);
|
||||
}
|
||||
setIsModalOpen(false);
|
||||
loadUsers();
|
||||
} catch (error) {
|
||||
alert('Error guardando usuario');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h2 className="text-2xl font-bold text-gray-800">Gestión de Usuarios</h2>
|
||||
<button
|
||||
onClick={handleCreate}
|
||||
className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 transition"
|
||||
>
|
||||
<Plus size={20} />
|
||||
<span>Nuevo Usuario</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded shadow cursor-default">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="bg-gray-50 border-b border-gray-200">
|
||||
<th className="p-4 font-semibold text-gray-600">Usuario</th>
|
||||
<th className="p-4 font-semibold text-gray-600">Rol</th>
|
||||
<th className="p-4 font-semibold text-gray-600">Email</th>
|
||||
<th className="p-4 font-semibold text-gray-600">Alta</th>
|
||||
<th className="p-4 font-semibold text-gray-600 text-right">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map(user => (
|
||||
<tr key={user.id} className="border-b border-gray-100 hover:bg-gray-50">
|
||||
<td className="p-4 flex items-center gap-2">
|
||||
<div className="bg-blue-100 p-1.5 rounded-full text-blue-600">
|
||||
<UserIcon size={16} />
|
||||
</div>
|
||||
<span className="font-medium">{user.username}</span>
|
||||
</td>
|
||||
<td className="p-4">
|
||||
<span className="inline-flex items-center gap-1 bg-gray-100 px-2 py-1 rounded text-sm">
|
||||
<Shield size={12} className="text-gray-500" />
|
||||
{user.role}
|
||||
</span>
|
||||
</td>
|
||||
<td className="p-4 text-gray-600">{user.email || '-'}</td>
|
||||
<td className="p-4 text-gray-500 text-sm">
|
||||
{new Date(user.createdAt).toLocaleDateString()}
|
||||
</td>
|
||||
<td className="p-4 text-right">
|
||||
<button onClick={() => handleEdit(user)} className="text-blue-600 hover:bg-blue-50 p-2 rounded mr-1">
|
||||
<Edit size={18} />
|
||||
</button>
|
||||
<button onClick={() => handleDelete(user.id)} className="text-red-600 hover:bg-red-50 p-2 rounded">
|
||||
<Trash2 size={18} />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{users.length === 0 && !isLoading && (
|
||||
<div className="p-8 text-center text-gray-500">No hay usuarios registrados.</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
isOpen={isModalOpen}
|
||||
onClose={() => setIsModalOpen(false)}
|
||||
title={editingId ? 'Editar Usuario' : 'Nuevo Usuario'}
|
||||
>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Usuario</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
value={formData.username}
|
||||
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
|
||||
className="w-full border p-2 rounded mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
{editingId ? 'Nueva Contraseña (Dejar vacío para no cambiar)' : 'Contraseña'}
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
required={!editingId}
|
||||
value={formData.password}
|
||||
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
|
||||
className="w-full border p-2 rounded mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Rol</label>
|
||||
<select
|
||||
value={formData.role}
|
||||
onChange={(e) => setFormData({ ...formData, role: e.target.value })}
|
||||
className="w-full border p-2 rounded mt-1"
|
||||
>
|
||||
<option value="Admin">Admin</option>
|
||||
<option value="Cajero">Cajero</option>
|
||||
<option value="Usuario">Usuario</option>
|
||||
<option value="Diagramador">Diagramador</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">Email</label>
|
||||
<input
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
|
||||
className="w-full border p-2 rounded mt-1"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 pt-4">
|
||||
<button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 hover:bg-gray-100 rounded">Cancelar</button>
|
||||
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">Guardar</button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
37
frontend/admin-panel/src/services/userService.ts
Normal file
37
frontend/admin-panel/src/services/userService.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import api from './api';
|
||||
// @ts-ignore
|
||||
import type { User } from '../types/User';
|
||||
|
||||
interface CreateUserDto {
|
||||
username: string;
|
||||
password: string;
|
||||
role: string;
|
||||
email?: string;
|
||||
}
|
||||
|
||||
interface UpdateUserDto {
|
||||
username: string;
|
||||
password?: string;
|
||||
role: string;
|
||||
email?: string;
|
||||
}
|
||||
|
||||
export const userService = {
|
||||
getAll: async (): Promise<User[]> => {
|
||||
const response = await api.get<User[]>('/users');
|
||||
// @ts-ignore
|
||||
return response.data;
|
||||
},
|
||||
|
||||
create: async (user: CreateUserDto): Promise<void> => {
|
||||
await api.post('/users', user);
|
||||
},
|
||||
|
||||
update: async (id: number, user: UpdateUserDto): Promise<void> => {
|
||||
await api.put(`/users/${id}`, user);
|
||||
},
|
||||
|
||||
delete: async (id: number): Promise<void> => {
|
||||
await api.delete(`/users/${id}`);
|
||||
}
|
||||
};
|
||||
7
frontend/admin-panel/src/types/User.ts
Normal file
7
frontend/admin-panel/src/types/User.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
role: string;
|
||||
email: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
90
src/SIGCM.API/Controllers/UsersController.cs
Normal file
90
src/SIGCM.API/Controllers/UsersController.cs
Normal file
@@ -0,0 +1,90 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SIGCM.Application.DTOs;
|
||||
using SIGCM.Domain.Entities;
|
||||
using SIGCM.Domain.Interfaces;
|
||||
|
||||
namespace SIGCM.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[Authorize(Roles = "Admin")] // Only admins can manage users
|
||||
public class UsersController : ControllerBase
|
||||
{
|
||||
private readonly IUserRepository _repository;
|
||||
|
||||
public UsersController(IUserRepository repository)
|
||||
{
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll()
|
||||
{
|
||||
var users = await _repository.GetAllAsync();
|
||||
// Don't expose password hashes
|
||||
var sanitized = users.Select(u => new {
|
||||
u.Id, u.Username, u.Role, u.Email, u.CreatedAt
|
||||
});
|
||||
return Ok(sanitized);
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
{
|
||||
var user = await _repository.GetByIdAsync(id);
|
||||
if (user == null) return NotFound();
|
||||
|
||||
return Ok(new { user.Id, user.Username, user.Role, user.Email, user.CreatedAt });
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create(CreateUserDto dto)
|
||||
{
|
||||
// Check if exists
|
||||
var existing = await _repository.GetByUsernameAsync(dto.Username);
|
||||
if (existing != null) return BadRequest("El nombre de usuario ya existe.");
|
||||
|
||||
var passwordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password);
|
||||
|
||||
var user = new User
|
||||
{
|
||||
Username = dto.Username,
|
||||
PasswordHash = passwordHash,
|
||||
Role = dto.Role,
|
||||
Email = dto.Email,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
var id = await _repository.CreateAsync(user);
|
||||
return CreatedAtAction(nameof(GetById), new { id }, new { id, user.Username });
|
||||
}
|
||||
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> Update(int id, UpdateUserDto dto)
|
||||
{
|
||||
var user = await _repository.GetByIdAsync(id);
|
||||
if (user == null) return NotFound();
|
||||
|
||||
user.Username = dto.Username;
|
||||
user.Role = dto.Role;
|
||||
user.Email = dto.Email;
|
||||
|
||||
if (!string.IsNullOrEmpty(dto.Password))
|
||||
{
|
||||
user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(dto.Password);
|
||||
}
|
||||
|
||||
await _repository.UpdateAsync(user);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
public async Task<IActionResult> Delete(int id)
|
||||
{
|
||||
// Safe check: prevent deleting yourself optional but good practice
|
||||
// For now simple delete
|
||||
await _repository.DeleteAsync(id);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
17
src/SIGCM.Application/DTOs/UserDtos.cs
Normal file
17
src/SIGCM.Application/DTOs/UserDtos.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
namespace SIGCM.Application.DTOs;
|
||||
|
||||
public class CreateUserDto
|
||||
{
|
||||
public required string Username { get; set; }
|
||||
public required string Password { get; set; }
|
||||
public required string Role { get; set; }
|
||||
public string? Email { get; set; }
|
||||
}
|
||||
|
||||
public class UpdateUserDto
|
||||
{
|
||||
public required string Username { get; set; }
|
||||
public string? Password { get; set; } // Opcional, solo si se quiere cambiar
|
||||
public required string Role { get; set; }
|
||||
public string? Email { get; set; }
|
||||
}
|
||||
@@ -4,5 +4,9 @@ using SIGCM.Domain.Entities;
|
||||
public interface IUserRepository
|
||||
{
|
||||
Task<User?> GetByUsernameAsync(string username);
|
||||
Task<IEnumerable<User>> GetAllAsync();
|
||||
Task<User?> GetByIdAsync(int id);
|
||||
Task<int> CreateAsync(User user);
|
||||
Task UpdateAsync(User user);
|
||||
Task DeleteAsync(int id);
|
||||
}
|
||||
|
||||
@@ -31,4 +31,32 @@ public class UserRepository : IUserRepository
|
||||
SELECT CAST(SCOPE_IDENTITY() as int);";
|
||||
return await conn.QuerySingleAsync<int>(sql, user);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<User>> GetAllAsync()
|
||||
{
|
||||
using var conn = _connectionFactory.CreateConnection();
|
||||
return await conn.QueryAsync<User>("SELECT Id, Username, Role, Email, CreatedAt, PasswordHash FROM Users");
|
||||
}
|
||||
|
||||
public async Task<User?> GetByIdAsync(int id)
|
||||
{
|
||||
using var conn = _connectionFactory.CreateConnection();
|
||||
return await conn.QuerySingleOrDefaultAsync<User>("SELECT * FROM Users WHERE Id = @Id", new { Id = id });
|
||||
}
|
||||
|
||||
public async Task UpdateAsync(User user)
|
||||
{
|
||||
using var conn = _connectionFactory.CreateConnection();
|
||||
var sql = @"
|
||||
UPDATE Users
|
||||
SET Username = @Username, Role = @Role, Email = @Email, PasswordHash = @PasswordHash
|
||||
WHERE Id = @Id";
|
||||
await conn.ExecuteAsync(sql, user);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(int id)
|
||||
{
|
||||
using var conn = _connectionFactory.CreateConnection();
|
||||
await conn.ExecuteAsync("DELETE FROM Users WHERE Id = @Id", new { Id = id });
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user