/* * Green Horizon - Enhanced Authentication System with Email Verification * Complete authentication flow with email verification and proper redirects */ // Initialize Firebase const firebaseConfig = { apiKey: "AIzaSyB2zDTDlPGGY1-vofuJTG8sT5W1yfBBW3A", authDomain: "green-horizon-web.firebaseapp.com", projectId: "green-horizon-web", storageBucket: "green-horizon-web.firebasestorage.app", messagingSenderId: "873381929701", appId: "1:873381929701:web:d4d610bb64347bd56dea0c", measurementId: "G-T4F71XBRRY" }; firebase.initializeApp(firebaseConfig); const auth = firebase.auth(); const db = firebase.firestore(); // If you're using Firestore // Password validation function function validatePassword(password) { const minLength = 10; const hasUpperCase = /[A-Z]/.test(password); const hasLowerCase = /[a-z]/.test(password); const hasNumbers = /\d/.test(password); const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password); return { isValid: password.length >= minLength && hasUpperCase && hasLowerCase && hasNumbers && hasSpecialChar, minLength: password.length >= minLength, hasUpperCase, hasLowerCase, hasNumbers, hasSpecialChar }; } // Enhanced SIGN UP with email verification function signUp() { const email = document.getElementById("register-email").value; const password = document.getElementById("register-password").value; // Validate password const passwordValidation = validatePassword(password); if (!passwordValidation.isValid) { showNotification("Please ensure your password meets all requirements", "error"); return; } // Validate email if (!validateEmail(email)) { showNotification("Please enter a valid email address", "error"); return; } // Show loading state const submitButton = document.querySelector('#register-form button[type="submit"]'); if (submitButton) { submitButton.innerHTML = ' Creating Account...'; submitButton.disabled = true; } auth.createUserWithEmailAndPassword(email, password) .then((userCredential) => { const user = userCredential.user; // Send email verification return user.sendEmailVerification() .then(() => { // Store user data in Firestore (optional) return db.collection('users').doc(user.uid).set({ email: user.email, createdAt: firebase.firestore.FieldValue.serverTimestamp(), emailVerified: false, lastLogin: null }); }) .then(() => { // Show success message with instructions showNotification(`Verification email sent to ${user.email}. Please verify your email before logging in.`, "success"); // Redirect to login after a delay setTimeout(() => { window.location.href = "login.html?message=verify_email"; }, 5000); }); }) .catch((error) => { // Reset button state if (submitButton) { submitButton.innerHTML = 'Create Account'; submitButton.disabled = false; } // Handle specific error cases let errorMessage = error.message; if (error.code === 'auth/email-already-in-use') { errorMessage = "This email is already registered. Please try logging in or use a different email."; } else if (error.code === 'auth/invalid-email') { errorMessage = "The email address is not valid."; } else if (error.code === 'auth/operation-not-allowed') { errorMessage = "Email/password accounts are not enabled. Please contact support."; } else if (error.code === 'auth/weak-password') { errorMessage = "The password is too weak. Please use a stronger password."; } showNotification(errorMessage, "error"); }); } // Enhanced LOGIN with email verification check function login() { const email = document.getElementById("login-email").value; const password = document.getElementById("login-password").value; // Validate email if (!validateEmail(email)) { showNotification("Please enter a valid email address", "error"); return; } // Show loading state const submitButton = document.querySelector('#login-form button[type="submit"]'); if (submitButton) { submitButton.innerHTML = ' Logging In...'; submitButton.disabled = true; } auth.signInWithEmailAndPassword(email, password) .then((userCredential) => { const user = userCredential.user; if (user.emailVerified) { // Update last login in Firestore (optional) db.collection('users').doc(user.uid).update({ lastLogin: firebase.firestore.FieldValue.serverTimestamp() }); showNotification(`Login successful! Welcome back, ${user.email}`, "success"); // Redirect to dashboard after a short delay setTimeout(() => { window.location.href = "../dashboard/index.html"; }, 1500); } else { // Reset button state if (submitButton) { submitButton.innerHTML = 'Log In'; submitButton.disabled = false; } showNotification("Please verify your email before logging in. Check your spam folder if you can't find the verification email.", "warning"); // Option to resend verification email if (confirm("Would you like us to resend the verification email?")) { user.sendEmailVerification() .then(() => { showNotification("Verification email sent. Please check your inbox.", "success"); }) .catch((error) => { showNotification("Error sending verification email: " + error.message, "error"); }); } } }) .catch((error) => { // Reset button state if (submitButton) { submitButton.innerHTML = 'Log In'; submitButton.disabled = false; } // Handle specific error cases let errorMessage = error.message; if (error.code === 'auth/user-not-found') { errorMessage = "No account found with this email. Please sign up first."; } else if (error.code === 'auth/wrong-password') { errorMessage = "Incorrect password. Please try again or reset your password."; } else if (error.code === 'auth/invalid-email') { errorMessage = "The email address is not valid."; } else if (error.code === 'auth/user-disabled') { errorMessage = "This account has been disabled. Please contact support."; } showNotification(errorMessage, "error"); }); } // Enhanced FORGOT PASSWORD with validation function resetPassword() { const email = document.getElementById("forgot-email").value; // Validate email if (!validateEmail(email)) { showNotification("Please enter a valid email address", "error"); return; } // Show loading state const submitButton = document.querySelector('#forgot-password-form button[type="submit"]'); if (submitButton) { submitButton.innerHTML = ' Sending...'; submitButton.disabled = true; } auth.sendPasswordResetEmail(email) .then(() => { showNotification("Password reset email sent! Check your inbox for instructions.", "success"); // Redirect to login after a delay setTimeout(() => { window.location.href = "login.html?message=reset_email_sent"; }, 3000); }) .catch((error) => { // Reset button state if (submitButton) { submitButton.innerHTML = 'Reset Password'; submitButton.disabled = false; } // Handle specific error cases let errorMessage = error.message; if (error.code === 'auth/user-not-found') { errorMessage = "No account found with this email. Please sign up first."; } else if (error.code === 'auth/invalid-email') { errorMessage = "The email address is not valid."; } showNotification(errorMessage, "error"); }); } // LOGOUT function function logout() { // Show confirmation dialog if (confirm("Are you sure you want to log out?")) { auth.signOut() .then(() => { showNotification("You have been logged out successfully", "success"); setTimeout(() => { window.location.href = "../auth/login.html"; }, 1500); }) .catch((error) => { showNotification("Error logging out: " + error.message, "error"); }); } } // Check authentication state and redirect if needed function checkAuthState() { auth.onAuthStateChanged((user) => { if (user) { console.log("User logged in:", user.email); // If user is on auth pages but already logged in, redirect to dashboard if (window.location.pathname.includes('auth/') && user.emailVerified) { window.location.href = "../dashboard/index.html"; } // If user's email is not verified, show reminder if (!user.emailVerified && !window.location.pathname.includes('register.html')) { showNotification("Please verify your email address to access all features", "warning"); } } else { console.log("No user logged in"); // If on protected pages, redirect to login if (window.location.pathname.includes('dashboard/')) { window.location.href = "../auth/login.html"; } } }); } // Email validation helper function function validateEmail(email) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } // Notification function function showNotification(message, type = "info") { // Create notification element const notification = document.createElement('div'); notification.className = `notification ${type}`; // Set icon based on type let icon = 'fa-info-circle'; if (type === 'success') icon = 'fa-check-circle'; if (type === 'error') icon = 'fa-exclamation-circle'; if (type === 'warning') icon = 'fa-exclamation-triangle'; notification.innerHTML = `
${message}
`; // Add to notification area or create one if it doesn't exist let notificationArea = document.getElementById('notificationArea'); if (!notificationArea) { notificationArea = document.createElement('div'); notificationArea.id = 'notificationArea'; notificationArea.className = 'notification-area'; document.body.appendChild(notificationArea); } notificationArea.appendChild(notification); // Auto remove after 5 seconds setTimeout(() => { if (notification.parentElement) { notification.remove(); } }, 5000); } // Initialize when DOM is loaded document.addEventListener('DOMContentLoaded', function() { // Set up password validation for all forms setupPasswordValidation(); // Check authentication state checkAuthState(); // Check for URL parameters to show specific messages const urlParams = new URLSearchParams(window.location.search); const message = urlParams.get('message'); if (message === 'verify_email') { showNotification("Please check your email to verify your account before logging in", "info"); } else if (message === 'reset_email_sent') { showNotification("Password reset email sent. Please check your inbox.", "success"); } // Add event listeners to forms to prevent default submission const forms = document.querySelectorAll('form'); forms.forEach(form => { form.addEventListener('submit', function(e) { e.preventDefault(); }); }); }); // Real-time password validation feedback function setupPasswordValidation() { const passwordInputs = document.querySelectorAll('input[type="password"]'); passwordInputs.forEach(input => { input.addEventListener('input', function() { const validation = validatePassword(this.value); const feedbackElement = document.getElementById(`${this.id}-feedback`); if (feedbackElement) { let feedbackHTML = ''; if (this.value.length > 0) { feedbackHTML = `
At least 10 characters
Uppercase letter
Lowercase letter
Number
Special character
`; } feedbackElement.innerHTML = feedbackHTML; } // Enable/disable submit button based on validation const form = this.closest('form'); if (form) { const submitButton = form.querySelector('button[type="submit"]'); if (submitButton && submitButton.id !== 'login-button') { submitButton.disabled = !validation.isValid; } } }); }); }