feat: implement user authentication and login modal, refactor backend
This commit is contained in:
554
web/frontend/src/views/Users.vue
Normal file
554
web/frontend/src/views/Users.vue
Normal file
@@ -0,0 +1,554 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-3 sm:gap-4 mb-4 sm:mb-6">
|
||||
<h1 class="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">Gestión de Usuarios</h1>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="isAuthenticated"
|
||||
@click="showChangePasswordModal = true"
|
||||
class="btn btn-secondary text-xs sm:text-sm"
|
||||
>
|
||||
🔑 Cambiar Mi Contraseña
|
||||
</button>
|
||||
<button @click="showAddModal = true" class="btn btn-primary text-xs sm:text-sm whitespace-nowrap">
|
||||
+ Crear Usuario
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="text-center py-12">
|
||||
<div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
|
||||
<p class="mt-2 text-gray-600 dark:text-gray-400">Cargando usuarios...</p>
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-4">
|
||||
<!-- Lista de usuarios -->
|
||||
<div v-if="users.length > 0" class="grid grid-cols-1 gap-4">
|
||||
<div
|
||||
v-for="user in users"
|
||||
:key="user.username"
|
||||
class="card hover:shadow-lg transition-shadow"
|
||||
>
|
||||
<div class="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
|
||||
<div class="flex-1">
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">{{ user.username }}</h3>
|
||||
<span
|
||||
v-if="user.username === currentUser"
|
||||
class="px-2 py-1 text-xs font-semibold rounded bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200"
|
||||
>
|
||||
Tú
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm text-gray-600 dark:text-gray-400">
|
||||
<div v-if="user.createdAt">
|
||||
<span class="font-medium">Creado:</span>
|
||||
<span class="ml-2">{{ formatDate(user.createdAt) }}</span>
|
||||
</div>
|
||||
<div v-if="user.createdBy">
|
||||
<span class="font-medium">Por:</span>
|
||||
<span class="ml-2">{{ user.createdBy }}</span>
|
||||
</div>
|
||||
<div v-if="user.updatedAt">
|
||||
<span class="font-medium">Actualizado:</span>
|
||||
<span class="ml-2">{{ formatDate(user.updatedAt) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
v-if="user.username === currentUser"
|
||||
@click="showChangePasswordModal = true"
|
||||
class="btn btn-secondary text-xs sm:text-sm"
|
||||
title="Cambiar contraseña"
|
||||
>
|
||||
🔑 Cambiar Contraseña
|
||||
</button>
|
||||
<button
|
||||
v-if="user.username !== currentUser"
|
||||
@click="confirmDeleteUser(user.username)"
|
||||
class="btn btn-danger text-xs sm:text-sm"
|
||||
title="Eliminar usuario"
|
||||
>
|
||||
🗑️ Eliminar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="card text-center py-12">
|
||||
<p class="text-gray-600 dark:text-gray-400 mb-4">No hay usuarios configurados</p>
|
||||
<button @click="showAddModal = true" class="btn btn-primary">
|
||||
+ Crear primer usuario
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal para crear/editar usuario -->
|
||||
<div
|
||||
v-if="showAddModal"
|
||||
class="fixed inset-0 bg-black bg-opacity-50 dark:bg-opacity-70 flex items-center justify-center z-50 p-4"
|
||||
@click.self="closeAddModal"
|
||||
>
|
||||
<div class="card max-w-md w-full max-h-[90vh] overflow-y-auto">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-xl font-bold text-gray-900 dark:text-gray-100">Crear Usuario</h2>
|
||||
<button
|
||||
@click="closeAddModal"
|
||||
class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
|
||||
title="Cerrar"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form @submit.prevent="handleCreateUser" class="space-y-4">
|
||||
<div v-if="addError" class="bg-red-100 dark:bg-red-900/30 border border-red-400 dark:border-red-700 text-red-700 dark:text-red-300 px-4 py-3 rounded">
|
||||
{{ addError }}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Nombre de usuario <span class="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
v-model="userForm.username"
|
||||
type="text"
|
||||
class="input"
|
||||
placeholder="nuevo_usuario"
|
||||
required
|
||||
minlength="3"
|
||||
autocomplete="username"
|
||||
/>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
Mínimo 3 caracteres
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Contraseña <span class="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
v-model="userForm.password"
|
||||
type="password"
|
||||
class="input"
|
||||
placeholder="••••••••"
|
||||
required
|
||||
minlength="6"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
Mínimo 6 caracteres
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Confirmar contraseña <span class="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
v-model="userForm.passwordConfirm"
|
||||
type="password"
|
||||
class="input"
|
||||
placeholder="••••••••"
|
||||
required
|
||||
minlength="6"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col-reverse sm:flex-row justify-end gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
type="button"
|
||||
@click="closeAddModal"
|
||||
class="btn btn-secondary text-sm sm:text-base"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
class="btn btn-primary text-sm sm:text-base"
|
||||
:disabled="loadingAction"
|
||||
>
|
||||
{{ loadingAction ? 'Creando...' : 'Crear Usuario' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal para cambiar contraseña -->
|
||||
<div
|
||||
v-if="showChangePasswordModal"
|
||||
class="fixed inset-0 bg-black bg-opacity-50 dark:bg-opacity-70 flex items-center justify-center z-50 p-4"
|
||||
@click.self="closeChangePasswordModal"
|
||||
>
|
||||
<div class="card max-w-md w-full">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-xl font-bold text-gray-900 dark:text-gray-100">Cambiar Contraseña</h2>
|
||||
<button
|
||||
@click="closeChangePasswordModal"
|
||||
class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
|
||||
title="Cerrar"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form @submit.prevent="handleChangePassword" class="space-y-4">
|
||||
<div v-if="passwordError" class="bg-red-100 dark:bg-red-900/30 border border-red-400 dark:border-red-700 text-red-700 dark:text-red-300 px-4 py-3 rounded">
|
||||
{{ passwordError }}
|
||||
</div>
|
||||
|
||||
<div v-if="passwordSuccess" class="bg-green-100 dark:bg-green-900/30 border border-green-400 dark:border-green-700 text-green-700 dark:text-green-300 px-4 py-3 rounded">
|
||||
{{ passwordSuccess }}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Contraseña actual <span class="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
v-model="passwordForm.currentPassword"
|
||||
type="password"
|
||||
class="input"
|
||||
placeholder="••••••••"
|
||||
required
|
||||
autocomplete="current-password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Nueva contraseña <span class="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
v-model="passwordForm.newPassword"
|
||||
type="password"
|
||||
class="input"
|
||||
placeholder="••••••••"
|
||||
required
|
||||
minlength="6"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
Mínimo 6 caracteres
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Confirmar nueva contraseña <span class="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
v-model="passwordForm.newPasswordConfirm"
|
||||
type="password"
|
||||
class="input"
|
||||
placeholder="••••••••"
|
||||
required
|
||||
minlength="6"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col-reverse sm:flex-row justify-end gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
type="button"
|
||||
@click="closeChangePasswordModal"
|
||||
class="btn btn-secondary text-sm sm:text-base"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
class="btn btn-primary text-sm sm:text-base"
|
||||
:disabled="loadingAction"
|
||||
>
|
||||
{{ loadingAction ? 'Cambiando...' : 'Cambiar Contraseña' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal de confirmación para eliminar -->
|
||||
<div
|
||||
v-if="userToDelete"
|
||||
class="fixed inset-0 bg-black bg-opacity-50 dark:bg-opacity-70 flex items-center justify-center z-50 p-4"
|
||||
@click.self="userToDelete = null"
|
||||
>
|
||||
<div class="card max-w-md w-full">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-xl font-bold text-gray-900 dark:text-gray-100">Confirmar Eliminación</h2>
|
||||
<button
|
||||
@click="userToDelete = null"
|
||||
class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
|
||||
title="Cerrar"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p class="text-gray-700 dark:text-gray-300 mb-4">
|
||||
¿Estás seguro de que deseas eliminar al usuario <strong>{{ userToDelete }}</strong>?
|
||||
</p>
|
||||
<p class="text-sm text-red-600 dark:text-red-400 mb-4">
|
||||
Esta acción no se puede deshacer.
|
||||
</p>
|
||||
|
||||
<div class="flex flex-col-reverse sm:flex-row justify-end gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
type="button"
|
||||
@click="userToDelete = null"
|
||||
class="btn btn-secondary text-sm sm:text-base"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
@click="handleDeleteUser"
|
||||
class="btn btn-danger text-sm sm:text-base"
|
||||
:disabled="loadingAction"
|
||||
>
|
||||
{{ loadingAction ? 'Eliminando...' : 'Eliminar Usuario' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, onUnmounted } from 'vue';
|
||||
import api from '../services/api';
|
||||
import authService from '../services/auth';
|
||||
|
||||
const users = ref([]);
|
||||
const loading = ref(true);
|
||||
const loadingAction = ref(false);
|
||||
const showAddModal = ref(false);
|
||||
const showChangePasswordModal = ref(false);
|
||||
const userToDelete = ref(null);
|
||||
const addError = ref('');
|
||||
const passwordError = ref('');
|
||||
const passwordSuccess = ref('');
|
||||
|
||||
const userForm = ref({
|
||||
username: '',
|
||||
password: '',
|
||||
passwordConfirm: '',
|
||||
});
|
||||
|
||||
const passwordForm = ref({
|
||||
currentPassword: '',
|
||||
newPassword: '',
|
||||
newPasswordConfirm: '',
|
||||
});
|
||||
|
||||
const isAuthenticated = computed(() => authService.hasCredentials());
|
||||
const currentUser = computed(() => {
|
||||
const creds = authService.getCredentials();
|
||||
return creds.username || '';
|
||||
});
|
||||
|
||||
function formatDate(dateString) {
|
||||
if (!dateString) return 'N/A';
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleString('es-ES', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
} catch (e) {
|
||||
return dateString;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const data = await api.getUsers();
|
||||
users.value = data.users || [];
|
||||
} catch (error) {
|
||||
console.error('Error cargando usuarios:', error);
|
||||
// El modal de login se manejará automáticamente desde App.vue
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateUser() {
|
||||
addError.value = '';
|
||||
loadingAction.value = true;
|
||||
|
||||
if (!userForm.value.username || !userForm.value.password || !userForm.value.passwordConfirm) {
|
||||
addError.value = 'Todos los campos son requeridos';
|
||||
loadingAction.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (userForm.value.username.length < 3) {
|
||||
addError.value = 'El nombre de usuario debe tener al menos 3 caracteres';
|
||||
loadingAction.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (userForm.value.password.length < 6) {
|
||||
addError.value = 'La contraseña debe tener al menos 6 caracteres';
|
||||
loadingAction.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (userForm.value.password !== userForm.value.passwordConfirm) {
|
||||
addError.value = 'Las contraseñas no coinciden';
|
||||
loadingAction.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.createUser({
|
||||
username: userForm.value.username,
|
||||
password: userForm.value.password,
|
||||
});
|
||||
|
||||
closeAddModal();
|
||||
await loadUsers();
|
||||
} catch (error) {
|
||||
console.error('Error creando usuario:', error);
|
||||
if (error.response?.data?.error) {
|
||||
addError.value = error.response.data.error;
|
||||
} else {
|
||||
addError.value = 'Error creando usuario. Intenta de nuevo.';
|
||||
}
|
||||
} finally {
|
||||
loadingAction.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleChangePassword() {
|
||||
passwordError.value = '';
|
||||
passwordSuccess.value = '';
|
||||
loadingAction.value = true;
|
||||
|
||||
if (!passwordForm.value.currentPassword || !passwordForm.value.newPassword || !passwordForm.value.newPasswordConfirm) {
|
||||
passwordError.value = 'Todos los campos son requeridos';
|
||||
loadingAction.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (passwordForm.value.newPassword.length < 6) {
|
||||
passwordError.value = 'La nueva contraseña debe tener al menos 6 caracteres';
|
||||
loadingAction.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (passwordForm.value.newPassword !== passwordForm.value.newPasswordConfirm) {
|
||||
passwordError.value = 'Las contraseñas no coinciden';
|
||||
loadingAction.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.changePassword({
|
||||
currentPassword: passwordForm.value.currentPassword,
|
||||
newPassword: passwordForm.value.newPassword,
|
||||
});
|
||||
|
||||
passwordSuccess.value = 'Contraseña actualizada correctamente';
|
||||
|
||||
// Actualizar credenciales guardadas si la nueva contraseña es para el usuario actual
|
||||
const creds = authService.getCredentials();
|
||||
if (creds.username === currentUser.value) {
|
||||
authService.saveCredentials(currentUser.value, passwordForm.value.newPassword);
|
||||
}
|
||||
|
||||
// Limpiar formulario después de 2 segundos
|
||||
setTimeout(() => {
|
||||
closeChangePasswordModal();
|
||||
}, 2000);
|
||||
} catch (error) {
|
||||
console.error('Error cambiando contraseña:', error);
|
||||
if (error.response?.data?.error) {
|
||||
passwordError.value = error.response.data.error;
|
||||
} else {
|
||||
passwordError.value = 'Error cambiando contraseña. Intenta de nuevo.';
|
||||
}
|
||||
} finally {
|
||||
loadingAction.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteUser() {
|
||||
if (!userToDelete.value) return;
|
||||
|
||||
loadingAction.value = true;
|
||||
try {
|
||||
await api.deleteUser(userToDelete.value);
|
||||
userToDelete.value = null;
|
||||
await loadUsers();
|
||||
} catch (error) {
|
||||
console.error('Error eliminando usuario:', error);
|
||||
alert(error.response?.data?.error || 'Error eliminando usuario. Intenta de nuevo.');
|
||||
} finally {
|
||||
loadingAction.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function confirmDeleteUser(username) {
|
||||
userToDelete.value = username;
|
||||
}
|
||||
|
||||
function closeAddModal() {
|
||||
showAddModal.value = false;
|
||||
addError.value = '';
|
||||
userForm.value = {
|
||||
username: '',
|
||||
password: '',
|
||||
passwordConfirm: '',
|
||||
};
|
||||
}
|
||||
|
||||
function closeChangePasswordModal() {
|
||||
showChangePasswordModal.value = false;
|
||||
passwordError.value = '';
|
||||
passwordSuccess.value = '';
|
||||
passwordForm.value = {
|
||||
currentPassword: '',
|
||||
newPassword: '',
|
||||
newPasswordConfirm: '',
|
||||
};
|
||||
}
|
||||
|
||||
function handleAuthLogout() {
|
||||
// Cuando el usuario se desconecta globalmente, limpiar datos
|
||||
users.value = [];
|
||||
showAddModal.value = false;
|
||||
showChangePasswordModal.value = false;
|
||||
userToDelete.value = null;
|
||||
addError.value = '';
|
||||
passwordError.value = '';
|
||||
passwordSuccess.value = '';
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadUsers();
|
||||
window.addEventListener('auth-logout', handleAuthLogout);
|
||||
// Escuchar evento de login exitoso para recargar usuarios
|
||||
window.addEventListener('auth-login', () => {
|
||||
loadUsers();
|
||||
});
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('auth-logout', handleAuthLogout);
|
||||
window.removeEventListener('auth-login', loadUsers);
|
||||
});
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user