"use strict"; // Class definition var KTSigninGeneral = function () { // Elements var form; var submitButton; var validator; // Handle form var handleForm = function (e) { // Init form validation rules. For more info check the FormValidation plugin's official documentation:https://formvalidation.io/ validator = FormValidation.formValidation( form, { fields: { 'email': { validators: { notEmpty: { message: 'Email address is required' }, emailAddress: { message: 'The value is not a valid email address' } } }, 'password': { validators: { notEmpty: { message: 'The password is required' }, callback: { message: 'Please enter valid password', } } } }, plugins: { trigger: new FormValidation.plugins.Trigger(), bootstrap: new FormValidation.plugins.Bootstrap5({ rowSelector: '.fv-row', eleInvalidClass: '', eleValidClass: '' }) } } ); // Handle form submit submitButton.addEventListener('click', function (e) { // Prevent button default action e.preventDefault(); // Validate form validator.validate().then(function (status) { if (status === 'Valid') { // Show loading indication submitButton.setAttribute('data-kt-indicator', 'on'); // Disable button to avoid multiple click submitButton.disabled = true; // Simulate ajax request axios.post(submitButton.closest('form').getAttribute('action'), new FormData(form)) .then(function (response) { if (response.data && response.data.token) { localStorage.setItem('access_token', response.data.token); // Get the user's email from the form const email = form.querySelector('input[name="email"]').value; // Call the API login callback to create the session axios.post('/api-login-callback', { email: email }) .then(function (callbackResponse) { if (callbackResponse.data.status === 'success') { Swal.fire({ text: "Login realizado com sucesso!", icon: "success", buttonsStyling: false, confirmButtonText: "Ok, vamos lá!", customClass: { confirmButton: "btn btn-primary" } }).then(function (result) { if (result.isConfirmed) { window.location.href = '/index'; // Redireciona para o dashboard } }); } else { Swal.fire({ text: "Erro ao criar sessão no painel.", icon: "error", buttonsStyling: false, confirmButtonText: "Ok, entendi.", customClass: { confirmButton: "btn btn-primary" } }); } }) .catch(function (callbackError) { Swal.fire({ text: "Erro ao chamar o callback de login.", icon: "error", buttonsStyling: false, confirmButtonText: "Ok, entendi.", customClass: { confirmButton: "btn btn-primary" } }); }); } else { Swal.fire({ text: "Token de acesso não encontrado na resposta.", icon: "error", buttonsStyling: false, confirmButtonText: "Ok, entendi.", customClass: { confirmButton: "btn btn-primary" } }); } }) .catch(function (error) { let errorMessage = "Ocorreu um erro inesperado. Por favor, tente novamente."; if (error.response && error.response.data) { let dataMessage = error.response.data.message || "Erro ao processar a solicitação."; let dataErrors = error.response.data.errors; let specificErrors = []; if (dataErrors) { for (const key in dataErrors) { if (dataErrors.hasOwnProperty(key)) { specificErrors.push(dataErrors[key]); } } } errorMessage = dataMessage; if (specificErrors.length > 0) { errorMessage += "\r\n" + specificErrors.join("\r\n"); } } else if (error.request) { errorMessage = "Não foi possível se comunicar com o servidor. Verifique sua conexão."; } Swal.fire({ text: errorMessage, icon: "error", buttonsStyling: false, confirmButtonText: "Ok, entendi.", customClass: { confirmButton: "btn btn-primary" } }); }) .then(function () { // always executed // Hide loading indication submitButton.removeAttribute('data-kt-indicator'); // Enable button submitButton.disabled = false; }); } else { // Show error popup. For more info check the plugin's official documentation: https://sweetalert2.github.io/ Swal.fire({ text: "Sorry, looks like there are some errors detected, please try again.", icon: "error", buttonsStyling: false, confirmButtonText: "Ok, got it!", customClass: { confirmButton: "btn btn-primary" } }); } }); }); } // Public functions return { // Initialization init: function () { form = document.querySelector('#kt_sign_in_form'); submitButton = document.querySelector('#kt_sign_in_submit'); handleForm(); } }; }(); // On document ready KTUtil.onDOMContentLoaded(function () { KTSigninGeneral.init(); });