login.js

5.54 KB
04/08/2025 05:23
JS
login.js
/**
 * Admin Login JavaScript
 * Handles admin authentication and login form
 */

// Dynamic path detection
const BASE_PATH = (() => {
  const path = window.location.pathname.replace(/\/$/, ''); // Remove trailing slash
  const pathParts = path.split('/').filter(part => part !== ''); // Remove empty parts

  console.log('Login - Current path:', path);
  console.log('Login - Path parts:', pathParts);

  // Find admin folder index
  const adminIndex = pathParts.indexOf('admin');
  console.log('Login - Admin index:', adminIndex);

  if (adminIndex > 0) {
    // Return base path up to admin folder (excluding admin)
    const basePath = '/' + pathParts.slice(0, adminIndex).join('/');
    console.log('Login - Detected BASE_PATH:', basePath);
    return basePath;
  }

  // Default to root if admin not found in path
  console.log('Login - Admin not found in path, using empty BASE_PATH');
  return '';
})();

const ADMIN_BASE_PATH = BASE_PATH + '/admin';

console.log('Login - Final ADMIN_BASE_PATH:', ADMIN_BASE_PATH);// API Base URL
const API_BASE = BASE_PATH + '/api';

document.addEventListener('DOMContentLoaded', function() {
  // Check if already logged in
  const token = localStorage.getItem('adminToken');
  if (token) {
    // Verify token is still valid
    fetch(`${API_BASE}/auth/me`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
      .then(response => response.json())
      .then(data => {
        if (data.success && data.data.user.role === 'admin') {
          window.location.href = ADMIN_BASE_PATH + '/';
        } else {
          localStorage.removeItem('adminToken');
        }
      })
      .catch(() => {
        localStorage.removeItem('adminToken');
      });
  }

  // Login form handler
  const loginForm = document.getElementById('loginForm');
  if (loginForm) {
    loginForm.addEventListener('submit', handleLogin);
  }
});

async function handleLogin(e) {
  e.preventDefault();

  const loginButton = document.getElementById('loginButton');
  const loginButtonText = document.getElementById('loginButtonText');
  const loginSpinner = document.getElementById('loginSpinner');
  const alertContainer = document.getElementById('alertContainer');
  const email = document.getElementById('email').value.trim();
  const password = document.getElementById('password').value;

  if (!email || !password) {
    showAlert('Please fill in all fields', 'danger');
    return;
  }

  setLoading(true);
  clearAlerts();

  try {
    const response = await fetch(`${API_BASE}/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: email,
        password: password
      })
    });

    const data = await response.json();

    if (response.ok && data.success) {
      // Check if user is admin
      if (data.data.user.role !== 'admin') {
        showAlert('Access denied. Admin privileges required.', 'danger');
        setLoading(false);
        return;
      }

      // Store token and redirect
      localStorage.setItem('adminToken', data.data.access_token);

      showAlert('Login successful! Redirecting...', 'success');

      setTimeout(() => {
        window.location.href = ADMIN_BASE_PATH + '/';
      }, 1000);
    } else {
      showAlert(data.message || 'Login failed. Please check your credentials.', 'danger');
      setLoading(false);
    }
  } catch (error) {
    console.error('Login error:', error);
    showAlert('Connection error. Please try again.', 'danger');
    setLoading(false);
  }
}

// Helper Functions
function setLoading(loading) {
  const loginButton = document.getElementById('loginButton');
  const loginButtonText = document.getElementById('loginButtonText');
  const loginSpinner = document.getElementById('loginSpinner');

  if (loading) {
    loginButtonText.style.display = 'none';
    loginSpinner.style.display = 'inline-block';
    loginButton.disabled = true;
  } else {
    loginButtonText.style.display = 'inline-block';
    loginSpinner.style.display = 'none';
    loginButton.disabled = false;
  }
}

function showAlert(message, type = 'info') {
  const alertContainer = document.getElementById('alertContainer');
  const alertDiv = document.createElement('div');
  alertDiv.className = `alert alert-${type}`;
  alertDiv.innerHTML = `
        <i class="fas fa-${getAlertIcon(type)}"></i>
        <span>${message}</span>
    `;

  alertContainer.appendChild(alertDiv);

  // Auto-remove success alerts
  if (type === 'success') {
    setTimeout(() => {
      alertDiv.remove();
    }, 5000);
  }
}

function clearAlerts() {
  const alertContainer = document.getElementById('alertContainer');
  alertContainer.innerHTML = '';
}

function getAlertIcon(type) {
  const icons = {
    success: 'check-circle',
    danger: 'exclamation-triangle',
    warning: 'exclamation-circle',
    info: 'info-circle'
  };
  return icons[type] || 'info-circle';
}

function togglePassword() {
  const passwordField = document.getElementById('password');
  const toggleIcon = document.getElementById('passwordToggleIcon');

  if (passwordField.type === 'password') {
    passwordField.type = 'text';
    toggleIcon.className = 'fas fa-eye-slash';
  } else {
    passwordField.type = 'password';
    toggleIcon.className = 'fas fa-eye';
  }
}

// Demo login function
function loginAsDemo() {
  const emailInput = document.getElementById('email');
  const passwordInput = document.getElementById('password');
  emailInput.value = 'admin@example.com';
  passwordInput.value = 'admin123';
}

// Go back to store function
function goBackToStore() {
  window.location.href = BASE_PATH + '/';
}