// Authentication Module for Pulse App class AuthManager { constructor() { this.currentUser = null; this.isSignedUp = false; this.currentStep = 1; this.init(); } init() { // Check if user is logged in this.checkAuthStatus(); // Initialize login form this.initLoginForm(); // Initialize signup form this.initSignupForm(); } checkAuthStatus() { const user = localStorage.getItem('pulseUser'); if (user) { this.currentUser = JSON.parse(user); // If on login/signup page and user is logged in, redirect to dashboard if (window.location.pathname.includes('login.html') || window.location.pathname.includes('signup.html')) { window.location.href = 'index.html'; } } } initLoginForm() { const loginForm = document.getElementById('loginForm'); if (loginForm) { loginForm.addEventListener('submit', (e) => { e.preventDefault(); this.handleLogin(e); }); } } initSignupForm() { const signupForm = document.getElementById('signupForm'); if (signupForm) { signupForm.addEventListener('submit', (e) => { e.preventDefault(); this.handleSignup(e); }); } } async handleLogin(e) { e.preventDefault(); const formData = new FormData(e.target); const email = formData.get('email'); const password = formData.get('password'); const remember = formData.get('remember-me'); try { // Simulate API call const response = await this.mockLoginAPI(email, password); if (response.success) { // Save user data this.currentUser = response.user; localStorage.setItem('pulseUser', JSON.stringify(response.user)); if (remember) { localStorage.setItem('rememberUser', 'true'); } // Show success message this.showNotification('เข้าสู่ระบบสำเร็จ!', 'success'); // Redirect to dashboard setTimeout(() => { window.location.href = 'index.html'; }, 1000); } else { this.showNotification(response.error || 'อีเมลหรือรหัสผ่านไม่ถูกต้อง', 'error'); } } catch (error) { this.showNotification('เกิดข้อผิดพลาด กรุณาลองใหม่', 'error'); } } async handleSignup(e) { e.preventDefault(); const formData = new FormData(e.target); // Validate passwords match const password = formData.get('password'); const confirmPassword = formData.get('confirmPassword'); if (password !== confirmPassword) { this.showNotification('รหัสผ่านไม่ตรงกัน', 'error'); return; } try { // Collect form data const userData = { firstName: formData.get('firstName'), lastName: formData.get('lastName'), email: formData.get('email'), password: password, // In real app, hash this gender: formData.get('gender'), birthdate: formData.get('birthdate'), height: formData.get('height'), weight: formData.get('weight'), primaryGoal: formData.get('primaryGoal'), dietType: formData.get('dietType'), homeAddress: { address: formData.get('homeAddress'), district: formData.get('homeDistrict'), province: formData.get('homeProvince'), zipcode: formData.get('homeZipcode') }, workAddress: { address: formData.get('workAddress'), district: formData.get('workDistrict'), province: formData.get('workProvince'), zipcode: formData.get('workZipcode') }, createdAt: new Date().toISOString() }; // Simulate API call const response = await this.mockSignupAPI(userData); if (response.success) { // Save user data this.currentUser = response.user; localStorage.setItem('pulseUser', JSON.stringify(response.user)); // Show success message this.showNotification('สมัครสมาชิกสำเร็จ!', 'success'); // Redirect to dashboard setTimeout(() => { window.location.href = 'index.html'; }, 1000); } else { this.showNotification(response.error || 'สมัครสมาชิกไม่สำเร็จ', 'error'); } } catch (error) { this.showNotification('เกิดข้อผิดพลาด กรุณาลองใหม่', 'error'); } } async mockLoginAPI(email, password) { // Simulate API delay await new Promise(resolve => setTimeout(resolve, 1000)); // Check if user exists in localStorage (for demo) const users = JSON.parse(localStorage.getItem('pulseUsers') || '[]'); const user = users.find(u => u.email === email); if (user && user.password === password) { return { success: true, user: { id: user.id, email: user.email, firstName: user.firstName, lastName: user.lastName } }; } // Demo account for testing if (email === 'demo@pulse.app' && password === 'demo123') { return { success: true, user: { id: 'demo-user', email: 'demo@pulse.app', firstName: 'ผู้ใช้', lastName: 'ทดลอง', gender: 'male', birthdate: '1995-01-15', height: '170', weight: '65' } }; } return { success: false, error: 'อีเมลหรือรหัสผ่านไม่ถูกต้อง' }; } async mockSignupAPI(userData) { // Simulate API delay await new Promise(resolve => setTimeout(resolve, 1000)); // Check if email already exists const users = JSON.parse(localStorage.getItem('pulseUsers') || '[]'); const existingUser = users.find(u => u.email === userData.email); if (existingUser) { return { success: false, error: 'อีเมลนี้มีผู้ใช้แล้ว' }; } // Generate user ID userData.id = 'user_' + Date.now(); // Save to localStorage (for demo) users.push(userData); localStorage.setItem('pulseUsers', JSON.stringify(users)); return { success: true, user: { id: userData.id, email: userData.email, firstName: userData.firstName, lastName: userData.lastName, gender: userData.gender, birthdate: userData.birthdate, height: userData.height, weight: userData.weight, primaryGoal: userData.primaryGoal, dietType: userData.dietType, homeAddress: userData.homeAddress, workAddress: userData.workAddress } }; } async loginWithGoogle() { try { // In a real app, this would use Google OAuth this.showNotification('กำลังเชื่อมต่อกับ Google...', 'info'); // Simulate OAuth flow await new Promise(resolve => setTimeout(resolve, 1500)); // Mock Google user data const googleUser = { id: 'google_' + Date.now(), email: 'user@gmail.com', firstName: 'Google', lastName: 'User' }; this.currentUser = googleUser; localStorage.setItem('pulseUser', JSON.stringify(googleUser)); this.showNotification('เข้าสู่ระบบด้วย Google สำเร็จ!', 'success'); setTimeout(() => { window.location.href = 'index.html'; }, 1000); } catch (error) { this.showNotification('เกิดข้อผิดพลาดในการเชื่อมต่อ Google', 'error'); } } async loginWithApple() { try { // In a real app, this would use Apple Sign In this.showNotification('กำลังเชื่อมต่อกับ Apple ID...', 'info'); // Simulate OAuth flow await new Promise(resolve => setTimeout(resolve, 1500)); // Mock Apple user data const appleUser = { id: 'apple_' + Date.now(), email: 'user@icloud.com', firstName: 'Apple', lastName: 'User' }; this.currentUser = appleUser; localStorage.setItem('pulseUser', JSON.stringify(appleUser)); this.showNotification('เข้าสู่ระบบด้วย Apple ID สำเร็จ!', 'success'); setTimeout(() => { window.location.href = 'index.html'; }, 1000); } catch (error) { this.showNotification('เกิดข้อผิดพลาดในการเชื่อมต่อ Apple ID', 'error'); } } logout() { this.currentUser = null; localStorage.removeItem('pulseUser'); localStorage.removeItem('rememberUser'); this.showNotification('ออกจากระบบสำเร็จ', 'info'); setTimeout(() => { window.location.href = 'login.html'; }, 1000); } showNotification(message, type = 'info') { // Remove existing notifications const existing = document.querySelector('.auth-notification'); if (existing) { existing.remove(); } // Create notification element const notification = document.createElement('div'); notification.className = `auth-notification fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 animate-pulse`; // Set color based on type const colors = { success: 'bg-green-500 text-white', error: 'bg-red-500 text-white', info: 'bg-blue-500 text-white', warning: 'bg-yellow-500 text-white' }; notification.classList.add(...colors[type].split(' ')); notification.innerHTML = `
${message}
`; document.body.appendChild(notification); // Remove after 3 seconds setTimeout(() => { notification.remove(); }, 3000); } // Step navigation for signup changeStep(direction) { const totalSteps = 3; const newStep = this.currentStep + direction; if (newStep < 1 || newStep > totalSteps) { return; } // Hide current step document.getElementById(`step${this.currentStep}Content`).classList.add('hidden'); // Show new step document.getElementById(`step${newStep}Content`).classList.remove('hidden'); // Update step indicators document.getElementById(`step${this.currentStep}`).classList.remove('bg-primary-600'); document.getElementById(`step${this.currentStep}`).classList.add('bg-gray-300'); document.getElementById(`step${newStep}`).classList.remove('bg-gray-300'); document.getElementById(`step${newStep}`).classList.add('bg-primary-600'); // Update progress bar const progressBar = document.getElementById('progressBar'); progressBar.style.width = `${(newStep / totalSteps) * 100}%`; // Update buttons const prevBtn = document.getElementById('prevBtn'); const nextBtn = document.getElementById('nextBtn'); const submitBtn = document.getElementById('submitBtn'); if (newStep === 1) { prevBtn.classList.add('hidden'); nextBtn.classList.remove('hidden'); submitBtn.classList.add('hidden'); } else if (newStep === totalSteps) { prevBtn.classList.remove('hidden'); nextBtn.classList.add('hidden'); submitBtn.classList.remove('hidden'); } else { prevBtn.classList.remove('hidden'); nextBtn.classList.remove('hidden'); submitBtn.classList.add('hidden'); } this.currentStep = newStep; } // Password visibility toggle togglePassword() { const passwordInput = document.getElementById('password'); const toggleIcon = document.getElementById('togglePasswordIcon'); if (passwordInput.type === 'password') { passwordInput.type = 'text'; toggleIcon.setAttribute('data-feather', 'eye-off'); } else { passwordInput.type = 'password'; toggleIcon.setAttribute('data-feather', 'eye'); } feather.replace(); } // Get current user getCurrentUser() { return this.currentUser; } // Check if user is authenticated isAuthenticated() { return this.currentUser !== null; } } // Initialize Auth Manager const authManager = new AuthManager(); // Global functions for HTML onclick handlers function togglePassword() { authManager.togglePassword(); } function changeStep(direction) { authManager.changeStep(direction); } function loginWithGoogle() { authManager.loginWithGoogle(); } function loginWithApple() { authManager.loginWithApple(); } // Export for use in other modules if (typeof module !== 'undefined' && module.exports) { module.exports = AuthManager; }