'use client' import { useState, useEffect } from 'react' import { useRouter } from 'next/navigation' export default function AdminLogin() { const [adminToken, setAdminToken] = useState('') const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState('') const [isClient, setIsClient] = useState(false) const router = useRouter() useEffect(() => { setIsClient(true) // Check if already authenticated const checkExistingAuth = async () => { const token = localStorage.getItem('admin_token') if (token) { try { // Verify token with API - no hardcoded secret check const response = await fetch('http://127.0.0.1:5000/api/admin/courses', { headers: { 'Authorization': `Bearer ${token}` } }) if (response.ok) { console.log('Existing token valid, redirecting to dashboard') window.location.href = '/admin' return } else { // Token invalid, remove it localStorage.removeItem('admin_token') } } catch (error) { console.error('Token verification failed:', error) localStorage.removeItem('admin_token') } } } setTimeout(checkExistingAuth, 200) }, [router]) const handleLogin = async (e?: React.FormEvent) => { if (e) e.preventDefault() setError('') if (!adminToken.trim()) { setError('Please enter admin token') return } setIsLoading(true) try { console.log('Attempting login with token:', adminToken) // Test API connection first const testResponse = await fetch('http://127.0.0.1:5000/api/admin/courses', { headers: { 'Authorization': `Bearer ${adminToken}` } }) if (testResponse.ok) { console.log('API accepts token, saving to localStorage') // Clear any existing token first localStorage.removeItem('admin_token') // Save new token localStorage.setItem('admin_token', adminToken) // Verify it was saved const savedToken = localStorage.getItem('admin_token') console.log('Token saved verification:', savedToken) if (savedToken === adminToken) { console.log('✅ Token saved successfully, redirecting...') // Use window.location for reliable redirect setTimeout(() => { window.location.href = '/admin' }, 100) } else { setError('Failed to save authentication. Please try again.') } } else { console.log('API rejected token') setError('Invalid admin credentials. Please contact administrator.') setAdminToken('') } } catch (err) { console.error('Login error:', err) setError('Connection failed. Make sure backend is running.') } finally { setIsLoading(false) } } if (!isClient) { return null } return (
Enter your admin credentials to manage courses
Secure access only - Contact administrator for credentials
Welcome back, 5t4l1n