update error

This commit is contained in:
5t4l1n
2025-07-28 23:19:59 +05:30
parent 7f6531b097
commit 8816091e63
19 changed files with 4407 additions and 691 deletions
+280
View File
@@ -0,0 +1,280 @@
"use client"
import { useState, useEffect, useRef } from "react"
import { useRouter } from "next/navigation"
import { useAuth } from "@/context/auth-context"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Wallet, Mail, Lock, Loader2, Shield, CheckCircle2, AlertCircle } from "lucide-react"
import { toast } from "react-hot-toast"
export default function LoginPage() {
const {
connectWallet,
loginWithEmail,
isLoadingAuth,
walletConnected,
walletAddress,
firebaseUser,
authMethod
} = useAuth()
const router = useRouter()
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [isEmailLogin, setIsEmailLogin] = useState(false)
const [isConnectingWallet, setIsConnectingWallet] = useState(false)
const [isSubmittingEmail, setIsSubmittingEmail] = useState(false)
const hasRedirected = useRef(false)
// ✅ Check for existing authentication
useEffect(() => {
if (hasRedirected.current || isLoadingAuth) return
const checkAuth = setTimeout(() => {
if (isLoadingAuth) return
const isAuthenticated = (walletConnected && walletAddress) || firebaseUser
if (isAuthenticated && !hasRedirected.current) {
console.log('✅ User already authenticated, redirecting to dashboard...')
hasRedirected.current = true
router.replace("/dashboard")
}
}, 500)
return () => clearTimeout(checkAuth)
}, [isLoadingAuth, walletConnected, walletAddress, firebaseUser, router])
// ✅ Handle MetaMask connection
const handleWalletConnect = async () => {
if (isConnectingWallet || isLoadingAuth) return
setIsConnectingWallet(true)
try {
console.log('🦊 Starting MetaMask connection...')
// Check if MetaMask is installed
if (typeof window !== 'undefined' && !window.ethereum) {
toast.error("MetaMask not detected. Please install MetaMask extension.")
window.open('https://metamask.io/download/', '_blank')
return
}
const success = await connectWallet()
if (success) {
console.log('✅ MetaMask connection successful')
// Redirect will be handled by useEffect
}
} catch (error: any) {
console.error('❌ Wallet connection error:', error)
} finally {
setIsConnectingWallet(false)
}
}
// ✅ Handle email login
const handleEmailLogin = async (e: React.FormEvent) => {
e.preventDefault()
if (isSubmittingEmail || isLoadingAuth) return
if (!email.trim() || !password.trim()) {
toast.error("Please enter both email and password")
return
}
setIsSubmittingEmail(true)
try {
await loginWithEmail(email, password)
// Redirect will be handled by useEffect
} catch (error: any) {
console.error('❌ Email login failed:', error)
toast.error(error.message || "Login failed. Please check your credentials.")
} finally {
setIsSubmittingEmail(false)
}
}
// Show connected state
if ((walletConnected && walletAddress) || firebaseUser) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-blue-900/20 dark:to-purple-900/20 p-4">
<Card className="w-full max-w-md shadow-2xl">
<CardHeader className="text-center">
<CheckCircle2 className="w-12 h-12 text-green-600 mx-auto mb-4" />
<CardTitle className="text-xl font-bold text-green-600">
{walletConnected ? "MetaMask Connected! 🦊" : "Email Login Successful! 📧"}
</CardTitle>
</CardHeader>
<CardContent className="text-center space-y-4">
<Alert className="border-green-200 bg-green-50">
<AlertDescription className="text-green-700">
{walletConnected
? `🦊 ${walletAddress?.slice(0, 6)}...${walletAddress?.slice(-4)}`
: `📧 ${firebaseUser?.email}`
}
</AlertDescription>
</Alert>
<Button
onClick={() => {
if (!hasRedirected.current) {
hasRedirected.current = true
router.replace("/dashboard")
}
}}
className="w-full"
>
Go to Dashboard
</Button>
</CardContent>
</Card>
</div>
)
}
// Show loading while initializing
if (isLoadingAuth) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-4" />
<p>Initializing...</p>
</div>
</div>
)
}
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-blue-900/20 dark:to-purple-900/20 p-4">
<Card className="w-full max-w-md shadow-2xl">
<CardHeader className="text-center space-y-4">
<div className="mx-auto w-16 h-16 bg-gradient-to-br from-purple-500 to-blue-600 rounded-full flex items-center justify-center">
<Shield className="w-8 h-8 text-white" />
</div>
<CardTitle className="text-2xl font-bold bg-gradient-to-r from-purple-600 to-blue-600 bg-clip-text text-transparent">
Welcome to OpenLearnX! 🎓
</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
{/* MetaMask Login */}
<div className="space-y-4">
<Button
onClick={handleWalletConnect}
disabled={isConnectingWallet || isLoadingAuth || isSubmittingEmail}
className="w-full bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 text-white py-3"
>
{isConnectingWallet ? (
<>
<Loader2 className="w-5 h-5 mr-2 animate-spin" />
Connecting MetaMask...
</>
) : (
<>
<Wallet className="w-5 h-5 mr-2" />
Connect MetaMask Wallet 🦊
</>
)}
</Button>
<div className="bg-purple-50 dark:bg-purple-900/20 p-3 rounded-lg">
<p className="text-xs text-purple-700 dark:text-purple-300 text-center">
Recommended: Get Web3 features and blockchain verification!
</p>
</div>
</div>
<Separator />
{/* Email Login */}
<div className="space-y-4">
<Button
variant="outline"
onClick={() => setIsEmailLogin(!isEmailLogin)}
disabled={isConnectingWallet || isSubmittingEmail}
className="w-full"
>
<Mail className="w-4 h-4 mr-2" />
{isEmailLogin ? 'Hide Email Login' : 'Login with Email'}
</Button>
{isEmailLogin && (
<form onSubmit={handleEmailLogin} className="space-y-4">
<div>
<Label htmlFor="email">Email Address</Label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email"
disabled={isSubmittingEmail || isConnectingWallet}
required
/>
</div>
<div>
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter your password"
disabled={isSubmittingEmail || isConnectingWallet}
required
/>
</div>
<Button
type="submit"
disabled={isSubmittingEmail || isConnectingWallet || !email.trim() || !password.trim()}
className="w-full"
>
{isSubmittingEmail ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Logging in...
</>
) : (
<>
<Lock className="w-4 h-4 mr-2" />
Login with Email
</>
)}
</Button>
</form>
)}
</div>
{/* MetaMask Installation Help */}
{typeof window !== 'undefined' && !window.ethereum && (
<Alert className="border-orange-200 bg-orange-50">
<AlertCircle className="w-4 h-4 text-orange-600" />
<AlertDescription className="text-orange-700">
MetaMask not detected.
<Button
variant="link"
className="p-0 h-auto font-semibold text-orange-600 ml-1"
onClick={() => window.open('https://metamask.io/download/', '_blank')}
>
Install MetaMask
</Button>
</AlertDescription>
</Alert>
)}
</CardContent>
</Card>
</div>
)
}
+116
View File
@@ -1,5 +1,121 @@
"use client"
import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { useAuth } from "@/context/auth-context"
import { DashboardStatsOverview } from "@/components/dashboard-stats"
import { Loader2, AlertCircle } from "lucide-react"
import { Button } from "@/components/ui/button"
export default function DashboardPage() {
const { isLoadingAuth, walletConnected, walletAddress, firebaseUser, authMethod } = useAuth()
const router = useRouter()
const [showDashboard, setShowDashboard] = useState(false)
const [debugInfo, setDebugInfo] = useState<any>(null)
useEffect(() => {
// Debug authentication state
const authState = {
isLoadingAuth,
walletConnected,
walletAddress: !!walletAddress,
firebaseUser: !!firebaseUser,
authMethod,
localStorage: {
token: !!localStorage.getItem('openlearnx_jwt_token'),
wallet: !!localStorage.getItem('openlearnx_wallet'),
user: !!localStorage.getItem('openlearnx_user')
}
}
setDebugInfo(authState)
console.log('📊 Dashboard auth state:', authState)
// Give auth some time to initialize
const timer = setTimeout(() => {
const isAuthenticated = (walletConnected && walletAddress) || firebaseUser
if (isAuthenticated) {
console.log('✅ User authenticated, showing dashboard')
setShowDashboard(true)
} else if (!isLoadingAuth) {
console.log('❌ User not authenticated, redirecting to login')
router.replace("/auth/login")
}
}, 2000) // Wait 2 seconds for auth to stabilize
return () => clearTimeout(timer)
}, [isLoadingAuth, walletConnected, walletAddress, firebaseUser, authMethod, router])
// Show loading state
if (isLoadingAuth || !showDashboard) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900">
<div className="text-center space-y-4 max-w-md mx-auto p-6">
<Loader2 className="w-12 h-12 animate-spin mx-auto text-purple-600" />
<div className="space-y-2">
<h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
Loading Dashboard...
</h3>
<p className="text-gray-600 dark:text-gray-400">
{walletConnected ? `Connected to ${walletAddress?.slice(0, 6)}...${walletAddress?.slice(-4)}` :
firebaseUser ? `Logged in as ${firebaseUser.email}` :
'Verifying authentication...'}
</p>
</div>
{/* Debug info in development */}
{process.env.NODE_ENV === 'development' && debugInfo && (
<details className="text-left text-xs text-gray-500 bg-gray-100 dark:bg-gray-800 p-2 rounded mt-4">
<summary>Debug Info</summary>
<pre>{JSON.stringify(debugInfo, null, 2)}</pre>
</details>
)}
</div>
</div>
)
}
// Show error state if no auth after loading
if (!walletConnected && !firebaseUser && !isLoadingAuth) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900">
<div className="text-center space-y-4 max-w-md mx-auto p-6">
<AlertCircle className="w-16 h-16 text-red-500 mx-auto" />
<h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
Authentication Required
</h3>
<p className="text-gray-600 dark:text-gray-400">
Please log in to access your dashboard.
</p>
<div className="space-y-2">
<Button onClick={() => router.push("/auth/login")} className="w-full">
Go to Login
</Button>
<Button
variant="outline"
onClick={() => {
localStorage.clear()
window.location.href = "/auth/login"
}}
className="w-full"
>
Clear Data & Login
</Button>
</div>
{/* Debug info */}
{process.env.NODE_ENV === 'development' && (
<details className="text-left text-xs text-gray-500 bg-gray-100 dark:bg-gray-800 p-2 rounded mt-4">
<summary>Debug Info</summary>
<pre>{JSON.stringify(debugInfo, null, 2)}</pre>
</details>
)}
</div>
</div>
)
}
// Show dashboard if authenticated
return <DashboardStatsOverview />
}
+20 -6
View File
@@ -10,9 +10,10 @@ import { ThemeProvider } from "@/components/theme-provider"
const inter = Inter({ subsets: ["latin"] })
export const metadata: Metadata = {
title: "OpenLearnX - Decentralized Adaptive Learning",
description: "AI-powered adaptive testing with blockchain-secured credentials.",
generator: 'v0.dev'
title: "OpenLearnX - Comprehensive Learning Dashboard",
description: "AI-powered adaptive learning with blockchain integration, real-time analytics, and professional progress tracking.",
keywords: "learning, coding, blockchain, AI, analytics, professional development",
generator: 'OpenLearnX v2.0'
}
export default function RootLayout({
@@ -25,9 +26,22 @@ export default function RootLayout({
<body className={inter.className}>
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
<AuthProvider>
<Navbar />
<main>{children}</main>
<Toaster position="top-right" />
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900">
<Navbar />
<main className="transition-all duration-300">{children}</main>
<Toaster
position="top-right"
toastOptions={{
duration: 4000,
style: {
background: 'rgba(17, 24, 39, 0.95)',
color: '#fff',
backdropFilter: 'blur(16px)',
border: '1px solid rgba(75, 85, 99, 0.3)',
},
}}
/>
</div>
</AuthProvider>
</ThemeProvider>
</body>