| Server IP : 3.111.61.48 / Your IP : 216.73.216.67 Web Server : Apache System : Linux ip-10-0-5-176 6.8.0-1057-aws #60~22.04.1-Ubuntu SMP Wed May 27 08:16:59 UTC 2026 x86_64 User : ubuntu ( 1000) PHP Version : 8.2.31 Disable Function : exec,passthru,shell_exec,system MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /var/www/vhost/book.gyaniguru.org/js/ |
Upload File : |
/* ================================================================
GYANI GURU — Auth Manager (auth.js)
Handles: login, register, session, user state
================================================================ */
const AuthManager = {
// ---- Storage Keys ----
KEYS: {
user: 'gg_user',
session: 'gg_session',
cart: 'gg_cart',
wishlist: 'gg_wishlist'
},
// ---- Initialize (redirect if logged in visiting auth pages) ----
init() {
// If logged in and on auth page, redirect to account
const currentPage = window.location.pathname.split('/').pop();
const authPages = ['login.html', 'register.html'];
if (authPages.includes(currentPage) && this.isLoggedIn()) {
window.location.href = 'account.html';
return;
}
// Update navbar across all pages
this.updateNavbar();
},
// ---- Check Login State ----
isLoggedIn() {
return !!localStorage.getItem(this.KEYS.user);
},
// ---- Get User ----
getUser() {
try {
return JSON.parse(localStorage.getItem(this.KEYS.user)) || null;
} catch { return null; }
},
// ---- Set User ----
setUser(userData) {
localStorage.setItem(this.KEYS.user, JSON.stringify(userData));
// Also store extended profile if not existing
const profile = this.getProfile();
if (!profile) {
this.setProfile({
firstName: userData.name ? userData.name.split(' ')[0] : 'User',
lastName: userData.name ? userData.name.split(' ').slice(1).join(' ') : '',
email: userData.email || '',
phone: userData.phone || '+91 98765 43210',
dob: userData.dob || '',
gender: userData.gender || 'Male',
city: userData.city || 'India',
joinedDate: userData.joinedDate || new Date().toLocaleDateString('en-IN', { month: 'long', year: 'numeric' })
});
}
},
// ---- Profile ----
getProfile() {
try { return JSON.parse(localStorage.getItem('gg_profile')) || null; } catch { return null; }
},
setProfile(data) {
localStorage.setItem('gg_profile', JSON.stringify(data));
},
// ---- Logout ----
logout() {
localStorage.removeItem(this.KEYS.user);
localStorage.removeItem('gg_profile');
window.location.href = 'login.html';
},
// ---- Login Form Handler ----
login() {
const email = document.getElementById('loginEmail')?.value?.trim();
const password = document.getElementById('loginPassword')?.value;
const alertEl = document.getElementById('loginAlert');
const alertMsg = document.getElementById('loginAlertMsg');
const successEl = document.getElementById('loginSuccess');
const btn = document.getElementById('loginBtn');
// Clear previous errors
this.clearFieldErrors(['emailError', 'passwordError']);
if (alertEl) alertEl.style.display = 'none';
let valid = true;
if (!email || !this.isValidEmail(email)) {
this.showFieldError('emailError', 'Please enter a valid email address');
document.getElementById('loginEmail')?.classList.add('input-error');
valid = false;
}
if (!password || password.length < 6) {
this.showFieldError('passwordError', 'Password must be at least 6 characters');
document.getElementById('loginPassword')?.classList.add('input-error');
valid = false;
}
if (!valid) return;
// Show loader
this.setButtonLoading(btn, true);
// Simulate async login
setTimeout(() => {
this.setButtonLoading(btn, false);
// Demo: accept any valid email/password combo
const userData = {
name: email.split('@')[0].replace(/[._]/g, ' ').replace(/\b\w/g, c => c.toUpperCase()),
email: email,
loginTime: new Date().toISOString()
};
this.setUser(userData);
if (successEl) successEl.style.display = 'flex';
// Redirect
const returnUrl = new URLSearchParams(window.location.search).get('from') || 'account.html';
setTimeout(() => { window.location.href = returnUrl; }, 1200);
}, 1500);
},
// ---- Register Form Handler ----
register() {
const firstName = document.getElementById('regFirstName')?.value?.trim();
const lastName = document.getElementById('regLastName')?.value?.trim();
const email = document.getElementById('regEmail')?.value?.trim();
const password = document.getElementById('regPassword')?.value;
const confirmPwd = document.getElementById('regConfirmPassword')?.value;
const agreeTerms = document.getElementById('agreeTerms')?.checked;
const alertEl = document.getElementById('registerAlert');
const alertMsg = document.getElementById('registerAlertMsg');
const successEl = document.getElementById('registerSuccess');
const btn = document.getElementById('registerBtn');
// Clear
this.clearFieldErrors(['firstNameError','lastNameError','regEmailError','regPwdError','regConfPwdError','termsError']);
if (alertEl) alertEl.style.display = 'none';
let valid = true;
if (!firstName) { this.showFieldError('firstNameError', 'First name is required'); valid = false; }
if (!lastName) { this.showFieldError('lastNameError', 'Last name is required'); valid = false; }
if (!email || !this.isValidEmail(email)) { this.showFieldError('regEmailError', 'Enter a valid email'); valid = false; }
if (!password || password.length < 8) { this.showFieldError('regPwdError', 'Password must be at least 8 characters'); valid = false; }
if (password !== confirmPwd) { this.showFieldError('regConfPwdError', 'Passwords do not match'); valid = false; }
if (!agreeTerms) { this.showFieldError('termsError', 'Please agree to the Terms of Service'); valid = false; }
if (!valid) return;
this.setButtonLoading(btn, true);
setTimeout(() => {
this.setButtonLoading(btn, false);
const userData = { name: `${firstName} ${lastName}`, email, joinedDate: new Date().toLocaleDateString('en-IN', { month: 'long', year: 'numeric' }) };
this.setUser(userData);
if (successEl) successEl.style.display = 'flex';
setTimeout(() => { window.location.href = 'account.html'; }, 1500);
}, 1800);
},
// ---- Update Navbar Based on Login State ----
updateNavbar() {
// Find or inject the user/account nav icon
const navIcons = document.querySelector('.nav-icons');
if (!navIcons) return;
let accountIcon = navIcons.querySelector('.nav-account-icon');
if (!accountIcon) {
accountIcon = document.createElement('a');
accountIcon.className = 'nav-icon-btn nav-account-icon';
accountIcon.title = 'My Account';
navIcons.appendChild(accountIcon);
}
if (this.isLoggedIn()) {
const user = this.getUser();
const initials = user?.name ? user.name.split(' ').map(w => w[0]).join('').slice(0,2).toUpperCase() : '👤';
accountIcon.href = 'account.html';
accountIcon.innerHTML = `<i class="bi bi-person-fill"></i>`;
accountIcon.style.background = 'rgba(212,175,55,0.2)';
accountIcon.style.borderColor = 'var(--gold)';
} else {
accountIcon.href = 'login.html';
accountIcon.innerHTML = `<i class="bi bi-person"></i>`;
}
},
// ---- Helpers ----
isValidEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
},
showFieldError(id, msg) {
const el = document.getElementById(id);
if (el) el.textContent = msg;
},
clearFieldErrors(ids) {
ids.forEach(id => {
const el = document.getElementById(id);
if (el) el.textContent = '';
});
document.querySelectorAll('.auth-input').forEach(inp => {
inp.classList.remove('input-error', 'input-success');
});
},
setButtonLoading(btn, loading) {
if (!btn) return;
const text = btn.querySelector('.btn-text');
const loader = btn.querySelector('.btn-loader');
if (loading) {
if (text) text.style.display = 'none';
if (loader) loader.style.display = 'flex';
btn.disabled = true;
} else {
if (text) text.style.display = 'flex';
if (loader) loader.style.display = 'none';
btn.disabled = false;
}
}
};
// Auto-run on every page
document.addEventListener('DOMContentLoaded', () => AuthManager.updateNavbar());