Merge branch 'cookies'
This commit is contained in:
+187
-201
@@ -1,217 +1,203 @@
|
||||
let idUsuarioSesion = null;
|
||||
|
||||
$(document).ready(function () {
|
||||
// Comprobar la sesión activa al cargar la página
|
||||
comprobarEstadoSesion();
|
||||
|
||||
// Evento Click: Login
|
||||
$('#botonAceptarLogin').on('click', function () {
|
||||
ejecutarLogin();
|
||||
});
|
||||
|
||||
// Permitir Submit con tecla Enter en el formulario de Login
|
||||
$('#formLogin').on('submit', function (e) {
|
||||
e.preventDefault();
|
||||
ejecutarLogin();
|
||||
});
|
||||
|
||||
// Evento Click: Registro
|
||||
$('#botonAceptarRegistro').on('click', function () {
|
||||
ejecutarRegistro();
|
||||
});
|
||||
|
||||
// Permitir Submit con tecla Enter en el formulario de Registro
|
||||
$('#formRegistro').on('submit', function (e) {
|
||||
e.preventDefault();
|
||||
ejecutarRegistro();
|
||||
});
|
||||
comprobarSesion();
|
||||
});
|
||||
|
||||
/**
|
||||
* Comprueba con el servidor si existe una sesión PHP
|
||||
*/
|
||||
function comprobarEstadoSesion() {
|
||||
$.ajax({
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: { orden: 'comprobarSesion' },
|
||||
success: function (respuesta) {
|
||||
if (respuesta.activa) {
|
||||
idUsuarioSesion = respuesta.usuario.idUsuario;
|
||||
renderizarCabeceraConSesion(respuesta.usuario);
|
||||
$('#colBotonJugar').removeClass('d-none');
|
||||
} else {
|
||||
renderizarCabeceraSinSesion();
|
||||
$('#colBotonJugar').addClass('d-none');
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
renderizarCabeceraSinSesion();
|
||||
}
|
||||
});
|
||||
// Función auxiliar para escapar texto HTML
|
||||
function escapeHTML(str) {
|
||||
return $("<div>")
|
||||
.text(str ?? "")
|
||||
.html();
|
||||
}
|
||||
|
||||
/**
|
||||
* Petición AJAX para iniciar sesión
|
||||
*/
|
||||
function ejecutarLogin() {
|
||||
let email = $('#loginEmail').val().trim();
|
||||
let contrasena = $('#loginPassword').val().trim();
|
||||
$('#errorLogin').text('');
|
||||
// Comprobar estado de sesión al cargar la página
|
||||
function comprobarSesion() {
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
data: { orden: "comprobarSesion" },
|
||||
}).done(function (respuesta) {
|
||||
try {
|
||||
if (typeof respuesta === "string") {
|
||||
respuesta = JSON.parse(respuesta);
|
||||
}
|
||||
|
||||
if (email === '' || contrasena === '') {
|
||||
$('#errorLogin').text('Por favor, rellena todos los campos.');
|
||||
return;
|
||||
}
|
||||
const contenedor = $("#contenedorUsuarioCabecera");
|
||||
contenedor.empty();
|
||||
|
||||
$.ajax({
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
orden: 'comprobarUsuario',
|
||||
email: email,
|
||||
contrasena: contrasena
|
||||
},
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
$('#errorLogin').text(respuesta.error);
|
||||
} else if (respuesta.exito) {
|
||||
$('#modalLogin').modal('hide');
|
||||
$('#formLogin')[0].reset();
|
||||
if (respuesta.activa && respuesta.usuario) {
|
||||
// Obtenemos la ruta del avatar o la de por defecto
|
||||
const avatarUrl =
|
||||
respuesta.usuario.avatar || "img/avatars/defaultProfile.jpeg";
|
||||
|
||||
// Cargar datos de la sesión actualizados
|
||||
comprobarEstadoSesion();
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
$('#errorLogin').text('Error al conectar con el servidor.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Petición AJAX para registrar un usuario
|
||||
*/
|
||||
function ejecutarRegistro() {
|
||||
let nombre = $('#regNombre').val().trim();
|
||||
let email = $('#regEmail').val().trim();
|
||||
let pass = $('#regPassword').val().trim();
|
||||
let passConfirm = $('#regPasswordConfirm').val().trim();
|
||||
|
||||
$('#errorRegistro').text('');
|
||||
|
||||
if (nombre === '' || email === '' || pass === '') {
|
||||
$('#errorRegistro').text('Todos los campos son obligatorios.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (pass !== passConfirm) {
|
||||
$('#errorRegistro').text('Las contraseñas no coinciden.');
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
orden: 'registrarUsuario',
|
||||
nombreUsuario: nombre,
|
||||
email: email,
|
||||
contrasena: pass
|
||||
},
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
$('#errorRegistro').text(respuesta.error);
|
||||
} else {
|
||||
$('#modalRegistro').modal('hide');
|
||||
$('#formRegistro')[0].reset();
|
||||
|
||||
// Autologin tras registrarse
|
||||
$('#loginEmail').val(email);
|
||||
$('#loginPassword').val(pass);
|
||||
ejecutarLogin();
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
$('#errorRegistro').text('Error al procesar el registro.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Petición AJAX para cerrar la sesión
|
||||
*/
|
||||
function cerrarSesion() {
|
||||
$.ajax({
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: { orden: 'cerrarSesion' },
|
||||
success: function () {
|
||||
renderizarCabeceraSinSesion();
|
||||
$('#colBotonJugar').addClass('d-none');
|
||||
|
||||
if (window.location.pathname.includes('perfil.php') || window.location.pathname.includes('buscadorSala.php')) {
|
||||
window.location.href = 'index.php';
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Renderiza la cabecera cuando HAY sesión iniciada
|
||||
*/
|
||||
function renderizarCabeceraConSesion(usuario) {
|
||||
//Mete el avatar en cabecera
|
||||
let avatarImg = (usuario.avatar && usuario.avatar !== '')
|
||||
? usuario.avatar
|
||||
: 'img/avatars/defaultProfile.jpeg';
|
||||
|
||||
// Refrescar avatar si se cambia
|
||||
let avatarConCacheBuster = avatarImg + '?v=' + new Date().getTime();
|
||||
|
||||
let html = `
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-outline-light dropdown-toggle d-flex align-items-center gap-2 rounded-pill px-3 py-1 fw-bold" type="button" id="userMenu" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<img src="${avatarConCacheBuster}" alt="Avatar" class="rounded-circle border" style="width: 32px; height: 32px; object-fit: cover;">
|
||||
<span>${escapeHtml(usuario.nombreUsuario)}</span>
|
||||
// Usuario autenticado: Mostrar Menú Dropdown con el avatar
|
||||
const htmlUsuario = `
|
||||
<div class="dropdown">
|
||||
<button class="btn user-dropdown-btn dropdown-toggle d-flex align-items-center gap-2"
|
||||
type="button" id="userDropdown" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<img src="${escapeHTML(avatarUrl)}" alt="Avatar" class="rounded-circle" style="width: 32px; height: 32px; object-fit: cover;">
|
||||
<span>${escapeHTML(respuesta.usuario.nombreUsuario)}</span>
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end shadow border-0 mt-2" aria-labelledby="userMenu">
|
||||
<li>
|
||||
<a class="dropdown-item py-2 fw-semibold" href="perfil.php">
|
||||
<i class="fa-solid fa-user me-2 text-primary"></i>Mi Perfil
|
||||
</a>
|
||||
</li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li>
|
||||
<button class="dropdown-item py-2 fw-semibold text-danger" onclick="cerrarSesion()">
|
||||
<i class="fa-solid fa-right-from-bracket me-2"></i>Cerrar Sesión
|
||||
</button>
|
||||
</li>
|
||||
<ul class="dropdown-menu dropdown-menu-end user-dropdown-menu" aria-labelledby="userDropdown">
|
||||
<li>
|
||||
<a class="dropdown-item d-flex align-items-center gap-2" href="perfil.php">
|
||||
<i class="fa-solid fa-user text-primary"></i> Perfil
|
||||
</a>
|
||||
</li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li>
|
||||
<a class="dropdown-item logout-item d-flex align-items-center gap-2" href="#" id="botonCerrarSesion">
|
||||
<i class="fa-solid fa-right-from-bracket"></i> Cerrar Sesión
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
`;
|
||||
$('#contenedorUsuarioCabecera').html(html);
|
||||
}
|
||||
</div>
|
||||
`;
|
||||
contenedor.html(htmlUsuario);
|
||||
|
||||
/**
|
||||
* Renderiza los botones en la cabecera cuando NO hay sesión (Iniciar sesión azul)
|
||||
*/
|
||||
function renderizarCabeceraSinSesion() {
|
||||
let html = `
|
||||
<button class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalLogin">
|
||||
<i class="fa-solid fa-right-to-bracket me-1"></i> Iniciar sesión
|
||||
</button>
|
||||
<button class="btn btn-success rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalRegistro">
|
||||
// Si estamos en la página principal, mostramos el botón JUGAR
|
||||
if ($("#colBotonJugar").length) {
|
||||
$("#colBotonJugar").removeClass("d-none");
|
||||
$("#colRanking")
|
||||
.removeClass("col-lg-8")
|
||||
.addClass("col-lg-7 col-xl-8");
|
||||
}
|
||||
} else {
|
||||
// No hay sesión: Mostrar botones de Login y Registro
|
||||
const htmlInvitado = `
|
||||
<button type="button" class="btn btn-kahoot-login rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#modalLogin">
|
||||
<i class="fa-solid fa-right-to-bracket me-1"></i> Iniciar Sesión
|
||||
</button>
|
||||
<button type="button" class="btn btn-kahoot-register rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#modalRegistro">
|
||||
<i class="fa-solid fa-user-plus me-1"></i> Registrarse
|
||||
</button>
|
||||
`;
|
||||
$('#contenedorUsuarioCabecera').html(html);
|
||||
</button>
|
||||
`;
|
||||
contenedor.html(htmlInvitado);
|
||||
|
||||
// Si estamos en la página principal, ocultamos el botón JUGAR
|
||||
if ($("#colBotonJugar").length) {
|
||||
$("#colBotonJugar").addClass("d-none");
|
||||
$("#colRanking")
|
||||
.removeClass("col-lg-7 col-xl-8")
|
||||
.addClass("col-lg-8");
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error al procesar la respuesta de la sesión:", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function escapeHtml(texto) {
|
||||
return $('<div>').text(texto).html();
|
||||
}
|
||||
// Registro
|
||||
$("#botonAceptarRegistro").click(function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
let nombreUsuario = $("#regNombre").val().trim();
|
||||
let email = $("#regEmail").val().trim();
|
||||
let contrasena = $("#regPassword").val();
|
||||
let contrasenaConfirmacion = $("#regPasswordConfirm").val();
|
||||
|
||||
$("#regNombre").removeClass("is-invalid");
|
||||
$("#regEmail").removeClass("is-invalid");
|
||||
$("#regPassword").removeClass("is-invalid");
|
||||
$("#regPasswordConfirm").removeClass("is-invalid");
|
||||
$("#errorRegistro").text("");
|
||||
|
||||
if (contrasena !== contrasenaConfirmacion) {
|
||||
$("#regPassword").addClass("is-invalid");
|
||||
$("#regPasswordConfirm").addClass("is-invalid");
|
||||
$("#errorRegistro").text("Las contraseñas no coinciden.");
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
data: {
|
||||
nombreUsuario: nombreUsuario,
|
||||
email: email,
|
||||
contrasena: contrasena,
|
||||
orden: "registrarUsuario",
|
||||
},
|
||||
}).done(function (respuesta) {
|
||||
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
$("#errorRegistro").text(respuesta.error);
|
||||
$("#regNombre").addClass("is-invalid");
|
||||
$("#regEmail").addClass("is-invalid");
|
||||
} else {
|
||||
$("#errorRegistro")
|
||||
.removeClass("text-danger")
|
||||
.addClass("text-success")
|
||||
.text(respuesta.exito);
|
||||
|
||||
$("#formRegistro")[0].reset();
|
||||
|
||||
setTimeout(function () {
|
||||
location.reload();
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Login
|
||||
$("#botonAceptarLogin").click(function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
let email = $("#loginEmail").val().trim();
|
||||
let contrasena = $("#loginPassword").val();
|
||||
let recuerdame = $("#recordar").is(":checked");
|
||||
|
||||
$("#loginEmail").removeClass("is-invalid");
|
||||
$("#loginPassword").removeClass("is-invalid");
|
||||
$("#errorLogin").text("");
|
||||
|
||||
if (email === "" || contrasena === "") {
|
||||
$("#errorLogin").text("Todos los campos son obligatorios.");
|
||||
if (email === "") $("#loginEmail").addClass("is-invalid");
|
||||
if (contrasena === "") $("#loginPassword").addClass("is-invalid");
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
data: {
|
||||
email: email,
|
||||
contrasena: contrasena,
|
||||
recuerdame: recuerdame,
|
||||
orden: "comprobarUsuario",
|
||||
},
|
||||
}).done(function (respuesta) {
|
||||
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
$("#loginEmail").addClass("is-invalid");
|
||||
$("#loginPassword").addClass("is-invalid");
|
||||
$("#errorLogin").text(respuesta.error);
|
||||
} else {
|
||||
location.reload();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Cerrar sesión
|
||||
$(document).on("click", "#botonCerrarSesion", function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
data: { orden: "cerrarSesion" },
|
||||
}).done(function (respuesta) {
|
||||
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
console.log(respuesta.error);
|
||||
} else {
|
||||
window.location.href = "index.php";
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user