feat: agregar sistema de autenticación con usuarios y roles
- Agregar Login con autenticación por DNI y contraseña - Crear tabla de usuarios con roles (admin, médico, enfermero) - Implementar gestión de usuarios (CRUD) para administradores - Agregar control de permisos basado en roles en el menú - Persistir estado de sesión en backend - Inicializar usuario admin por defecto (DNI: 12345678, pass: admin123) - Corregir inicialización de arrays en el store para evitar errores al cargar estado
This commit is contained in:
@@ -0,0 +1,275 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useHospitalStore } from '@/hooks/useHospitalStore';
|
||||
import type { Usuario, RolUsuario } from '@/types';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Plus, Pencil, Trash2, UserCog, Mail, Shield } from 'lucide-react';
|
||||
|
||||
const API_BASE = 'http://localhost:4001/api';
|
||||
|
||||
export function GestionUsuarios() {
|
||||
const { logout, areas } = useHospitalStore();
|
||||
const [usuarios, setUsuarios] = useState<Usuario[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editUsuario, setEditUsuario] = useState<Usuario | null>(null);
|
||||
|
||||
const [form, setForm] = useState({
|
||||
apellido: '',
|
||||
nombre: '',
|
||||
dni: '',
|
||||
fechaNacimiento: '',
|
||||
email: '',
|
||||
rol: 'medico' as RolUsuario,
|
||||
matriculaProfesional: '',
|
||||
password: '',
|
||||
areaId: '',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchUsuarios();
|
||||
}, []);
|
||||
|
||||
const fetchUsuarios = async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/usuarios`);
|
||||
const data = await res.json();
|
||||
setUsuarios(data);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
setForm({
|
||||
apellido: '',
|
||||
nombre: '',
|
||||
dni: '',
|
||||
fechaNacimiento: '',
|
||||
email: '',
|
||||
rol: 'medico',
|
||||
matriculaProfesional: '',
|
||||
password: '',
|
||||
areaId: '',
|
||||
});
|
||||
setEditUsuario(null);
|
||||
};
|
||||
|
||||
const openEdit = (usu: Usuario) => {
|
||||
setEditUsuario(usu);
|
||||
setForm({
|
||||
apellido: usu.apellido,
|
||||
nombre: usu.nombre,
|
||||
dni: usu.dni,
|
||||
fechaNacimiento: usu.fechaNacimiento,
|
||||
email: usu.email,
|
||||
rol: usu.rol,
|
||||
matriculaProfesional: usu.matriculaProfesional || '',
|
||||
password: '',
|
||||
areaId: usu.areaId || '',
|
||||
});
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
try {
|
||||
if (editUsuario) {
|
||||
await fetch(`${API_BASE}/usuarios/${editUsuario.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
} else {
|
||||
await fetch(`${API_BASE}/usuarios`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
}
|
||||
setDialogOpen(false);
|
||||
resetForm();
|
||||
fetchUsuarios();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
alert('Error al guardar usuario');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (!confirm('¿Está seguro de eliminar este usuario?')) return;
|
||||
try {
|
||||
await fetch(`${API_BASE}/usuarios/${id}`, { method: 'DELETE' });
|
||||
fetchUsuarios();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
};
|
||||
|
||||
const getRolLabel = (rol: RolUsuario) => {
|
||||
switch (rol) {
|
||||
case 'admin': return 'Administrador';
|
||||
case 'medico': return 'Médico';
|
||||
case 'enfermero': return 'Enfermero';
|
||||
}
|
||||
};
|
||||
|
||||
const getAreaName = (areaId?: string) => {
|
||||
if (!areaId) return '-';
|
||||
return areas.find(a => a.id === areaId)?.nombre || '-';
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <div>Cargando...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold dark:text-white">Gestión de Usuarios</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">Administrar usuarios del sistema</p>
|
||||
</div>
|
||||
<Button onClick={() => { resetForm(); setDialogOpen(true); }}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Nuevo Usuario
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Apellido, Nombre</TableHead>
|
||||
<TableHead>DNI</TableHead>
|
||||
<TableHead>Rol</TableHead>
|
||||
<TableHead>Área</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Matrícula</TableHead>
|
||||
<TableHead>Acciones</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{usuarios.map((usu) => (
|
||||
<TableRow key={usu.id}>
|
||||
<TableCell className="font-medium">{usu.apellido}, {usu.nombre}</TableCell>
|
||||
<TableCell>{usu.dni}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={usu.rol === 'admin' ? 'default' : 'secondary'}>
|
||||
{getRolLabel(usu.rol)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{getAreaName(usu.areaId)}</TableCell>
|
||||
<TableCell>{usu.email}</TableCell>
|
||||
<TableCell>{usu.matriculaProfesional || '-'}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="ghost" size="icon" onClick={() => openEdit(usu)}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" onClick={() => handleDelete(usu.id)}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editUsuario ? 'Editar Usuario' : 'Nuevo Usuario'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Apellido</Label>
|
||||
<Input value={form.apellido} onChange={(e) => setForm({ ...form, apellido: e.target.value })} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Nombre</Label>
|
||||
<Input value={form.nombre} onChange={(e) => setForm({ ...form, nombre: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>DNI</Label>
|
||||
<Input value={form.dni} onChange={(e) => setForm({ ...form, dni: e.target.value })} disabled={!!editUsuario} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Fecha de Nacimiento</Label>
|
||||
<Input type="date" value={form.fechaNacimiento} onChange={(e) => setForm({ ...form, fechaNacimiento: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Email</Label>
|
||||
<Input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Rol</Label>
|
||||
<Select value={form.rol} onValueChange={(v) => setForm({ ...form, rol: v as RolUsuario })}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="admin">Administrador</SelectItem>
|
||||
<SelectItem value="medico">Médico</SelectItem>
|
||||
<SelectItem value="enfermero">Enfermero</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Matrícula Profesional</Label>
|
||||
<Input value={form.matriculaProfesional} onChange={(e) => setForm({ ...form, matriculaProfesional: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{form.rol === 'medico' && (
|
||||
<div className="space-y-2">
|
||||
<Label>Área Asignada</Label>
|
||||
<Select value={form.areaId} onValueChange={(v) => setForm({ ...form, areaId: v })}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccionar área" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{areas.map((area) => (
|
||||
<SelectItem key={area.id} value={area.id}>{area.nombre}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{editUsuario ? 'Nueva Contraseña (opcional)' : 'Contraseña'}</Label>
|
||||
<Input type="password" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 mt-4">
|
||||
<Button variant="outline" onClick={() => setDialogOpen(false)}>Cancelar</Button>
|
||||
<Button onClick={handleSubmit}>
|
||||
{editUsuario ? 'Actualizar' : 'Crear'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+51
-18
@@ -4,17 +4,18 @@ import {
|
||||
Users,
|
||||
ClipboardList,
|
||||
FileText,
|
||||
|
||||
Activity,
|
||||
Microscope,
|
||||
Menu,
|
||||
Sun,
|
||||
Moon
|
||||
Moon,
|
||||
LogOut,
|
||||
UserCog
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
|
||||
|
||||
import type { Vista } from '@/types';
|
||||
import type { Vista, Usuario } from '@/types';
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -28,27 +29,39 @@ interface LayoutProps {
|
||||
children: React.ReactNode;
|
||||
vistaActual: Vista;
|
||||
onCambiarVista: (vista: Vista) => void;
|
||||
currentUser: Usuario | null;
|
||||
onLogout: () => void;
|
||||
}
|
||||
|
||||
const menuItems: { vista: Vista; label: string; icon: React.ElementType }[] = [
|
||||
{ vista: 'dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
||||
{ vista: 'camas', label: 'Camas', icon: Bed },
|
||||
{ vista: 'pacientes', label: 'Pacientes', icon: Users },
|
||||
{ vista: 'internaciones', label: 'Internaciones', icon: ClipboardList },
|
||||
{ vista: 'evoluciones', label: 'Evoluciones', icon: FileText },
|
||||
//{ vista: 'laboratorios', label: 'Laboratorios', icon: FlaskConical },
|
||||
//{ vista: 'acidobase', label: 'Ácido-Base', icon: Activity },
|
||||
{ vista: 'cultivos', label: 'Cultivos', icon: Microscope },
|
||||
];
|
||||
|
||||
export function Layout({ children, vistaActual, onCambiarVista }: LayoutProps) {
|
||||
export function Layout({ children, vistaActual, onCambiarVista, currentUser, onLogout }: LayoutProps) {
|
||||
const { theme, setTheme } = useTheme()
|
||||
|
||||
const toggleDarkMode = () => setTheme(theme === "dark" ? "light" : "dark")
|
||||
|
||||
const menuItems: { vista: Vista; label: string; icon: React.ElementType; rolRequerido?: string }[] = [
|
||||
{ vista: 'dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
||||
{ vista: 'camas', label: 'Camas', icon: Bed, rolRequerido: 'medico' },
|
||||
{ vista: 'pacientes', label: 'Pacientes', icon: Users },
|
||||
{ vista: 'internaciones', label: 'Internaciones', icon: ClipboardList },
|
||||
{ vista: 'evoluciones', label: 'Evoluciones', icon: FileText },
|
||||
{ vista: 'cultivos', label: 'Cultivos', icon: Microscope },
|
||||
];
|
||||
|
||||
const filteredMenuItems = menuItems.filter(item => {
|
||||
const rol = currentUser?.rol as string | undefined;
|
||||
if (!item.rolRequerido) return true;
|
||||
if (rol === 'admin') return true;
|
||||
if (item.rolRequerido === 'medico' && (rol === 'medico' || rol === 'admin')) return true;
|
||||
return false;
|
||||
});
|
||||
|
||||
if ((currentUser?.rol as string) === 'admin') {
|
||||
filteredMenuItems.push({ vista: 'usuarios', label: 'Usuarios', icon: UserCog });
|
||||
}
|
||||
|
||||
const NavContent = () => (
|
||||
<nav className="flex flex-col gap-2">
|
||||
{menuItems.map((item) => {
|
||||
{filteredMenuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = vistaActual === item.vista;
|
||||
return (
|
||||
@@ -85,6 +98,10 @@ export function Layout({ children, vistaActual, onCambiarVista }: LayoutProps) {
|
||||
<NavContent />
|
||||
</div>
|
||||
<div className="p-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<div className="text-sm text-gray-600 dark:text-gray-300 mb-2">
|
||||
<div className="font-medium">{currentUser?.apellido}, {currentUser?.nombre}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 capitalize">{currentUser?.rol}</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
@@ -106,6 +123,9 @@ export function Layout({ children, vistaActual, onCambiarVista }: LayoutProps) {
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="icon" onClick={onLogout} title="Cerrar sesión">
|
||||
<LogOut className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="text-xs text-gray-400 dark:text-gray-500 text-center mt-2">
|
||||
v2.0
|
||||
@@ -132,11 +152,15 @@ export function Layout({ children, vistaActual, onCambiarVista }: LayoutProps) {
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-bold text-lg dark:text-white">Menú</span>
|
||||
</div>
|
||||
<div className="mt-2 text-sm text-gray-600 dark:text-gray-300">
|
||||
<div className="font-medium">{currentUser?.apellido}, {currentUser?.nombre}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 capitalize">{currentUser?.rol}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<NavContent />
|
||||
</div>
|
||||
<div className="p-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<div className="p-4 border-t border-gray-200 dark:border-gray-700 space-y-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -146,6 +170,15 @@ export function Layout({ children, vistaActual, onCambiarVista }: LayoutProps) {
|
||||
{theme === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
|
||||
<span className="text-sm">{theme === "dark" ? 'Modo Claro' : 'Modo Oscuro'}</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onLogout}
|
||||
className="w-full flex items-center justify-center gap-2 dark:text-white"
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
<span className="text-sm">Cerrar Sesión</span>
|
||||
</Button>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
@@ -159,4 +192,4 @@ export function Layout({ children, vistaActual, onCambiarVista }: LayoutProps) {
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useState } from 'react';
|
||||
import { useHospitalStore } from '@/hooks/useHospitalStore';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Shield, Lock, User } from 'lucide-react';
|
||||
|
||||
export function Login() {
|
||||
const { login } = useHospitalStore();
|
||||
const [dni, setDni] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await login(dni, password);
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Error de autenticación');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900 p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="mx-auto mb-4 w-16 h-16 bg-blue-600 rounded-full flex items-center justify-center">
|
||||
<Shield className="w-8 h-8 text-white" />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Sistema de Gestión Hospitalaria</CardTitle>
|
||||
<CardDescription>Ingrese sus credenciales para acceder</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="dni">DNI</Label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
id="dni"
|
||||
type="text"
|
||||
placeholder="Ingrese su DNI"
|
||||
value={dni}
|
||||
onChange={(e) => setDni(e.target.value)}
|
||||
className="pl-10"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Contraseña</Label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="Ingrese su contraseña"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="pl-10"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-600 dark:text-red-400 px-3 py-2 rounded-md text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading ? 'Ingresando...' : 'Ingresar'}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user