/** * Session Handler - Xử lý session timeout và tự động redirect */ class SessionHandler { constructor() { this.checkInterval = 30000; // Kiểm tra mỗi 30 giây this.warningTime = 300000; // Cảnh báo trước 5 phút this.init(); } init() { // Chỉ chạy nếu user đã đăng nhập if (document.body.classList.contains('logged-in') || document.querySelector('[data-user-id]')) { this.startSessionCheck(); this.setupActivityListeners(); } } startSessionCheck() { setInterval(() => { this.checkSession(); }, this.checkInterval); } setupActivityListeners() { // Reset timer khi user hoạt động const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click']; events.forEach(event => { document.addEventListener(event, () => { this.resetSessionTimer(); }, true); }); } resetSessionTimer() { // Reset session timer khi user hoạt động if (window.sessionTimer) { clearTimeout(window.sessionTimer); } } async checkSession() { try { const response = await fetch('/public_html/includes/session_check.php', { method: 'GET', headers: { 'X-Requested-With': 'XMLHttpRequest' } }); if (response.ok) { const data = await response.json(); if (!data.success && data.redirect) { this.handleSessionExpired(data.message); } } } catch (error) { console.log('Session check error:', error); } } handleSessionExpired(message) { // Hiển thị thông báo session hết hạn this.showSessionExpiredMessage(message); // Redirect sau 3 giây setTimeout(() => { window.location.href = '/public_html/modules/login.php?msg=session_expired'; }, 3000); } showSessionExpiredMessage(message) { // Tạo thông báo const notification = document.createElement('div'); notification.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-4 rounded-lg shadow-lg z-50 max-w-sm'; notification.innerHTML = `
Phiên đăng nhập hết hạn
${message}
`; document.body.appendChild(notification); // Tự động ẩn sau 5 giây setTimeout(() => { if (notification.parentNode) { notification.parentNode.removeChild(notification); } }, 5000); } // Phương thức để logout từ JavaScript async logout() { try { const response = await fetch('/public_html/modules/logout.php', { method: 'GET', headers: { 'X-Requested-With': 'XMLHttpRequest' } }); if (response.ok) { window.location.href = '/public_html/modules/login.php'; } } catch (error) { console.log('Logout error:', error); // Fallback redirect window.location.href = '/public_html/modules/login.php'; } } } // Khởi tạo SessionHandler khi trang load document.addEventListener('DOMContentLoaded', () => { new SessionHandler(); }); // Export để sử dụng ở nơi khác window.SessionHandler = SessionHandler;