/******************************* auth.js *******************************/ // Utility to check if user is logged in window.isLoggedIn = function() { return window.auth.currentUser !== null; }; // Utility to get current username window.getCurrentUsername = function() { if (!window.auth.currentUser) return null; return window.auth.currentUser.displayName || window.auth.currentUser.email; }; // References const authTitle = document.getElementById("authTitle"); const loginForm = document.getElementById("loginForm"); const signupForm = document.getElementById("signupForm"); const showSignupLink = document.getElementById("showSignupLink"); const showLoginLink = document.getElementById("showLoginLink"); const loginUserEmail = document.getElementById("loginUserEmail"); const loginPassword = document.getElementById("loginPassword"); const loginBtnEl = document.getElementById("loginBtn"); const signupFirstName = document.getElementById("signupFirstName"); const signupLastName = document.getElementById("signupLastName"); const signupZip = document.getElementById("signupZip"); const signupDOB = document.getElementById("signupDOB"); const signupEmail = document.getElementById("signupEmail"); const signupUsername = document.getElementById("signupUsername"); const signupPassword = document.getElementById("signupPassword"); const signupBtnEl = document.getElementById("signupBtn"); const logoutBtn = document.getElementById("logoutBtn"); const profileEmail = document.getElementById("profileEmail"); const virtualBalanceSpan = document.getElementById("virtualBalance"); const totalBalanceSpan = document.getElementById("totalBalanceSpan"); const resetPasswordLink = document.getElementById("resetPasswordLink"); // Also references for Home auth section const homeShowLoginBtn = document.getElementById("homeShowLoginBtn"); const homeShowSignupBtn = document.getElementById("homeShowSignupBtn"); const homeAuthSection = document.getElementById("homeAuthSection"); const homeLoginForm = document.getElementById("homeLoginForm"); const homeSignupForm = document.getElementById("homeSignupForm"); const homeLoginBtn = document.getElementById("homeLoginBtn"); const homeSignupBtn = document.getElementById("homeSignupBtn"); const homeShowSignupLink = document.getElementById("homeShowSignupLink"); const homeShowLoginLink = document.getElementById("homeShowLoginLink"); // The dynamic Auth button in nav const authButton = document.getElementById("authButton"); // Basic email validation function isValidEmail(email) { const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return pattern.test(email.toLowerCase()); } // Show/hide forms showSignupLink.addEventListener("click", (e) => { e.preventDefault(); loginForm.style.display = "none"; signupForm.style.display = "block"; authTitle.textContent = "Sign Up"; }); showLoginLink.addEventListener("click", (e) => { e.preventDefault(); loginForm.style.display = "block"; signupForm.style.display = "none"; authTitle.textContent = "Login"; }); // For the Home page forms homeShowSignupLink.addEventListener("click", (e) => { e.preventDefault(); homeLoginForm.style.display = "none"; homeSignupForm.style.display = "block"; authTitle.textContent = "Sign Up"; }); homeShowLoginLink.addEventListener("click", (e) => { e.preventDefault(); homeLoginForm.style.display = "block"; homeSignupForm.style.display = "none"; authTitle.textContent = "Login"; }); homeShowLoginBtn.addEventListener("click", () => { window.showSection("account"); authTitle.textContent = "Login"; loginForm.style.display = "block"; signupForm.style.display = "none"; }); homeShowSignupBtn.addEventListener("click", () => { window.showSection("account"); authTitle.textContent = "Sign Up"; loginForm.style.display = "none"; signupForm.style.display = "block"; }); // Signup button logic signupBtnEl.addEventListener("click", async (e) => { e.preventDefault(); const fName = signupFirstName.value.trim(); const lName = signupLastName.value.trim(); const zip = signupZip.value.trim(); const dob = signupDOB.value.trim(); const email = signupEmail.value.trim(); const user = signupUsername.value.trim(); const pwd = signupPassword.value.trim(); const tradingPlan = signupForm.querySelector('input[name="signupTradingPlan"]:checked').value; if (!fName || !lName || !zip || !dob || !email || !user || !pwd) { alert("Please fill out all fields (First/Last Name, Zip Code, DOB, Email, Username, Password)."); return; } if (!isValidEmail(email)) { alert("Please enter a valid email."); return; } const users = JSON.parse(localStorage.getItem("pt_users") || "{}"); if (users[user]) { alert("Username is already taken. Please choose another one."); return; } try { await window.auth.createUserWithEmailAndPassword(email, pwd); const currentUser = window.auth.currentUser; if (currentUser) { await currentUser.updateProfile({ displayName: user }); } initializeUserData(user); users[user] = { email, firstName: fName, lastName: lName, zip, dob, tradingPlan }; localStorage.setItem("pt_users", JSON.stringify(users)); alert("Signup successful! You are now logged in."); signupFirstName.value = ""; signupLastName.value = ""; signupZip.value = ""; signupDOB.value = ""; signupEmail.value = ""; signupUsername.value = ""; signupPassword.value = ""; updateProfileUI(); updateAuthButton(); window.showSection("account"); if (window.handleGamification) { window.handleGamification(user); } } catch (error) { alert("Signup Error: " + error.message); } }); // Login button logic loginBtnEl.addEventListener("click", async (e) => { e.preventDefault(); let identifier = loginUserEmail.value.trim(); const pwd = loginPassword.value.trim(); if (!identifier || !pwd) { alert("Please enter valid credentials."); return; } let email = identifier; if (!isValidEmail(identifier)) { const users = JSON.parse(localStorage.getItem("pt_users") || "{}"); if (users[identifier]) { email = users[identifier].email; } else { alert("Username not found."); return; } } try { await window.auth.signInWithEmailAndPassword(email, pwd); const currentUser = window.auth.currentUser; const username = currentUser.displayName || email; initializeUserData(username); alert("Login successful!"); loginUserEmail.value = ""; loginPassword.value = ""; updateProfileUI(); updateAuthButton(); window.showSection("account"); if (window.handleGamification) { window.handleGamification(username); } } catch (error) { alert("Login Error: " + error.message); } }); // For Home page login homeLoginBtn.addEventListener("click", async () => { // This can be made identical or you can re-use the same logic above if needed // (In your original code, it appeared you'd just do signInWithEmailAndPassword here.) }); // For Home page signup homeSignupBtn.addEventListener("click", async () => { // Similar logic to signupBtnEl, can be duplicated if desired }); // Logout logoutBtn.addEventListener("click", () => { window.auth.signOut().then(() => { alert("You have been logged out."); updateAuthButton(); window.showSection("home"); updateProfileUI(); }).catch((error) => { alert("Logout Error: " + error.message); }); }); // Password reset resetPasswordLink.addEventListener("click", (e) => { e.preventDefault(); const identifier = prompt('Please enter your email or username for password reset:'); if (identifier) { let email = identifier; if (!isValidEmail(identifier)) { const users = JSON.parse(localStorage.getItem("pt_users") || "{}"); if (users[identifier]) { email = users[identifier].email; } else { alert("Username not found."); return; } } window.auth.sendPasswordResetEmail(email) .then(() => { alert('Password reset email sent!'); }) .catch((error) => { alert('Error: ' + error.message); }); } }); // init user data function initializeUserData(username) { if (!localStorage.getItem(`pt_balance_${username}`)) { localStorage.setItem(`pt_balance_${username}`, "100000"); } if (!localStorage.getItem(`pt_portfolio_${username}`)) { localStorage.setItem(`pt_portfolio_${username}`, JSON.stringify({})); } if (!localStorage.getItem(`pt_watchlist_${username}`)) { localStorage.setItem(`pt_watchlist_${username}`, JSON.stringify([])); } } // Update profile UI window.updateProfileUI = async function() { const user = window.auth.currentUser; if (!user) { if (window.toggleHomeAuthSection) { window.toggleHomeAuthSection(); } return; } if (window.toggleHomeAuthSection) { window.toggleHomeAuthSection(); } profileEmail.textContent = user.displayName || user.email; const username = user.displayName || user.email; const balanceKey = `pt_balance_${username}`; const currentBalance = parseFloat(localStorage.getItem(balanceKey) || "100000"); virtualBalanceSpan.textContent = "$" + currentBalance.toFixed(2); if (window.loadPositionsForCalc) { const positionsVal = await loadPositionsForCalc(username); const grandTotal = currentBalance + positionsVal; totalBalanceSpan.textContent = "$" + grandTotal.toFixed(2); } }; // Toggling home auth window.toggleHomeAuthSection = function() { if (window.isLoggedIn && window.isLoggedIn()) { homeAuthSection.style.display = "none"; const ctaButtons = document.querySelector('.cta-buttons'); if (ctaButtons) { ctaButtons.style.display = "none"; } } else { homeAuthSection.style.display = "block"; const ctaButtons = document.querySelector('.cta-buttons'); if (ctaButtons) { ctaButtons.style.display = "flex"; } } }; // Auth button in nav authButton.addEventListener("click", (e) => { e.preventDefault(); if (window.isLoggedIn && window.isLoggedIn()) { logoutBtn.click(); } else { window.showSection("account"); } }); // updateAuthButton logic window.updateAuthButton = function() { const adminNavLink = document.getElementById("adminNavLink"); const adminTradesNavLink = document.getElementById("adminTradesNavLink"); if (window.isLoggedIn && window.isLoggedIn()) { authButton.textContent = "Logout"; authButton.classList.remove("login-signup"); authButton.classList.add("logout"); if (window.getCurrentUsername() === "Opulentissimus") { adminNavLink.style.display = "block"; adminTradesNavLink.style.display = "block"; } else { adminNavLink.style.display = "none"; adminTradesNavLink.style.display = "none"; } } else { authButton.textContent = "Login / Sign Up"; authButton.classList.remove("logout"); authButton.classList.add("login-signup"); adminNavLink.style.display = "none"; adminTradesNavLink.style.display = "none"; } }; // Listen for auth state changes window.auth.onAuthStateChanged(async (user) => { if (user) { updateProfileUI(); updateAuthButton(); toggleHomeAuthSection(); if (accountSection.style.display === "block" || profileSection.style.display === "block") { window.showSection("account"); } if (window.getCurrentUsername() === "Opulentissimus") { const users = JSON.parse(localStorage.getItem("pt_users") || "{}"); if (!users["Opulentissimus"]) { users["Opulentissimus"] = { email: "papertradecommunications@gmail.com", firstName: "Admin", lastName: "User", zip: "00000", dob: "1970-01-01", tradingPlan: "Yes" }; localStorage.setItem("pt_users", JSON.stringify(users)); } } } else { updateProfileUI(); updateAuthButton(); toggleHomeAuthSection(); } });