// ========================================== // AUTHENTICATION LOGIC (auth.js) // ========================================== $(document).ready(function () { // 1. Check auth immediately when the page loads checkAuth(); function checkAuth() { $.ajax({ url: "includes/api/api.php?action=check_auth", type: "GET", dataType: "json", success: function (res) { if (res.status === "success") { // Grab global variable from main.js currentUserRole = res.role; $("#currentUser").text(res.full_name); $("#loginSection").removeClass("d-flex").hide(); $("#topNavbar, #dashboardSection").fadeIn(); // SPA Initial Load: If no tab is active, load inventory if (!window.currentTab) { switchTab('inventory'); } } else if (res.status === "timeout"){ $("#topNavbar, #dashboardSection").hide(); $("#loginSection").addClass("d-flex").fadeIn(); showAlert("Your session has expired due to inactivity. Please log in again.", "warning"); allInventoryData = []; allPOData = []; window.currentTab = null; } else { $("#topNavbar, #dashboardSection").hide(); $("#loginSection").addClass("d-flex").fadeIn(); } }, error: function() { $("#topNavbar, #dashboardSection").hide(); $("#loginSection").addClass("d-flex").fadeIn(); } }); setInterval(function() { if ($("#dashboardSection").is(":visible")) { checkAuth(); } }, 5 * 60 * 1000); } // 2. Handle Login Form & Brute Force Cooldown Timer let loginCooldownInterval; $(document).on("submit", "#loginForm", function (e) { e.preventDefault(); let btn = $(this).find('button[type="submit"]'); let originalText = 'Sign In '; btn.prop('disabled', true).html(' Authenticating...'); $.ajax({ url: "includes/api/api.php?action=login", type: "POST", data: $(this).serialize(), dataType: "json", success: function (res) { if (res.status === "success") { btn.prop('disabled', false).html(originalText); $("#loginForm")[0].reset(); $("#loginAlert").empty(); checkAuth(); } else if (res.status === "locked") { let timeLeft = res.remaining; clearInterval(loginCooldownInterval); loginCooldownInterval = setInterval(function() { if (timeLeft <= 0) { clearInterval(loginCooldownInterval); btn.prop('disabled', false).html(originalText); $("#loginAlert").html(`