From aee6173ab5acf1cecc5c41043a30f9a43ab62298 Mon Sep 17 00:00:00 2001 From: gabrielroeder Date: Fri, 14 Jun 2024 15:23:43 -0300 Subject: [PATCH] =?UTF-8?q?feat:=20Reset=20de=20senha=20pela=20p=C3=A1gina?= =?UTF-8?q?=20de=20login=20(#117)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/README.md | 10 ++ src/assets/css/login.css | 3 +- src/assets/js/login.js | 128 ++++++++++++++++++++++++++ src/assets/js/pass-recovery.js | 90 ------------------ src/pages/login.html | 60 +++++++----- src/pages/pass-recovery.html | 163 --------------------------------- 6 files changed, 178 insertions(+), 276 deletions(-) delete mode 100644 src/assets/js/pass-recovery.js delete mode 100644 src/pages/pass-recovery.html diff --git a/src/README.md b/src/README.md index 471b23c..88bba51 100644 --- a/src/README.md +++ b/src/README.md @@ -269,6 +269,16 @@ O site em HTML/CSS/JS é um projeto estático. É necessário implantá-lo em um - Lógica para buscar os cartões de crédito cadastrados +### [0.1.31] - 12/06/2024 + +#### Atualizado + +- Lógica de reset da senha na página de Login + +#### Removido + +- Página de reset de senha + ### [0.1.31] - DD/MM/AAAA #### Adicionado/Atualizado/Removido diff --git a/src/assets/css/login.css b/src/assets/css/login.css index c5273fa..61295f4 100644 --- a/src/assets/css/login.css +++ b/src/assets/css/login.css @@ -67,7 +67,6 @@ form .formulario { - color: #343F4B; font-family: Lato; } @@ -79,7 +78,7 @@ form border-radius: 5px; width: 280px; height: 38px; - color: #8190A5; + color: #000000; font-family: Lato; font-size: 16px; text-align: left; diff --git a/src/assets/js/login.js b/src/assets/js/login.js index 1809aeb..2290000 100644 --- a/src/assets/js/login.js +++ b/src/assets/js/login.js @@ -3,6 +3,14 @@ const loginButton = document.getElementById("BtnEntrar"); const emailInput = document.getElementById("email_user"); const passwordInput = document.getElementById("senha_user"); +// variáveis globais de reset de senha +const modal = new bootstrap.Modal(document.querySelector('.modal')); +const emailInputReset = document.getElementById('email__reset'); +const passwordReset = document.getElementById('nova-senha__reset'); +const passwordResetConfirmation = document.getElementById('confirmar-senha__reset'); +const showPassword = document.getElementById('showPassword'); +const showConfirmPassword = document.getElementById('showConfirmPassword'); + function getUserFromLocalStorage(email) { return JSON.parse(localStorage.getItem(email)); } @@ -16,6 +24,7 @@ loginButton.addEventListener("click", function (event) { if (user && user.password === passwordInput.value) { alert("Login realizado com sucesso!"); window.location.href = "restaurantes.html"; + localStorage.setItem("lastEmail", emailInput.value); localStorage.setItem("userLoggedIn", "true"); } else if (user) { formSection.textContent = "Senha incorreta!"; @@ -42,3 +51,122 @@ loginButton.addEventListener("click", function (event) { return; } }); + +// Lógica para reset da senha + +/** + * Função que valida se um email é válido + * @param {string} email + * @returns + */ +function emailIsValid(email) { + return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); +} + +/** + * Função que adiciona a classe is-invalid ao input e exibe a mensagem de erro + */ +function showInputError(input, divError="", message="") { + input.classList.add("is-invalid"); + divError.textContent = message; +} + +/** + * Função que remove a classe is-invalid do input e limpa a mensagem de erro + */ +function clearInputError(input, divError="") { + input.classList.remove("is-invalid"); + divError.textContent = ""; +} + +/** + * Função que compara as senhas digitadas no formulário de reset de senha + */ +function comparePasswords() { + if (!(passwordReset.value === passwordResetConfirmation.value)) { + showInputError(passwordReset); + showInputError(passwordResetConfirmation, document.getElementById('password-error__reset'), 'As senhas não coincidem'); + } else { + passwordReset.classList.remove('is-invalid'); + passwordResetConfirmation.classList.remove('is-invalid'); + passwordReset.classList.add('is-valid'); + passwordResetConfirmation.classList.add('is-valid'); + document.getElementById('password-error__reset').textContent = ''; + } +} + +/** + * Função que atualiza a classe de um elemento + */ +function updateClass(element, add, className) { + if (add) { + element.classList.add(className); + } else { + element.classList.remove(className); + } +} + +/** + * Função que exibe a senha do input e muda o ícone do botão de exibir senha + */ +showPassword.addEventListener("click", function () { + const isPassword = passwordReset.type === "password"; + passwordReset.type = isPassword ? "text" : "password"; + updateClass(showPassword, isPassword, "bi-eye-slash"); + updateClass(showPassword, !isPassword, "bi-eye-fill"); +}); + + +/** + * Função que exibe a senha do input de confirmar senha e muda o ícone do botão de exibir senha + */ +showConfirmPassword.addEventListener("click", function () { + const isPassword = passwordResetConfirmation.type === "password"; + passwordResetConfirmation.type = isPassword ? "text" : "password"; + updateClass(showConfirmPassword, isPassword, "bi-eye-slash"); + updateClass(showConfirmPassword, !isPassword, "bi-eye-fill"); +}); + +document.getElementById('forgot-pass').addEventListener('click', function(e) { + e.preventDefault(); + + modal.show(); + + emailInputReset.addEventListener('input', function() { + const emailResetValue = emailInputReset.value; + if (emailResetValue === '') { + showInputError(emailInputReset, document.getElementById('email-error__reset'), 'O campo de email não pode estar vazio'); + } else if (!emailIsValid(emailResetValue)) { + showInputError(emailInputReset, document.getElementById('email-error__reset'), 'Email inválido'); + } else if (!getUserFromLocalStorage(emailResetValue)) { + showInputError(emailInputReset, document.getElementById('email-error__reset'), 'Email não cadastrado'); + } else { + emailInputReset.classList.remove('is-invalid'); + emailInputReset.classList.add('is-valid'); + } + }); + + passwordReset.addEventListener('input', comparePasswords); + passwordResetConfirmation.addEventListener('input', comparePasswords); +}); + +document.getElementById('forgot-pass-form').addEventListener('submit', function(event) { + event.preventDefault(); + + const invalidFields = this.querySelectorAll('.is-invalid'); + if (invalidFields.length > 0) { + alert("Corrija os erros antes de enviar o formulário!") + } else { + modal.hide() + + const email = emailInputReset.value; + const userInfo = JSON.parse(localStorage.getItem(email)); + userInfo.password = passwordReset.value; + localStorage.setItem(email, JSON.stringify(userInfo)); + this.querySelectorAll('.is-valid').forEach(function(element) { + element.classList.remove('is-valid'); + }); + this.reset(); + alert("Senha alterada com sucesso! Faça o login com as novas credenciais"); + } +}); diff --git a/src/assets/js/pass-recovery.js b/src/assets/js/pass-recovery.js deleted file mode 100644 index af52e41..0000000 --- a/src/assets/js/pass-recovery.js +++ /dev/null @@ -1,90 +0,0 @@ -const formSection = document.querySelector('.mensagem'); -const loginButton = document.getElementById('BtnEntrar'); -const emailInput = document.getElementById('email_user'); - -function createAlertMessage(alertType, message) { - return ` - `; -} - -function displayModalAlert(alertType, message) { - const modalAlerts = document.getElementById('modalAlerts'); - const alertMessage = createAlertMessage(alertType, message); - modalAlerts.innerHTML = alertMessage; -} - -function handleLogin(event) { - event.preventDefault(); - - const existingAlert = formSection.querySelector('.alert'); - if (existingAlert) { - formSection.removeChild(existingAlert); - } - - const email = emailInput.value.trim(); - - if (!email) { - const alertMessage = createAlertMessage('warning', 'O campo de e-mail não pode ser vazio.'); - formSection.insertAdjacentHTML('afterbegin', alertMessage); - return; - } - - let userInfo = JSON.parse(localStorage.getItem(email)); - - if (userInfo) { - const newPasswordModal = new bootstrap.Modal(document.getElementById('newPasswordModal')); - newPasswordModal.show(); - - const newPasswordInput = document.getElementById('newPassword'); - const confirmPasswordInput = document.getElementById('confirmPassword'); - - document.getElementById('saveNewPassword').addEventListener('click', function() { - const newPassword = newPasswordInput.value.trim(); - const confirmPassword = confirmPasswordInput.value.trim(); - - if (newPassword.length < 6) { - displayModalAlert('danger', 'A senha deve ter no mínimo 6 caracteres.'); - return; - } - - if (newPassword !== confirmPassword) { - displayModalAlert('danger', 'As senhas não coincidem. Tente novamente.'); - return; - } - - if (newPassword === userInfo.password) { - displayModalAlert('danger', 'A nova senha não pode ser igual à senha anterior.'); - return; - } - - // Atualizamos a senha no localStorage - userInfo.password = newPassword; - localStorage.setItem(email, JSON.stringify(userInfo)); - - displayModalAlert('success', 'Senha atualizada com sucesso.'); - - newPasswordModal.hide(); - const alertMessage = createAlertMessage('success', 'Senha atualizada com sucesso.'); - formSection.insertAdjacentHTML('afterbegin', alertMessage); - return; - - }); - - return; - } - - const alertMessage = createAlertMessage('danger', 'E-mail não encontrado. Cadastre uma conta.'); - formSection.insertAdjacentHTML('afterbegin', alertMessage); - return; -} - -loginButton.addEventListener('click', handleLogin); - -emailInput.addEventListener('keydown', function(event) { - if (event.key === 'Enter') { - handleLogin(event); - } -}); \ No newline at end of file diff --git a/src/pages/login.html b/src/pages/login.html index 3701c30..289cadd 100644 --- a/src/pages/login.html +++ b/src/pages/login.html @@ -3,15 +3,13 @@ - Login + - -
+
- - - - - - - \ No newline at end of file