mirror of
https://github.com/th30d4y/OpenLearnX.git
synced 2026-05-26 19:26:33 +00:00
update error
This commit is contained in:
+75
-46
@@ -13,6 +13,9 @@ from pymongo import MongoClient
|
|||||||
from bson import ObjectId
|
from bson import ObjectId
|
||||||
import hashlib
|
import hashlib
|
||||||
import time
|
import time
|
||||||
|
import signal
|
||||||
|
import io
|
||||||
|
from contextlib import redirect_stdout, redirect_stderr
|
||||||
|
|
||||||
# Load environment variables
|
# Load environment variables
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
@@ -276,7 +279,7 @@ def get_comprehensive_stats():
|
|||||||
# Calculate real-time statistics
|
# Calculate real-time statistics
|
||||||
current_time = datetime.now()
|
current_time = datetime.now()
|
||||||
join_date = user_stats.get('join_date', current_time - timedelta(days=30)) if user_stats else current_time - timedelta(days=30)
|
join_date = user_stats.get('join_date', current_time - timedelta(days=30)) if user_stats else current_time - timedelta(days=30)
|
||||||
days_since_join = (current_time - join_date).days if days_since_join > 0 else 30
|
days_since_join = (current_time - join_date).days if (current_time - join_date).days > 0 else 30
|
||||||
|
|
||||||
# ✅ ENHANCED: Calculate coding streak with proper logic
|
# ✅ ENHANCED: Calculate coding streak with proper logic
|
||||||
coding_streak = calculate_coding_streak(db, user_id)
|
coding_streak = calculate_coding_streak(db, user_id)
|
||||||
@@ -381,34 +384,41 @@ def get_recent_activity():
|
|||||||
]
|
]
|
||||||
|
|
||||||
for collection, activity_type, default_title, default_points in activity_sources:
|
for collection, activity_type, default_title, default_points in activity_sources:
|
||||||
recent_items = collection.find(
|
try:
|
||||||
{"user_id": user_id}
|
recent_items = collection.find(
|
||||||
).sort([("completed_at", -1), ("submitted_at", -1), ("earned_at", -1), ("issued_at", -1)]).limit(max_records // len(activity_sources))
|
{"user_id": user_id}
|
||||||
|
).sort([("completed_at", -1), ("submitted_at", -1), ("earned_at", -1), ("issued_at", -1)]).limit(max_records // len(activity_sources))
|
||||||
for item in recent_items:
|
|
||||||
# Determine the completion date field
|
|
||||||
completed_at = (
|
|
||||||
item.get('completed_at') or
|
|
||||||
item.get('submitted_at') or
|
|
||||||
item.get('earned_at') or
|
|
||||||
item.get('issued_at') or
|
|
||||||
datetime.now()
|
|
||||||
)
|
|
||||||
|
|
||||||
if isinstance(completed_at, str):
|
for item in recent_items:
|
||||||
completed_at = datetime.fromisoformat(completed_at)
|
# Determine the completion date field
|
||||||
|
completed_at = (
|
||||||
activities.append({
|
item.get('completed_at') or
|
||||||
"id": str(item.get('_id', uuid.uuid4())),
|
item.get('submitted_at') or
|
||||||
"type": activity_type,
|
item.get('earned_at') or
|
||||||
"title": item.get('title', item.get('name', default_title)),
|
item.get('issued_at') or
|
||||||
"description": format_activity_description(item, activity_type),
|
datetime.now()
|
||||||
"completed_at": completed_at.isoformat(),
|
)
|
||||||
"points_earned": item.get('points', item.get('points_earned', default_points)),
|
|
||||||
"success_rate": item.get('score', item.get('completion_percentage', 100)),
|
if isinstance(completed_at, str):
|
||||||
"difficulty": item.get('difficulty', 'Intermediate'),
|
try:
|
||||||
"blockchain_verified": item.get('blockchain_verified', False)
|
completed_at = datetime.fromisoformat(completed_at)
|
||||||
})
|
except:
|
||||||
|
completed_at = datetime.now()
|
||||||
|
|
||||||
|
activities.append({
|
||||||
|
"id": str(item.get('_id', uuid.uuid4())),
|
||||||
|
"type": activity_type,
|
||||||
|
"title": item.get('title', item.get('name', default_title)),
|
||||||
|
"description": format_activity_description(item, activity_type),
|
||||||
|
"completed_at": completed_at.isoformat(),
|
||||||
|
"points_earned": item.get('points', item.get('points_earned', default_points)),
|
||||||
|
"success_rate": item.get('score', item.get('completion_percentage', 100)),
|
||||||
|
"difficulty": item.get('difficulty', 'Intermediate'),
|
||||||
|
"blockchain_verified": item.get('blockchain_verified', False)
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"⚠️ Failed to fetch {activity_type} activities: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
# Sort all activities by completion date
|
# Sort all activities by completion date
|
||||||
activities.sort(key=lambda x: x['completed_at'], reverse=True)
|
activities.sort(key=lambda x: x['completed_at'], reverse=True)
|
||||||
@@ -559,7 +569,10 @@ def calculate_coding_streak(db, user_id):
|
|||||||
for submission in submissions:
|
for submission in submissions:
|
||||||
submission_date = submission.get('submitted_at')
|
submission_date = submission.get('submitted_at')
|
||||||
if isinstance(submission_date, str):
|
if isinstance(submission_date, str):
|
||||||
submission_date = datetime.fromisoformat(submission_date).date()
|
try:
|
||||||
|
submission_date = datetime.fromisoformat(submission_date).date()
|
||||||
|
except:
|
||||||
|
continue
|
||||||
elif isinstance(submission_date, datetime):
|
elif isinstance(submission_date, datetime):
|
||||||
submission_date = submission_date.date()
|
submission_date = submission_date.date()
|
||||||
else:
|
else:
|
||||||
@@ -860,15 +873,11 @@ def format_activity_description(item, activity_type):
|
|||||||
return "Activity completed"
|
return "Activity completed"
|
||||||
|
|
||||||
# ===================================================================
|
# ===================================================================
|
||||||
# ✅ ENHANCED DYNAMIC SCORING SYSTEM - WITH YOUR UPDATES
|
# ✅ ENHANCED DYNAMIC SCORING SYSTEM
|
||||||
# ===================================================================
|
# ===================================================================
|
||||||
|
|
||||||
def calculate_dynamic_score(code, language, problem):
|
def calculate_dynamic_score(code, language, problem):
|
||||||
"""Enhanced dynamic scoring with better error handling and feedback"""
|
"""Enhanced dynamic scoring with better error handling and feedback"""
|
||||||
import io
|
|
||||||
from contextlib import redirect_stdout, redirect_stderr
|
|
||||||
import time
|
|
||||||
import signal
|
|
||||||
|
|
||||||
# Handle both old and new problem formats
|
# Handle both old and new problem formats
|
||||||
test_cases = problem.get('test_cases', [])
|
test_cases = problem.get('test_cases', [])
|
||||||
@@ -906,11 +915,24 @@ def calculate_dynamic_score(code, language, problem):
|
|||||||
# ✅ ENHANCED: Safer execution environment
|
# ✅ ENHANCED: Safer execution environment
|
||||||
exec_globals = {
|
exec_globals = {
|
||||||
"__builtins__": {
|
"__builtins__": {
|
||||||
**__builtins__,
|
'print': print,
|
||||||
'__import__': None, # Disable imports for security
|
'len': len,
|
||||||
'open': None, # Disable file operations
|
'str': str,
|
||||||
'eval': None, # Disable eval
|
'int': int,
|
||||||
'exec': None, # Disable nested exec
|
'float': float,
|
||||||
|
'list': list,
|
||||||
|
'dict': dict,
|
||||||
|
'tuple': tuple,
|
||||||
|
'set': set,
|
||||||
|
'range': range,
|
||||||
|
'enumerate': enumerate,
|
||||||
|
'zip': zip,
|
||||||
|
'sum': sum,
|
||||||
|
'max': max,
|
||||||
|
'min': min,
|
||||||
|
'sorted': sorted,
|
||||||
|
'abs': abs,
|
||||||
|
'round': round,
|
||||||
},
|
},
|
||||||
"__name__": "__main__"
|
"__name__": "__main__"
|
||||||
}
|
}
|
||||||
@@ -923,18 +945,25 @@ def calculate_dynamic_score(code, language, problem):
|
|||||||
else:
|
else:
|
||||||
exec_globals['input'] = lambda prompt='': ''
|
exec_globals['input'] = lambda prompt='': ''
|
||||||
|
|
||||||
# ✅ ADDED: Timeout protection
|
# ✅ ADDED: Timeout protection (Unix-like systems only)
|
||||||
def timeout_handler(signum, frame):
|
try:
|
||||||
raise TimeoutError("Code execution timed out")
|
def timeout_handler(signum, frame):
|
||||||
|
raise TimeoutError("Code execution timed out")
|
||||||
signal.signal(signal.SIGALRM, timeout_handler)
|
|
||||||
signal.alarm(5) # 5 second timeout
|
signal.signal(signal.SIGALRM, timeout_handler)
|
||||||
|
signal.alarm(5) # 5 second timeout
|
||||||
|
except:
|
||||||
|
# Skip timeout on Windows
|
||||||
|
pass
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with redirect_stdout(stdout_buffer), redirect_stderr(stderr_buffer):
|
with redirect_stdout(stdout_buffer), redirect_stderr(stderr_buffer):
|
||||||
exec(code, exec_globals)
|
exec(code, exec_globals)
|
||||||
finally:
|
finally:
|
||||||
signal.alarm(0) # Cancel timeout
|
try:
|
||||||
|
signal.alarm(0) # Cancel timeout
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
actual_output = stdout_buffer.getvalue().strip()
|
actual_output = stdout_buffer.getvalue().strip()
|
||||||
stderr_content = stderr_buffer.getvalue().strip()
|
stderr_content = stderr_buffer.getvalue().strip()
|
||||||
|
|||||||
@@ -157,4 +157,4 @@ def verify_signature():
|
|||||||
return jsonify({
|
return jsonify({
|
||||||
"success": False,
|
"success": False,
|
||||||
"error": str(e)
|
"error": str(e)
|
||||||
}), 500
|
}), 500
|
||||||
@@ -824,4 +824,4 @@ def dashboard_root():
|
|||||||
"/api/dashboard/update-profile"
|
"/api/dashboard/update-profile"
|
||||||
],
|
],
|
||||||
"authentication": "JWT Token in Authorization header OR Wallet address in X-Wallet-Address header"
|
"authentication": "JWT Token in Authorization header OR Wallet address in X-Wallet-Address header"
|
||||||
})
|
})
|
||||||
@@ -1,81 +1,101 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState, useEffect, useRef } from "react"
|
import { useEffect, useRef, useState } from "react"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
import { useAuth } from "@/context/auth-context"
|
import { useAuth } from "@/context/auth-context"
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input"
|
||||||
import { Label } from "@/components/ui/label"
|
import { Label } from "@/components/ui/label"
|
||||||
import { Separator } from "@/components/ui/separator"
|
import { Separator } from "@/components/ui/separator"
|
||||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
import { Wallet, Mail, Lock, Loader2, CheckCircle2 } from "lucide-react"
|
||||||
import { Wallet, Mail, Lock, Loader2, Shield, CheckCircle2, AlertCircle } from "lucide-react"
|
|
||||||
import { toast } from "react-hot-toast"
|
import { toast } from "react-hot-toast"
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
const {
|
const {
|
||||||
connectWallet,
|
user,
|
||||||
loginWithEmail,
|
firebaseUser,
|
||||||
isLoadingAuth,
|
|
||||||
walletConnected,
|
walletConnected,
|
||||||
walletAddress,
|
walletAddress,
|
||||||
firebaseUser,
|
isLoadingAuth,
|
||||||
authMethod
|
authMethod,
|
||||||
|
connectWallet,
|
||||||
|
loginWithEmail
|
||||||
} = useAuth()
|
} = useAuth()
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const hasRedirected = useRef(false)
|
||||||
const [email, setEmail] = useState("")
|
const [email, setEmail] = useState("")
|
||||||
const [password, setPassword] = useState("")
|
const [password, setPassword] = useState("")
|
||||||
const [isEmailLogin, setIsEmailLogin] = useState(false)
|
const [isEmailLogin, setIsEmailLogin] = useState(false)
|
||||||
const [isConnectingWallet, setIsConnectingWallet] = useState(false)
|
|
||||||
const [isSubmittingEmail, setIsSubmittingEmail] = useState(false)
|
const [isSubmittingEmail, setIsSubmittingEmail] = useState(false)
|
||||||
const hasRedirected = useRef(false)
|
|
||||||
|
|
||||||
// ✅ Check for existing authentication
|
// ✅ FIXED: More comprehensive redirect logic with debug logging
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (hasRedirected.current || isLoadingAuth) return
|
console.log("🔍 Login page - checking auth state:", {
|
||||||
|
isLoadingAuth,
|
||||||
|
hasRedirected: hasRedirected.current,
|
||||||
|
user: !!user,
|
||||||
|
firebaseUser: !!firebaseUser,
|
||||||
|
walletConnected,
|
||||||
|
walletAddress,
|
||||||
|
authMethod
|
||||||
|
})
|
||||||
|
|
||||||
const checkAuth = setTimeout(() => {
|
// Don't redirect if still loading or already redirected
|
||||||
if (isLoadingAuth) return
|
if (isLoadingAuth || hasRedirected.current) {
|
||||||
|
console.log("⏳ Skipping redirect - loading or already redirected")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const isAuthenticated = (walletConnected && walletAddress) || firebaseUser
|
// Check for successful authentication
|
||||||
|
const isMetaMaskAuth = walletConnected && walletAddress && user && authMethod === "metamask"
|
||||||
|
const isFirebaseAuth = firebaseUser && authMethod === "firebase"
|
||||||
|
const isAuthenticated = isMetaMaskAuth || isFirebaseAuth
|
||||||
|
|
||||||
if (isAuthenticated && !hasRedirected.current) {
|
console.log("🔍 Authentication check:", {
|
||||||
console.log('✅ User already authenticated, redirecting to dashboard...')
|
isMetaMaskAuth,
|
||||||
hasRedirected.current = true
|
isFirebaseAuth,
|
||||||
|
isAuthenticated
|
||||||
|
})
|
||||||
|
|
||||||
|
if (isAuthenticated && !hasRedirected.current) {
|
||||||
|
console.log("✅ User authenticated - redirecting to dashboard...")
|
||||||
|
hasRedirected.current = true
|
||||||
|
|
||||||
|
// Add a small delay to ensure state is fully updated
|
||||||
|
setTimeout(() => {
|
||||||
router.replace("/dashboard")
|
router.replace("/dashboard")
|
||||||
}
|
}, 100)
|
||||||
}, 500)
|
}
|
||||||
|
}, [
|
||||||
|
user,
|
||||||
|
firebaseUser,
|
||||||
|
walletConnected,
|
||||||
|
walletAddress,
|
||||||
|
authMethod,
|
||||||
|
isLoadingAuth,
|
||||||
|
router
|
||||||
|
]) // ✅ FIXED: Include all necessary dependencies
|
||||||
|
|
||||||
return () => clearTimeout(checkAuth)
|
// ✅ Handle MetaMask connection with immediate redirect check
|
||||||
}, [isLoadingAuth, walletConnected, walletAddress, firebaseUser, router])
|
const handleMetaMaskLogin = async () => {
|
||||||
|
|
||||||
// ✅ Handle MetaMask connection
|
|
||||||
const handleWalletConnect = async () => {
|
|
||||||
if (isConnectingWallet || isLoadingAuth) return
|
|
||||||
|
|
||||||
setIsConnectingWallet(true)
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log('🦊 Starting MetaMask connection...')
|
console.log("🦊 Starting MetaMask login...")
|
||||||
|
await connectWallet()
|
||||||
|
console.log("🦊 MetaMask login completed, checking for redirect...")
|
||||||
|
|
||||||
// Check if MetaMask is installed
|
// Force a redirect check after a short delay
|
||||||
if (typeof window !== 'undefined' && !window.ethereum) {
|
setTimeout(() => {
|
||||||
toast.error("MetaMask not detected. Please install MetaMask extension.")
|
const isAuth = walletConnected && walletAddress && user && authMethod === "metamask"
|
||||||
window.open('https://metamask.io/download/', '_blank')
|
if (isAuth && !hasRedirected.current) {
|
||||||
return
|
console.log("🔄 Force redirecting after MetaMask success...")
|
||||||
}
|
hasRedirected.current = true
|
||||||
|
router.replace("/dashboard")
|
||||||
const success = await connectWallet()
|
}
|
||||||
|
}, 500)
|
||||||
if (success) {
|
} catch (error) {
|
||||||
console.log('✅ MetaMask connection successful')
|
console.error("❌ MetaMask login failed:", error)
|
||||||
// Redirect will be handled by useEffect
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error('❌ Wallet connection error:', error)
|
|
||||||
} finally {
|
|
||||||
setIsConnectingWallet(false)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,8 +103,6 @@ export default function LoginPage() {
|
|||||||
const handleEmailLogin = async (e: React.FormEvent) => {
|
const handleEmailLogin = async (e: React.FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
|
|
||||||
if (isSubmittingEmail || isLoadingAuth) return
|
|
||||||
|
|
||||||
if (!email.trim() || !password.trim()) {
|
if (!email.trim() || !password.trim()) {
|
||||||
toast.error("Please enter both email and password")
|
toast.error("Please enter both email and password")
|
||||||
return
|
return
|
||||||
@@ -96,34 +114,39 @@ export default function LoginPage() {
|
|||||||
await loginWithEmail(email, password)
|
await loginWithEmail(email, password)
|
||||||
// Redirect will be handled by useEffect
|
// Redirect will be handled by useEffect
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error('❌ Email login failed:', error)
|
console.error("❌ Email login failed:", error)
|
||||||
toast.error(error.message || "Login failed. Please check your credentials.")
|
toast.error(error.message || "Login failed")
|
||||||
} finally {
|
} finally {
|
||||||
setIsSubmittingEmail(false)
|
setIsSubmittingEmail(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show connected state
|
// ✅ Show success state when authenticated but not yet redirected
|
||||||
if ((walletConnected && walletAddress) || firebaseUser) {
|
const isAuthenticated = (walletConnected && walletAddress && user) || firebaseUser
|
||||||
|
|
||||||
|
if (isAuthenticated && !hasRedirected.current) {
|
||||||
return (
|
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">
|
<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">
|
<Card className="w-full max-w-md shadow-2xl">
|
||||||
<CardHeader className="text-center">
|
<CardHeader className="text-center">
|
||||||
<CheckCircle2 className="w-12 h-12 text-green-600 mx-auto mb-4" />
|
<CheckCircle2 className="w-12 h-12 text-green-600 mx-auto mb-4" />
|
||||||
<CardTitle className="text-xl font-bold text-green-600">
|
<CardTitle className="text-xl font-bold text-green-600">
|
||||||
{walletConnected ? "MetaMask Connected! 🦊" : "Email Login Successful! 📧"}
|
Login Successful! ✅
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="text-center space-y-4">
|
<CardContent className="text-center space-y-4">
|
||||||
<Alert className="border-green-200 bg-green-50">
|
<p className="text-gray-700">
|
||||||
<AlertDescription className="text-green-700">
|
{authMethod === "metamask"
|
||||||
{walletConnected
|
? `🦊 MetaMask connected: ${walletAddress?.slice(0, 6)}...${walletAddress?.slice(-4)}`
|
||||||
? `🦊 ${walletAddress?.slice(0, 6)}...${walletAddress?.slice(-4)}`
|
: `📧 Email: ${firebaseUser?.email}`
|
||||||
: `📧 ${firebaseUser?.email}`
|
}
|
||||||
}
|
</p>
|
||||||
</AlertDescription>
|
<div className="flex items-center justify-center space-x-2">
|
||||||
</Alert>
|
<Loader2 className="w-4 h-4 animate-spin" />
|
||||||
|
<span>Redirecting to dashboard...</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Manual redirect button as backup */}
|
||||||
<Button
|
<Button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!hasRedirected.current) {
|
if (!hasRedirected.current) {
|
||||||
@@ -131,9 +154,9 @@ export default function LoginPage() {
|
|||||||
router.replace("/dashboard")
|
router.replace("/dashboard")
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
className="w-full"
|
className="w-full mt-4"
|
||||||
>
|
>
|
||||||
Go to Dashboard
|
Go to Dashboard Manually
|
||||||
</Button>
|
</Button>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -141,26 +164,11 @@ export default function LoginPage() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show loading while initializing
|
// ✅ Show login form
|
||||||
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 (
|
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">
|
<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">
|
<Card className="w-full max-w-md shadow-2xl">
|
||||||
<CardHeader className="text-center space-y-4">
|
<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">
|
<CardTitle className="text-2xl font-bold bg-gradient-to-r from-purple-600 to-blue-600 bg-clip-text text-transparent">
|
||||||
Welcome to OpenLearnX! 🎓
|
Welcome to OpenLearnX! 🎓
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
@@ -170,11 +178,11 @@ export default function LoginPage() {
|
|||||||
{/* MetaMask Login */}
|
{/* MetaMask Login */}
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<Button
|
<Button
|
||||||
onClick={handleWalletConnect}
|
onClick={handleMetaMaskLogin}
|
||||||
disabled={isConnectingWallet || isLoadingAuth || isSubmittingEmail}
|
disabled={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"
|
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 ? (
|
{isLoadingAuth ? (
|
||||||
<>
|
<>
|
||||||
<Loader2 className="w-5 h-5 mr-2 animate-spin" />
|
<Loader2 className="w-5 h-5 mr-2 animate-spin" />
|
||||||
Connecting MetaMask...
|
Connecting MetaMask...
|
||||||
@@ -201,7 +209,7 @@ export default function LoginPage() {
|
|||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={() => setIsEmailLogin(!isEmailLogin)}
|
onClick={() => setIsEmailLogin(!isEmailLogin)}
|
||||||
disabled={isConnectingWallet || isSubmittingEmail}
|
disabled={isLoadingAuth || isSubmittingEmail}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
>
|
>
|
||||||
<Mail className="w-4 h-4 mr-2" />
|
<Mail className="w-4 h-4 mr-2" />
|
||||||
@@ -218,7 +226,7 @@ export default function LoginPage() {
|
|||||||
value={email}
|
value={email}
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
placeholder="Enter your email"
|
placeholder="Enter your email"
|
||||||
disabled={isSubmittingEmail || isConnectingWallet}
|
disabled={isSubmittingEmail || isLoadingAuth}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -231,14 +239,14 @@ export default function LoginPage() {
|
|||||||
value={password}
|
value={password}
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
placeholder="Enter your password"
|
placeholder="Enter your password"
|
||||||
disabled={isSubmittingEmail || isConnectingWallet}
|
disabled={isSubmittingEmail || isLoadingAuth}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={isSubmittingEmail || isConnectingWallet || !email.trim() || !password.trim()}
|
disabled={isSubmittingEmail || isLoadingAuth || !email.trim() || !password.trim()}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
>
|
>
|
||||||
{isSubmittingEmail ? (
|
{isSubmittingEmail ? (
|
||||||
@@ -256,23 +264,6 @@ export default function LoginPage() {
|
|||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
</div>
|
</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>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+353
-100
@@ -1,121 +1,374 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import { useAuth } from "@/context/auth-context"
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
import { useRouter } from "next/navigation"
|
import { useRouter } from "next/navigation"
|
||||||
import { useAuth } from "@/context/auth-context"
|
import {
|
||||||
import { DashboardStatsOverview } from "@/components/dashboard-stats"
|
User,
|
||||||
import { Loader2, AlertCircle } from "lucide-react"
|
LogOut,
|
||||||
import { Button } from "@/components/ui/button"
|
Settings,
|
||||||
|
Trophy,
|
||||||
|
BookOpen,
|
||||||
|
Target,
|
||||||
|
TrendingUp,
|
||||||
|
Wallet,
|
||||||
|
Mail,
|
||||||
|
Calendar,
|
||||||
|
Award,
|
||||||
|
BarChart3,
|
||||||
|
Activity,
|
||||||
|
Edit3,
|
||||||
|
Save,
|
||||||
|
X
|
||||||
|
} from "lucide-react"
|
||||||
|
|
||||||
export default function DashboardPage() {
|
export default function DashboardPage() {
|
||||||
const { isLoadingAuth, walletConnected, walletAddress, firebaseUser, authMethod } = useAuth()
|
const { user, firebaseUser, walletConnected, logout, authMethod } = useAuth()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const [showDashboard, setShowDashboard] = useState(false)
|
const [isEditingProfile, setIsEditingProfile] = useState(false)
|
||||||
const [debugInfo, setDebugInfo] = useState<any>(null)
|
const [profileData, setProfileData] = useState({
|
||||||
|
name: user?.name || '',
|
||||||
|
bio: user?.bio || '',
|
||||||
|
avatar: user?.avatar || ''
|
||||||
|
})
|
||||||
|
|
||||||
|
const [stats, setStats] = useState({
|
||||||
|
coursesCompleted: 12,
|
||||||
|
totalXP: 2450,
|
||||||
|
currentStreak: 7,
|
||||||
|
rank: 156,
|
||||||
|
certificatesEarned: 3,
|
||||||
|
hoursLearned: 45
|
||||||
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Debug authentication state
|
if (!user && !firebaseUser) {
|
||||||
const authState = {
|
router.replace("/auth/login")
|
||||||
isLoadingAuth,
|
|
||||||
walletConnected,
|
|
||||||
walletAddress: !!walletAddress,
|
|
||||||
firebaseUser: !!firebaseUser,
|
|
||||||
authMethod,
|
|
||||||
localStorage: {
|
|
||||||
token: !!localStorage.getItem('openlearnx_jwt_token'),
|
|
||||||
wallet: !!localStorage.getItem('openlearnx_wallet'),
|
|
||||||
user: !!localStorage.getItem('openlearnx_user')
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}, [user, firebaseUser, router])
|
||||||
setDebugInfo(authState)
|
|
||||||
console.log('📊 Dashboard auth state:', authState)
|
|
||||||
|
|
||||||
// Give auth some time to initialize
|
const handleProfileUpdate = async () => {
|
||||||
const timer = setTimeout(() => {
|
try {
|
||||||
const isAuthenticated = (walletConnected && walletAddress) || firebaseUser
|
// Here you would call your API to update profile
|
||||||
|
// await updateProfile(profileData)
|
||||||
if (isAuthenticated) {
|
setIsEditingProfile(false)
|
||||||
console.log('✅ User authenticated, showing dashboard')
|
console.log("Profile updated:", profileData)
|
||||||
setShowDashboard(true)
|
} catch (error) {
|
||||||
} else if (!isLoadingAuth) {
|
console.error("Failed to update profile:", error)
|
||||||
console.log('❌ User not authenticated, redirecting to login')
|
}
|
||||||
router.replace("/auth/login")
|
}
|
||||||
}
|
|
||||||
}, 2000) // Wait 2 seconds for auth to stabilize
|
|
||||||
|
|
||||||
return () => clearTimeout(timer)
|
if (!user && !firebaseUser) {
|
||||||
}, [isLoadingAuth, walletConnected, walletAddress, firebaseUser, authMethod, router])
|
|
||||||
|
|
||||||
// Show loading state
|
|
||||||
if (isLoadingAuth || !showDashboard) {
|
|
||||||
return (
|
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="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||||
<div className="text-center space-y-4 max-w-md mx-auto p-6">
|
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
|
||||||
<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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show error state if no auth after loading
|
return (
|
||||||
if (!walletConnected && !firebaseUser && !isLoadingAuth) {
|
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-blue-50">
|
||||||
return (
|
{/* Professional Header */}
|
||||||
<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">
|
<header className="bg-white shadow-lg border-b border-gray-100">
|
||||||
<div className="text-center space-y-4 max-w-md mx-auto p-6">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||||
<AlertCircle className="w-16 h-16 text-red-500 mx-auto" />
|
<div className="flex justify-between items-center h-16">
|
||||||
<h3 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
|
<div className="flex items-center space-x-4">
|
||||||
Authentication Required
|
<div className="flex items-center space-x-3">
|
||||||
</h3>
|
<div className="w-10 h-10 bg-gradient-to-r from-indigo-600 via-purple-600 to-blue-600 rounded-xl flex items-center justify-center shadow-lg">
|
||||||
<p className="text-gray-600 dark:text-gray-400">
|
<BookOpen className="w-6 h-6 text-white" />
|
||||||
Please log in to access your dashboard.
|
</div>
|
||||||
</p>
|
<div>
|
||||||
<div className="space-y-2">
|
<h1 className="text-xl font-bold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">
|
||||||
<Button onClick={() => router.push("/auth/login")} className="w-full">
|
OpenLearnX
|
||||||
Go to Login
|
</h1>
|
||||||
</Button>
|
<p className="text-xs text-gray-500">Learn • Earn • Grow</p>
|
||||||
<Button
|
</div>
|
||||||
variant="outline"
|
</div>
|
||||||
onClick={() => {
|
</div>
|
||||||
localStorage.clear()
|
|
||||||
window.location.href = "/auth/login"
|
<div className="flex items-center space-x-3">
|
||||||
}}
|
<button className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-xl transition-all duration-200">
|
||||||
className="w-full"
|
<Settings className="w-5 h-5" />
|
||||||
>
|
</button>
|
||||||
Clear Data & Login
|
<button
|
||||||
</Button>
|
onClick={logout}
|
||||||
|
className="flex items-center space-x-2 px-4 py-2 text-red-600 hover:text-white hover:bg-red-600 rounded-xl transition-all duration-200 border border-red-200 hover:border-red-600"
|
||||||
|
>
|
||||||
|
<LogOut className="w-4 h-4" />
|
||||||
|
<span className="text-sm font-medium">Logout</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</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>
|
||||||
</div>
|
</header>
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Show dashboard if authenticated
|
{/* Main Dashboard Content */}
|
||||||
return <DashboardStatsOverview />
|
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||||
|
{/* Welcome Section */}
|
||||||
|
<div className="mb-8">
|
||||||
|
<div className="bg-gradient-to-r from-indigo-600 via-purple-600 to-blue-600 rounded-2xl p-8 text-white shadow-xl">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-3xl font-bold mb-2">
|
||||||
|
Welcome back! 👋
|
||||||
|
</h2>
|
||||||
|
<p className="text-indigo-100 text-lg">
|
||||||
|
Ready to continue your learning journey?
|
||||||
|
</p>
|
||||||
|
{authMethod === "metamask" && user ? (
|
||||||
|
<div className="mt-3 flex items-center space-x-2">
|
||||||
|
<Wallet className="w-4 h-4 text-orange-300" />
|
||||||
|
<span className="text-sm text-indigo-100">
|
||||||
|
Connected: {user.wallet_address.slice(0, 6)}...{user.wallet_address.slice(-4)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
) : firebaseUser && (
|
||||||
|
<div className="mt-3 flex items-center space-x-2">
|
||||||
|
<Mail className="w-4 h-4 text-blue-300" />
|
||||||
|
<span className="text-sm text-indigo-100">
|
||||||
|
{firebaseUser.email}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="hidden md:block">
|
||||||
|
<div className="w-32 h-32 bg-white/10 rounded-full flex items-center justify-center backdrop-blur-sm">
|
||||||
|
<Trophy className="w-16 h-16 text-yellow-300" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Stats Grid */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
|
||||||
|
<div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-gray-600 uppercase tracking-wide">Total XP</p>
|
||||||
|
<p className="text-3xl font-bold text-gray-900 mt-1">{stats.totalXP.toLocaleString()}</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4 bg-gradient-to-r from-indigo-500 to-purple-500 rounded-xl shadow-lg">
|
||||||
|
<Trophy className="w-8 h-8 text-white" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center mt-4">
|
||||||
|
<TrendingUp className="w-4 h-4 text-green-500 mr-2" />
|
||||||
|
<span className="text-sm text-green-600 font-medium">+12% from last week</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-gray-600 uppercase tracking-wide">Courses</p>
|
||||||
|
<p className="text-3xl font-bold text-gray-900 mt-1">{stats.coursesCompleted}</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4 bg-gradient-to-r from-green-500 to-teal-500 rounded-xl shadow-lg">
|
||||||
|
<BookOpen className="w-8 h-8 text-white" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center mt-4">
|
||||||
|
<Activity className="w-4 h-4 text-blue-500 mr-2" />
|
||||||
|
<span className="text-sm text-blue-600 font-medium">3 in progress</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-gray-600 uppercase tracking-wide">Streak</p>
|
||||||
|
<p className="text-3xl font-bold text-gray-900 mt-1">{stats.currentStreak} days</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4 bg-gradient-to-r from-orange-500 to-red-500 rounded-xl shadow-lg">
|
||||||
|
<Target className="w-8 h-8 text-white" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center mt-4">
|
||||||
|
<span className="text-sm text-orange-600 font-medium">🔥 Keep it up!</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-gray-600 uppercase tracking-wide">Global Rank</p>
|
||||||
|
<p className="text-3xl font-bold text-gray-900 mt-1">#{stats.rank}</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4 bg-gradient-to-r from-purple-500 to-pink-500 rounded-xl shadow-lg">
|
||||||
|
<BarChart3 className="w-8 h-8 text-white" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center mt-4">
|
||||||
|
<Award className="w-4 h-4 text-purple-500 mr-2" />
|
||||||
|
<span className="text-sm text-purple-600 font-medium">Top 5% learner</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Main Content Grid */}
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
||||||
|
{/* Profile Card with Edit Functionality */}
|
||||||
|
<div className="lg:col-span-1">
|
||||||
|
<div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-6">
|
||||||
|
<div className="flex items-center justify-between mb-6">
|
||||||
|
<h3 className="text-xl font-bold text-gray-900">Profile</h3>
|
||||||
|
<button
|
||||||
|
onClick={() => setIsEditingProfile(!isEditingProfile)}
|
||||||
|
className="p-2 text-gray-500 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-all duration-200"
|
||||||
|
>
|
||||||
|
{isEditingProfile ? <X className="w-5 h-5" /> : <Edit3 className="w-5 h-5" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="text-center mb-6">
|
||||||
|
<div className="w-20 h-20 bg-gradient-to-r from-indigo-600 to-purple-600 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg">
|
||||||
|
<User className="w-10 h-10 text-white" />
|
||||||
|
</div>
|
||||||
|
{isEditingProfile ? (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={profileData.name}
|
||||||
|
onChange={(e) => setProfileData({...profileData, name: e.target.value})}
|
||||||
|
placeholder="Your name"
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-center"
|
||||||
|
/>
|
||||||
|
<textarea
|
||||||
|
value={profileData.bio}
|
||||||
|
onChange={(e) => setProfileData({...profileData, bio: e.target.value})}
|
||||||
|
placeholder="Your bio"
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-center h-20 resize-none"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={handleProfileUpdate}
|
||||||
|
className="flex items-center space-x-2 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors mx-auto"
|
||||||
|
>
|
||||||
|
<Save className="w-4 h-4" />
|
||||||
|
<span>Save</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
<h4 className="text-lg font-semibold text-gray-900">
|
||||||
|
{profileData.name || "Your Name"}
|
||||||
|
</h4>
|
||||||
|
<p className="text-gray-600 text-sm mt-1">
|
||||||
|
{profileData.bio || "Add a bio to tell others about yourself"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between p-4 bg-gradient-to-r from-indigo-50 to-purple-50 rounded-xl border border-indigo-100">
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
{authMethod === "metamask" ? (
|
||||||
|
<Wallet className="w-6 h-6 text-orange-600" />
|
||||||
|
) : (
|
||||||
|
<Mail className="w-6 h-6 text-blue-600" />
|
||||||
|
)}
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-gray-900">Auth Method</p>
|
||||||
|
<p className="text-xs text-gray-600">
|
||||||
|
{authMethod === "metamask" ? "MetaMask Wallet" : "Email Account"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<div className="w-3 h-3 bg-green-500 rounded-full animate-pulse"></div>
|
||||||
|
<span className="text-xs text-green-600 font-medium">Connected</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="text-center p-4 bg-blue-50 rounded-xl">
|
||||||
|
<Calendar className="w-6 h-6 text-blue-600 mx-auto mb-2" />
|
||||||
|
<p className="text-2xl font-bold text-blue-900">{stats.hoursLearned}</p>
|
||||||
|
<p className="text-xs text-blue-600 font-medium">Hours Learned</p>
|
||||||
|
</div>
|
||||||
|
<div className="text-center p-4 bg-green-50 rounded-xl">
|
||||||
|
<Award className="w-6 h-6 text-green-600 mx-auto mb-2" />
|
||||||
|
<p className="text-2xl font-bold text-green-900">{stats.certificatesEarned}</p>
|
||||||
|
<p className="text-xs text-green-600 font-medium">Certificates</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Recent Activity */}
|
||||||
|
<div className="lg:col-span-2">
|
||||||
|
<div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-6">
|
||||||
|
<div className="flex items-center justify-between mb-6">
|
||||||
|
<h3 className="text-xl font-bold text-gray-900">Recent Activity</h3>
|
||||||
|
<button className="text-sm text-indigo-600 hover:text-indigo-800 font-semibold hover:bg-indigo-50 px-3 py-1 rounded-lg transition-all duration-200">
|
||||||
|
View all →
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
{[
|
||||||
|
{
|
||||||
|
type: "course",
|
||||||
|
title: "Completed React Fundamentals",
|
||||||
|
time: "2 hours ago",
|
||||||
|
icon: BookOpen,
|
||||||
|
color: "green",
|
||||||
|
bgColor: "bg-green-100",
|
||||||
|
textColor: "text-green-600"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "quiz",
|
||||||
|
title: "Scored 95% on JavaScript Quiz",
|
||||||
|
time: "1 day ago",
|
||||||
|
icon: Award,
|
||||||
|
color: "blue",
|
||||||
|
bgColor: "bg-blue-100",
|
||||||
|
textColor: "text-blue-600"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "streak",
|
||||||
|
title: "7-day learning streak!",
|
||||||
|
time: "Today",
|
||||||
|
icon: Target,
|
||||||
|
color: "orange",
|
||||||
|
bgColor: "bg-orange-100",
|
||||||
|
textColor: "text-orange-600"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: "rank",
|
||||||
|
title: "Moved up 5 positions in leaderboard",
|
||||||
|
time: "2 days ago",
|
||||||
|
icon: TrendingUp,
|
||||||
|
color: "purple",
|
||||||
|
bgColor: "bg-purple-100",
|
||||||
|
textColor: "text-purple-600"
|
||||||
|
},
|
||||||
|
].map((activity, index) => (
|
||||||
|
<div key={index} className="flex items-center space-x-4 p-4 hover:bg-gray-50 rounded-xl transition-all duration-200 border border-gray-100 hover:border-gray-200 hover:shadow-md">
|
||||||
|
<div className={`p-3 rounded-xl ${activity.bgColor} shadow-sm`}>
|
||||||
|
<activity.icon className={`w-5 h-5 ${activity.textColor}`} />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1">
|
||||||
|
<p className="text-sm font-semibold text-gray-900">{activity.title}</p>
|
||||||
|
<p className="text-xs text-gray-500 mt-1">{activity.time}</p>
|
||||||
|
</div>
|
||||||
|
<div className="w-2 h-2 bg-gray-300 rounded-full"></div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-6 p-4 bg-gradient-to-r from-indigo-50 to-purple-50 rounded-xl border border-indigo-100">
|
||||||
|
<h4 className="text-sm font-semibold text-indigo-900 mb-2">🚀 Keep Learning!</h4>
|
||||||
|
<p className="text-xs text-indigo-700">
|
||||||
|
You're doing great! Complete 2 more courses this week to maintain your streak.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// components/ErrorBoundary.tsx
|
||||||
|
import React from 'react'
|
||||||
|
|
||||||
|
class ErrorBoundary extends React.Component {
|
||||||
|
constructor(props) {
|
||||||
|
super(props)
|
||||||
|
this.state = { hasError: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
static getDerivedStateFromError(error) {
|
||||||
|
return { hasError: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (this.state.hasError) {
|
||||||
|
return <div>Something went wrong. Please refresh the page.</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.props.children
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrap your app
|
||||||
|
<ErrorBoundary>
|
||||||
|
<YourApp />
|
||||||
|
</ErrorBoundary>
|
||||||
@@ -5,7 +5,6 @@ import detectEthereumProvider from "@metamask/detect-provider"
|
|||||||
import { ethers } from "ethers"
|
import { ethers } from "ethers"
|
||||||
import { toast } from "react-hot-toast"
|
import { toast } from "react-hot-toast"
|
||||||
import api from "@/lib/api"
|
import api from "@/lib/api"
|
||||||
import type { AuthNonceRequest, AuthNonceResponse, AuthVerifyRequest, AuthVerifyResponse, User } from "@/lib/types"
|
|
||||||
import { auth } from "@/lib/firebase"
|
import { auth } from "@/lib/firebase"
|
||||||
import {
|
import {
|
||||||
signInWithEmailAndPassword,
|
signInWithEmailAndPassword,
|
||||||
@@ -15,12 +14,24 @@ import {
|
|||||||
type User as FirebaseUser,
|
type User as FirebaseUser,
|
||||||
} from "firebase/auth"
|
} from "firebase/auth"
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
id: string
|
||||||
|
wallet_address: string
|
||||||
|
name?: string
|
||||||
|
bio?: string
|
||||||
|
avatar?: string
|
||||||
|
created_at: string
|
||||||
|
last_login: string
|
||||||
|
}
|
||||||
|
|
||||||
interface AuthContextType {
|
interface AuthContextType {
|
||||||
user: User | null // MetaMask user
|
user: User | null
|
||||||
firebaseUser: FirebaseUser | null // Firebase user
|
firebaseUser: FirebaseUser | null
|
||||||
token: string | null // JWT token from backend (only for MetaMask users)
|
token: string | null
|
||||||
isLoadingAuth: boolean
|
isLoadingAuth: boolean
|
||||||
authMethod: "metamask" | "firebase" | null
|
authMethod: "metamask" | "firebase" | null
|
||||||
|
walletAddress: string | null
|
||||||
|
walletConnected: boolean
|
||||||
connectWallet: () => Promise<void>
|
connectWallet: () => Promise<void>
|
||||||
loginWithEmail: (email: string, password: string) => Promise<void>
|
loginWithEmail: (email: string, password: string) => Promise<void>
|
||||||
signupWithEmail: (email: string, password: string) => Promise<void>
|
signupWithEmail: (email: string, password: string) => Promise<void>
|
||||||
@@ -30,39 +41,39 @@ interface AuthContextType {
|
|||||||
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||||
|
|
||||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
const [user, setUser] = useState<User | null>(null) // For MetaMask user
|
const [user, setUser] = useState<User | null>(null)
|
||||||
const [firebaseUser, setFirebaseUser] = useState<FirebaseUser | null>(null) // For Firebase user
|
const [firebaseUser, setFirebaseUser] = useState<FirebaseUser | null>(null)
|
||||||
const [token, setToken] = useState<string | null>(null) // JWT token
|
const [token, setToken] = useState<string | null>(null)
|
||||||
const [isLoadingAuth, setIsLoadingAuth] = useState(true)
|
const [isLoadingAuth, setIsLoadingAuth] = useState(true)
|
||||||
const [authMethod, setAuthMethod] = useState<"metamask" | "firebase" | null>(null)
|
const [authMethod, setAuthMethod] = useState<"metamask" | "firebase" | null>(null)
|
||||||
|
const [walletAddress, setWalletAddress] = useState<string | null>(null)
|
||||||
|
const [walletConnected, setWalletConnected] = useState(false)
|
||||||
|
|
||||||
|
// Initialize auth state
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Check for MetaMask token
|
|
||||||
const storedToken = localStorage.getItem("openlearnx_jwt_token")
|
const storedToken = localStorage.getItem("openlearnx_jwt_token")
|
||||||
const storedUser = localStorage.getItem("openlearnx_user")
|
const storedUser = localStorage.getItem("openlearnx_user")
|
||||||
if (storedToken && storedUser) {
|
const storedWallet = localStorage.getItem("openlearnx_wallet")
|
||||||
|
|
||||||
|
if (storedToken && storedUser && storedWallet) {
|
||||||
try {
|
try {
|
||||||
setUser(JSON.parse(storedUser))
|
setUser(JSON.parse(storedUser))
|
||||||
setToken(storedToken)
|
setToken(storedToken)
|
||||||
|
setWalletAddress(storedWallet)
|
||||||
|
setWalletConnected(true)
|
||||||
setAuthMethod("metamask")
|
setAuthMethod("metamask")
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to parse stored MetaMask user or token:", error)
|
localStorage.clear()
|
||||||
localStorage.removeItem("openlearnx_jwt_token")
|
|
||||||
localStorage.removeItem("openlearnx_user")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Listen for Firebase auth state changes
|
|
||||||
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
|
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
|
||||||
if (currentUser) {
|
if (currentUser && authMethod !== "metamask") {
|
||||||
setFirebaseUser(currentUser)
|
setFirebaseUser(currentUser)
|
||||||
setAuthMethod("firebase")
|
setAuthMethod("firebase")
|
||||||
} else {
|
} else if (!currentUser && authMethod === "firebase") {
|
||||||
setFirebaseUser(null)
|
setFirebaseUser(null)
|
||||||
if (authMethod !== "metamask") {
|
setAuthMethod(null)
|
||||||
// Only clear if not already MetaMask authenticated
|
|
||||||
setAuthMethod(null)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
setIsLoadingAuth(false)
|
setIsLoadingAuth(false)
|
||||||
})
|
})
|
||||||
@@ -70,26 +81,11 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
return () => unsubscribe()
|
return () => unsubscribe()
|
||||||
}, [authMethod])
|
}, [authMethod])
|
||||||
|
|
||||||
const logout = useCallback(async () => {
|
|
||||||
setUser(null)
|
|
||||||
setFirebaseUser(null)
|
|
||||||
setToken(null)
|
|
||||||
setAuthMethod(null)
|
|
||||||
localStorage.removeItem("openlearnx_jwt_token")
|
|
||||||
localStorage.removeItem("openlearnx_user")
|
|
||||||
try {
|
|
||||||
await signOut(auth) // Sign out from Firebase
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error signing out from Firebase:", error)
|
|
||||||
}
|
|
||||||
toast.success("Logged out successfully!")
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const connectWallet = useCallback(async () => {
|
const connectWallet = useCallback(async () => {
|
||||||
setIsLoadingAuth(true)
|
setIsLoadingAuth(true)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const provider = await detectEthereumProvider()
|
const provider = await detectEthereumProvider()
|
||||||
|
|
||||||
if (!provider) {
|
if (!provider) {
|
||||||
toast.error("MetaMask not detected. Please install it.")
|
toast.error("MetaMask not detected. Please install it.")
|
||||||
return
|
return
|
||||||
@@ -97,64 +93,81 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
|
|
||||||
const ethProvider = new ethers.BrowserProvider(provider as any)
|
const ethProvider = new ethers.BrowserProvider(provider as any)
|
||||||
const accounts = await ethProvider.send("eth_requestAccounts", [])
|
const accounts = await ethProvider.send("eth_requestAccounts", [])
|
||||||
|
|
||||||
if (accounts.length === 0) {
|
if (accounts.length === 0) {
|
||||||
toast.error("No accounts connected.")
|
toast.error("No accounts connected.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const walletAddress = accounts[0]
|
const walletAddr = accounts[0]
|
||||||
|
|
||||||
// 1. Request Nonce
|
// Get nonce from backend
|
||||||
const nonceResponse = await api.post<AuthNonceResponse>("/api/auth/nonce", {
|
const nonceResponse = await api.post("/api/auth/nonce", {
|
||||||
wallet_address: walletAddress,
|
wallet_address: walletAddr,
|
||||||
} as AuthNonceRequest)
|
})
|
||||||
const { nonce, message } = nonceResponse.data
|
|
||||||
|
if (!nonceResponse.data.success) {
|
||||||
|
throw new Error(nonceResponse.data.error || "Failed to get nonce")
|
||||||
|
}
|
||||||
|
|
||||||
// 2. Sign Message
|
const { message } = nonceResponse.data
|
||||||
|
|
||||||
|
// Sign message
|
||||||
const signer = await ethProvider.getSigner()
|
const signer = await ethProvider.getSigner()
|
||||||
const signature = await signer.signMessage(message)
|
const signature = await signer.signMessage(message)
|
||||||
|
|
||||||
// 3. Verify Signature
|
// Verify signature
|
||||||
const verifyResponse = await api.post<AuthVerifyResponse>("/api/auth/verify", {
|
const verifyResponse = await api.post("/api/auth/verify", {
|
||||||
wallet_address: walletAddress,
|
wallet_address: walletAddr,
|
||||||
signature,
|
signature,
|
||||||
message,
|
message,
|
||||||
} as AuthVerifyRequest)
|
})
|
||||||
|
|
||||||
if (verifyResponse.data.success) {
|
if (verifyResponse.data.success) {
|
||||||
const { token: newToken, user: newUser } = verifyResponse.data
|
const { token, user } = verifyResponse.data
|
||||||
setToken(newToken)
|
|
||||||
setUser(newUser)
|
// Update states
|
||||||
setFirebaseUser(null) // Clear Firebase user if MetaMask logs in
|
setToken(token)
|
||||||
|
setUser(user)
|
||||||
|
setWalletAddress(walletAddr)
|
||||||
|
setWalletConnected(true)
|
||||||
|
setFirebaseUser(null)
|
||||||
setAuthMethod("metamask")
|
setAuthMethod("metamask")
|
||||||
localStorage.setItem("openlearnx_jwt_token", newToken)
|
|
||||||
localStorage.setItem("openlearnx_user", JSON.stringify(newUser))
|
// Store in localStorage
|
||||||
toast.success(`Welcome, ${newUser.wallet_address.slice(0, 6)}...${newUser.wallet_address.slice(-4)}!`)
|
localStorage.setItem("openlearnx_jwt_token", token)
|
||||||
|
localStorage.setItem("openlearnx_user", JSON.stringify(user))
|
||||||
|
localStorage.setItem("openlearnx_wallet", walletAddr)
|
||||||
|
|
||||||
|
toast.success(`Welcome! 🦊`)
|
||||||
|
|
||||||
|
// ✅ CRITICAL: Redirect to dashboard after successful login
|
||||||
|
setTimeout(() => {
|
||||||
|
window.location.href = "/dashboard"
|
||||||
|
}, 1000)
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
toast.error("MetaMask authentication failed. Please try again.")
|
throw new Error("Authentication failed")
|
||||||
logout()
|
|
||||||
}
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error("MetaMask authentication error:", error)
|
console.error("MetaMask error:", error)
|
||||||
toast.error(error.message || "Failed to connect wallet or authenticate.")
|
toast.error(error.message || "Failed to connect MetaMask")
|
||||||
logout()
|
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoadingAuth(false)
|
setIsLoadingAuth(false)
|
||||||
}
|
}
|
||||||
}, [logout])
|
}, [])
|
||||||
|
|
||||||
const loginWithEmail = useCallback(async (email: string, password: string) => {
|
const loginWithEmail = useCallback(async (email: string, password: string) => {
|
||||||
setIsLoadingAuth(true)
|
setIsLoadingAuth(true)
|
||||||
try {
|
try {
|
||||||
await signInWithEmailAndPassword(auth, email, password)
|
await signInWithEmailAndPassword(auth, email, password)
|
||||||
// Firebase user is set by onAuthStateChanged listener
|
setUser(null)
|
||||||
setUser(null) // Clear MetaMask user if Firebase logs in
|
setToken(null)
|
||||||
setToken(null) // Clear JWT token
|
setWalletAddress(null)
|
||||||
|
setWalletConnected(false)
|
||||||
toast.success("Logged in with email!")
|
toast.success("Logged in with email!")
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error("Firebase login error:", error)
|
toast.error(error.message || "Email login failed")
|
||||||
toast.error(error.message || "Failed to login with email.")
|
throw error
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoadingAuth(false)
|
setIsLoadingAuth(false)
|
||||||
}
|
}
|
||||||
@@ -164,40 +177,57 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
setIsLoadingAuth(true)
|
setIsLoadingAuth(true)
|
||||||
try {
|
try {
|
||||||
await createUserWithEmailAndPassword(auth, email, password)
|
await createUserWithEmailAndPassword(auth, email, password)
|
||||||
// Firebase user is set by onAuthStateChanged listener
|
toast.success("Account created!")
|
||||||
setUser(null) // Clear MetaMask user if Firebase logs in
|
|
||||||
setToken(null) // Clear JWT token
|
|
||||||
toast.success("Signed up and logged in with email!")
|
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error("Firebase signup error:", error)
|
toast.error(error.message || "Signup failed")
|
||||||
toast.error(error.message || "Failed to sign up with email.")
|
throw error
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoadingAuth(false)
|
setIsLoadingAuth(false)
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const contextValue = React.useMemo(
|
const logout = useCallback(async () => {
|
||||||
() => ({
|
setUser(null)
|
||||||
user,
|
setFirebaseUser(null)
|
||||||
firebaseUser,
|
setToken(null)
|
||||||
token,
|
setWalletAddress(null)
|
||||||
isLoadingAuth,
|
setWalletConnected(false)
|
||||||
authMethod,
|
setAuthMethod(null)
|
||||||
connectWallet,
|
localStorage.clear()
|
||||||
loginWithEmail,
|
|
||||||
signupWithEmail,
|
try {
|
||||||
logout,
|
await signOut(auth)
|
||||||
}),
|
} catch (error) {
|
||||||
[user, firebaseUser, token, isLoadingAuth, authMethod, connectWallet, loginWithEmail, signupWithEmail, logout],
|
console.error("Logout error:", error)
|
||||||
)
|
}
|
||||||
|
|
||||||
|
toast.success("Logged out!")
|
||||||
|
}, [])
|
||||||
|
|
||||||
return <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
|
const value = {
|
||||||
|
user,
|
||||||
|
firebaseUser,
|
||||||
|
token,
|
||||||
|
isLoadingAuth,
|
||||||
|
authMethod,
|
||||||
|
walletAddress,
|
||||||
|
walletConnected,
|
||||||
|
connectWallet,
|
||||||
|
loginWithEmail,
|
||||||
|
signupWithEmail,
|
||||||
|
logout,
|
||||||
|
}
|
||||||
|
|
||||||
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAuth() {
|
export function useAuth() {
|
||||||
const context = useContext(AuthContext)
|
const context = useContext(AuthContext)
|
||||||
if (context === undefined) {
|
if (!context) {
|
||||||
throw new Error("useAuth must be used within an AuthProvider")
|
throw new Error("useAuth must be used within an AuthProvider")
|
||||||
}
|
}
|
||||||
return context
|
return context
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ✅ CRITICAL: Default export to fix the "invalid element type" error
|
||||||
|
export default AuthProvider
|
||||||
|
|||||||
Reference in New Issue
Block a user