auth.js

2.60 KB
06/11/2025 15:25
JS
auth.js
// Authentication Functions

// Check if user is authenticated
function isAuthenticated() {
  const token = storage.get('authToken');
  return !!token;
}

// Get current user
function getCurrentUser() {
  return storage.get('currentUser');
}

// Login
async function login(email, password) {
  try {
    showLoading();

    const response = await mockApi.login(email, password);

    if (response.success) {
      storage.set('authToken', response.token);
      storage.set('currentUser', response.user);

      showToast('Login successful!', 'success');

      setTimeout(() => {
        window.location.href = 'index.html';
      }, 1000);
    }
  } catch (error) {
    showToast('Invalid email or password', 'error');
  } finally {
    hideLoading();
  }
}

// Logout
function logout() {
  storage.remove('authToken');
  storage.remove('currentUser');
  window.location.href = 'login.html';
}

// Initialize auth on page load
document.addEventListener('DOMContentLoaded', () => {
  // Check if on login page
  if (window.location.pathname.includes('login.html')) {
    // If already authenticated, redirect to dashboard
    if (isAuthenticated()) {
      window.location.href = 'index.html';
      return;
    }

    // Handle login form
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
      loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const formData = new FormData(loginForm);
        const email = formData.get('email');
        const password = formData.get('password');

        await login(email, password);
      });
    }

    // Toggle password visibility
    const togglePassword = document.querySelector('.toggle-password');
    if (togglePassword) {
      togglePassword.addEventListener('click', () => {
        const passwordInput = document.querySelector('input[name="password"]');
        const icon = togglePassword.querySelector('i');

        if (passwordInput.type === 'password') {
          passwordInput.type = 'text';
          icon.classList.remove('fa-eye');
          icon.classList.add('fa-eye-slash');
        } else {
          passwordInput.type = 'password';
          icon.classList.remove('fa-eye-slash');
          icon.classList.add('fa-eye');
        }
      });
    }
  } else {
    // If not authenticated, redirect to login
    if (!isAuthenticated()) {
      window.location.href = 'login.html';
      return;
    }

    // Handle logout
    const logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) {
      logoutBtn.addEventListener('click', (e) => {
        e.preventDefault();
        logout();
      });
    }
  }
});