feat: unify real activity tracking, admin monitoring, and error UX

This commit is contained in:
Stalin
2026-04-19 17:50:53 +05:30
parent 23e4e587bd
commit 53308f698e
86 changed files with 9002 additions and 2838 deletions
+137 -72
View File
@@ -20,7 +20,6 @@ export function LoginComponent() {
walletConnected,
walletAddress,
user,
firebaseUser,
authMethod
} = useAuth()
@@ -29,23 +28,21 @@ export function LoginComponent() {
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [isEmailLogin, setIsEmailLogin] = useState(false)
const [isSignup, setIsSignup] = useState(false)
const [username, setUsername] = useState("")
const [isConnectingWallet, setIsConnectingWallet] = useState(false)
const [connectionStatus, setConnectionStatus] = useState<'idle' | 'connecting' | 'connected' | 'error'>('idle')
// ✅ Check if user is already authenticated
useEffect(() => {
if (!isLoadingAuth) {
if (walletConnected && walletAddress) {
console.log('✅ MetaMask already connected:', walletAddress)
if (user && authMethod) {
console.log('✅ User already authenticated:', authMethod)
setConnectionStatus('connected')
toast.success("Already connected to MetaMask!")
router.push("/dashboard")
} else if (firebaseUser) {
console.log('✅ Firebase user already logged in:', firebaseUser.email)
router.push("/dashboard")
}
}
}, [isLoadingAuth, walletConnected, walletAddress, firebaseUser, router])
}, [isLoadingAuth, user, authMethod, router])
const handleWalletConnect = async () => {
setIsConnectingWallet(true)
@@ -66,7 +63,6 @@ export function LoginComponent() {
if (success) {
setConnectionStatus('connected')
console.log('✅ MetaMask connection successful')
toast.success("MetaMask connected successfully! 🦊")
// Small delay to ensure state is updated
setTimeout(() => {
@@ -74,19 +70,10 @@ export function LoginComponent() {
}, 1000)
} else {
setConnectionStatus('error')
toast.error("Failed to connect MetaMask. Please try again.")
}
} catch (error: any) {
console.error('❌ Wallet connection error:', error)
setConnectionStatus('error')
if (error.message?.includes('User rejected')) {
toast.error("Connection cancelled by user.")
} else if (error.message?.includes('MetaMask not detected')) {
toast.error("Please install MetaMask extension.")
} else {
toast.error("MetaMask connection failed. Please try again.")
}
} finally {
setIsConnectingWallet(false)
}
@@ -107,17 +94,48 @@ export function LoginComponent() {
try {
console.log('📧 Attempting email login for:', email)
await loginWithEmail(email, password)
toast.success("Logged in successfully!")
router.push("/dashboard")
const success = await loginWithEmail(email, password)
if (success) {
setTimeout(() => router.push("/dashboard"), 500)
}
} catch (error: any) {
console.error('❌ Email login failed:', error)
toast.error(error.message || "Login failed. Please check your credentials.")
}
}
const { signupWithEmail } = useAuth()
const handleEmailSignup = async (e: React.FormEvent) => {
e.preventDefault()
if (!email.trim() || !password.trim() || !username.trim()) {
toast.error("Please fill in all fields")
return
}
if (!email.includes('@')) {
toast.error("Please enter a valid email address")
return
}
if (password.length < 6) {
toast.error("Password must be at least 6 characters")
return
}
try {
console.log('📧 Attempting email signup for:', email)
const success = await signupWithEmail(email, password, username)
if (success) {
setTimeout(() => router.push("/dashboard"), 500)
}
} catch (error: any) {
console.error('❌ Email signup failed:', error)
}
}
// ✅ Show connected state if already authenticated
if (connectionStatus === 'connected' || (walletConnected && walletAddress)) {
if (user && authMethod) {
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 border-0 bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm">
@@ -126,14 +144,18 @@ export function LoginComponent() {
<CheckCircle2 className="w-6 h-6 text-green-600" />
</div>
<CardTitle className="text-xl font-bold text-green-600">
MetaMask Connected! 🦊
{authMethod === 'metamask' ? 'MetaMask Connected' : 'Logged In'}
</CardTitle>
</CardHeader>
<CardContent className="text-center space-y-4">
<Alert className="border-green-200 bg-green-50 dark:bg-green-900/20">
<Wallet className="w-4 h-4 text-green-600" />
<AlertDescription className="text-green-700 dark:text-green-300">
🦊 {walletAddress?.slice(0, 6)}...{walletAddress?.slice(-4)}
{authMethod === 'metamask' && walletAddress ? (
<>{walletAddress.slice(0, 6)}...{walletAddress.slice(-4)}</>
) : (
<>{user.email}</>
)}
</AlertDescription>
</Alert>
@@ -146,7 +168,7 @@ export function LoginComponent() {
onClick={() => window.location.reload()}
className="w-full"
>
Connect Different Wallet
Logout
</Button>
</div>
</CardContent>
@@ -154,6 +176,12 @@ export function LoginComponent() {
</div>
)
}
</div>
</CardContent>
</Card>
</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">
@@ -165,7 +193,7 @@ export function LoginComponent() {
<div className="space-y-2">
<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>
<p className="text-gray-600 dark:text-gray-300">
Connect your MetaMask wallet or login with email
@@ -194,14 +222,14 @@ export function LoginComponent() {
) : (
<>
<Wallet className="w-5 h-5 mr-2" />
Connect MetaMask Wallet 🦊
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, blockchain verification, and token rewards!
Recommended: Get Web3 features, blockchain verification, and token rewards.
</p>
</div>
</div>
@@ -223,55 +251,92 @@ export function LoginComponent() {
className="w-full"
>
<Mail className="w-4 h-4 mr-2" />
{isEmailLogin ? 'Hide Email Login' : 'Login with Email'}
{isEmailLogin ? 'Hide Email Options' : 'Login with Email'}
</Button>
{isEmailLogin && (
<form onSubmit={handleEmailLogin} className="space-y-4 mt-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={isLoadingAuth}
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={isLoadingAuth}
required
/>
<div className="space-y-4 mt-4">
{/* Toggle between Login and Signup */}
<div className="flex gap-2 bg-gray-100 dark:bg-gray-700 p-1 rounded-lg">
<Button
variant={!isSignup ? "default" : "ghost"}
size="sm"
onClick={() => setIsSignup(false)}
className="flex-1"
>
Login
</Button>
<Button
variant={isSignup ? "default" : "ghost"}
size="sm"
onClick={() => setIsSignup(true)}
className="flex-1"
>
Sign Up
</Button>
</div>
<Button
type="submit"
disabled={isLoadingAuth || !email.trim() || !password.trim()}
className="w-full"
>
{isLoadingAuth ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Logging in...
</>
) : (
<>
<Lock className="w-4 h-4 mr-2" />
Login with Email
</>
<form onSubmit={isSignup ? handleEmailSignup : handleEmailLogin} className="space-y-4">
{isSignup && (
<div>
<Label htmlFor="username">Username</Label>
<Input
id="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Choose a username"
disabled={isLoadingAuth}
required={isSignup}
/>
</div>
)}
</Button>
</form>
<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={isLoadingAuth}
required
/>
</div>
<div>
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={isSignup ? "Create a password (min 6 characters)" : "Enter your password"}
disabled={isLoadingAuth}
required
/>
</div>
<Button
type="submit"
disabled={isLoadingAuth || !email.trim() || !password.trim() || (isSignup && !username.trim())}
className="w-full"
>
{isLoadingAuth ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
{isSignup ? 'Creating Account...' : 'Logging in...'}
</>
) : (
<>
<Lock className="w-4 h-4 mr-2" />
{isSignup ? 'Create Account' : 'Login'}
</>
)}
</Button>
</form>
</div>
)}
</div>
@@ -0,0 +1,49 @@
"use client"
import { useMemo } from "react"
import { usePathname } from "next/navigation"
import { ShieldAlert } from "lucide-react"
import { useAuth } from "@/context/auth-context"
const BLOCKED_STATUSES = new Set(["suspended", "restricted", "banned"])
export function AccountStatusGuard() {
const pathname = usePathname()
const { user, isLoadingAuth, logout } = useAuth()
const status = useMemo(() => String((user as any)?.status || "active").toLowerCase().trim(), [user])
const skipGuard = pathname.startsWith("/auth/") || pathname === "/admin/login"
if (skipGuard || isLoadingAuth || !user) return null
if (!BLOCKED_STATUSES.has(status)) return null
const title = status === "banned" ? "Account Banned" : "Account Suspended"
const message =
status === "banned"
? "Your account is banned. You cannot use OpenLearnX with this account. Contact admin for support."
: "Your account is suspended. Contact admin to restore access."
return (
<div className="fixed inset-0 z-[9999] flex items-center justify-center bg-white p-4 dark:bg-slate-950">
<div className="w-full max-w-xl rounded-2xl border-2 border-red-200 bg-white p-7 text-center shadow-xl dark:border-red-900 dark:bg-slate-900">
<div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-300">
<ShieldAlert className="h-7 w-7" />
</div>
<h2 className="text-2xl font-semibold text-gray-900 dark:text-white">{title}</h2>
<p className="mt-2 inline-flex rounded-full bg-red-100 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-red-700 dark:bg-red-950 dark:text-red-200">
Status: {status}
</p>
<p className="mt-3 text-sm text-gray-700 dark:text-gray-300">{message}</p>
<p className="mt-2 text-sm font-medium text-red-700 dark:text-red-300">Contact admin.</p>
<div className="mt-5">
<button
onClick={() => logout()}
className="rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700"
>
Logout
</button>
</div>
</div>
</div>
)
}
+113 -54
View File
@@ -8,37 +8,56 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { toast } from "react-hot-toast"
export function AuthButtons() {
const { user, firebaseUser, isLoadingAuth, authMethod, connectWallet, loginWithEmail, signupWithEmail, logout } =
useAuth()
const { user, isLoadingAuth, authMethod, connectWallet, loginWithEmail, signupWithEmail, logout } = useAuth()
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const [username, setUsername] = useState("")
const [isAuthModalOpen, setIsAuthModalOpen] = useState(false)
const handleEmailLogin = async () => {
await loginWithEmail(email, password)
setIsAuthModalOpen(false)
if (!email.trim() || !password.trim()) {
toast.error("Please enter email and password")
return
}
const success = await loginWithEmail(email, password)
if (success) {
setIsAuthModalOpen(false)
setEmail("")
setPassword("")
}
}
const handleEmailSignup = async () => {
await signupWithEmail(email, password)
setIsAuthModalOpen(false)
if (!email.trim() || !password.trim() || !username.trim()) {
toast.error("Please fill in all fields")
return
}
if (password.length < 6) {
toast.error("Password must be at least 6 characters")
return
}
const success = await signupWithEmail(email, password, username)
if (success) {
setIsAuthModalOpen(false)
setEmail("")
setPassword("")
setUsername("")
}
}
const displayAddress = user?.wallet_address || firebaseUser?.email || "Guest"
const displayAddress = user?.wallet_address || user?.email || "Guest"
return (
<div className="flex items-center gap-4">
{authMethod ? (
{authMethod && user ? (
<>
<span className="text-sm text-gray-600 dark:text-gray-300">
Connected:{" "}
{authMethod === "metamask" && user?.wallet_address
{authMethod === "metamask" && user.wallet_address
? `${user.wallet_address.slice(0, 6)}...${user.wallet_address.slice(-4)}`
: authMethod === "firebase" && firebaseUser?.email
? firebaseUser.email
: displayAddress}
: user.email || displayAddress}
</span>
<Button onClick={logout} variant="outline" disabled={isLoadingAuth}>
Logout
@@ -76,48 +95,88 @@ export function AuthButtons() {
</TabsContent>
<TabsContent value="email" className="space-y-4 p-4">
<p className="text-sm text-gray-600 dark:text-gray-300">
Use email for a quick testing process (quizzes only).
Use email to access courses and quizzes.
</p>
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="your@email.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="dark:bg-gray-700 dark:border-gray-600"
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="dark:bg-gray-700 dark:border-gray-600"
/>
</div>
<div className="flex gap-2">
<Button
onClick={handleEmailLogin}
disabled={isLoadingAuth}
className="flex-1 bg-primary-purple hover:bg-primary-purple/90 text-white"
>
{isLoadingAuth && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Login
</Button>
<Button
onClick={handleEmailSignup}
disabled={isLoadingAuth}
variant="outline"
className="flex-1 dark:text-gray-100 dark:border-gray-600 bg-transparent"
>
{isLoadingAuth && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Sign Up
</Button>
</div>
<Tabs defaultValue="login" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="login">Login</TabsTrigger>
<TabsTrigger value="signup">Sign Up</TabsTrigger>
</TabsList>
<TabsContent value="login" className="space-y-3">
<div className="space-y-2">
<Label htmlFor="login-email">Email</Label>
<Input
id="login-email"
type="email"
placeholder="your@email.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="dark:bg-gray-700 dark:border-gray-600"
/>
</div>
<div className="space-y-2">
<Label htmlFor="login-password">Password</Label>
<Input
id="login-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="dark:bg-gray-700 dark:border-gray-600"
/>
</div>
<Button
onClick={handleEmailLogin}
disabled={isLoadingAuth}
className="w-full bg-primary-purple hover:bg-primary-purple/90 text-white"
>
{isLoadingAuth && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Login
</Button>
</TabsContent>
<TabsContent value="signup" className="space-y-3">
<div className="space-y-2">
<Label htmlFor="signup-username">Username</Label>
<Input
id="signup-username"
type="text"
placeholder="Choose a username"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="dark:bg-gray-700 dark:border-gray-600"
/>
</div>
<div className="space-y-2">
<Label htmlFor="signup-email">Email</Label>
<Input
id="signup-email"
type="email"
placeholder="your@email.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="dark:bg-gray-700 dark:border-gray-600"
/>
</div>
<div className="space-y-2">
<Label htmlFor="signup-password">Password</Label>
<Input
id="signup-password"
type="password"
placeholder="Min 6 characters"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="dark:bg-gray-700 dark:border-gray-600"
/>
</div>
<Button
onClick={handleEmailSignup}
disabled={isLoadingAuth}
className="w-full bg-primary-purple hover:bg-primary-purple/90 text-white"
>
{isLoadingAuth && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Create Account
</Button>
</TabsContent>
</Tabs>
</TabsContent>
</Tabs>
</DialogContent>
+6 -6
View File
@@ -13,15 +13,15 @@ import { Loader2, CheckCircle2 } from "lucide-react"
import { api } from "@/lib/api" // Import api
export function CodingProblemList() {
const { user, firebaseUser, isLoadingAuth, authMethod, token } = useAuth() // Check token for access
const { user, isLoadingAuth, authMethod, token } = useAuth() // Check token for access
const router = useRouter()
const [problems, setProblems] = useState<CodingProblem[]>([])
const [isLoadingProblems, setIsLoadingProblems] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!isLoadingAuth && !user && !firebaseUser) {
// Allow either MetaMask or Firebase user
if (!isLoadingAuth && !user) {
// Allow MetaMask or email auth
toast.error("Please login to view coding problems.")
router.push("/")
return
@@ -44,11 +44,11 @@ export function CodingProblemList() {
}
}
if (user || firebaseUser) {
// Only fetch if either user type is logged in
if (user) {
// Only fetch if user is logged in
fetchProblems()
}
}, [user, firebaseUser, isLoadingAuth, router, token])
}, [user, isLoadingAuth, router, token])
const getDifficultyColor = (difficulty: CodingProblem["difficulty"]) => {
switch (difficulty) {
+6 -6
View File
@@ -17,7 +17,7 @@ interface CodingProblemViewProps {
}
export function CodingProblemView({ problemId }: CodingProblemViewProps) {
const { user, firebaseUser, isLoadingAuth, authMethod, token } = useAuth() // Check token for access
const { user, isLoadingAuth, authMethod, token } = useAuth() // Check token for access
const router = useRouter()
const [problem, setProblem] = useState<CodingProblem | null>(null)
const [code, setCode] = useState<string>("")
@@ -31,8 +31,8 @@ export function CodingProblemView({ problemId }: CodingProblemViewProps) {
const availableLanguages = ["python", "javascript", "java"] // Example languages
useEffect(() => {
if (!isLoadingAuth && !user && !firebaseUser) {
// Allow either MetaMask or Firebase user
if (!isLoadingAuth && !user) {
// Allow either MetaMask or email auth
toast.error("Please login to view coding problems.")
router.push("/")
return
@@ -64,11 +64,11 @@ export function CodingProblemView({ problemId }: CodingProblemViewProps) {
}
}
if (user || firebaseUser) {
// Only fetch if either user type is logged in
if (user) {
// Only fetch if user is logged in
fetchProblem()
}
}, [user, firebaseUser, isLoadingAuth, router, problemId, language, token])
}, [user, isLoadingAuth, router, problemId, language, token])
const handleRunCode = async () => {
if (!problem || !code || !token) {
+7 -7
View File
@@ -13,15 +13,15 @@ import { Loader2 } from "lucide-react"
import api from "@/lib/api" // Corrected import: default import
export function CourseList() {
const { user, firebaseUser, isLoadingAuth, authMethod, token } = useAuth() // Check token for access
const { user, isLoadingAuth, authMethod, token } = useAuth() // Check token for access
const router = useRouter()
const [courses, setCourses] = useState<Course[]>([])
const [isLoadingCourses, setIsLoadingCourses] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!isLoadingAuth && !user && !firebaseUser) {
// Allow either MetaMask or Firebase user
if (!isLoadingAuth && !user) {
// Allow either MetaMask or email auth
toast.error("Please login to view courses.")
router.push("/")
return
@@ -49,11 +49,11 @@ export function CourseList() {
}
}
if (user || firebaseUser) {
// Fetch if either user type is logged in
if (user) {
// Fetch if user is logged in
fetchCourses()
}
}, [user, firebaseUser, isLoadingAuth, router, token])
}, [user, isLoadingAuth, router, token])
if (isLoadingAuth || isLoadingCourses) {
return (
@@ -97,7 +97,7 @@ export function CourseList() {
{courses.map((course) => (
<Card
key={course.id}
className="bg-white shadow-md rounded-lg overflow-hidden dark:bg-gray-800 dark:text-gray-100"
className="bg-white shadow-md rounded-lg overflow-hidden dark:bg-[#22314a] dark:text-gray-100 dark:border-blue-300/20"
>
<CardHeader>
<CardTitle className="text-xl font-semibold">{course.title}</CardTitle>
+14 -9
View File
@@ -69,6 +69,7 @@ interface ActivityData {
title: string
description: string
completed_at: string
timestamp_utc?: string
points_earned: number
blockchain_verified?: boolean
}
@@ -185,14 +186,18 @@ export function DashboardStatsOverview() {
fetchPureMongoDBData()
}
const formatTimeAgo = (dateString: string) => {
const diff = Date.now() - new Date(dateString).getTime()
const hours = Math.floor(diff / (1000 * 60 * 60))
const days = Math.floor(hours / 24)
if (days > 0) return `${days}d ago`
if (hours > 0) return `${hours}h ago`
return 'Just now'
const formatUtcTimestamp = (dateString: string) => {
const date = new Date(dateString)
if (Number.isNaN(date.getTime())) return "Invalid time"
const y = date.getUTCFullYear()
const m = String(date.getUTCMonth() + 1).padStart(2, "0")
const d = String(date.getUTCDate()).padStart(2, "0")
const hh = String(date.getUTCHours()).padStart(2, "0")
const mm = String(date.getUTCMinutes()).padStart(2, "0")
const ss = String(date.getUTCSeconds()).padStart(2, "0")
return `${y}-${m}-${d} ${hh}:${mm}:${ss} UTC`
}
const getRarityColor = (rarity: string) => {
@@ -566,7 +571,7 @@ export function DashboardStatsOverview() {
<p className="text-xs text-gray-600 dark:text-gray-400">{item.description}</p>
<div className="flex items-center justify-between">
<span className="text-xs text-gray-500">
{formatTimeAgo(item.completed_at)}
{item.timestamp_utc || formatUtcTimestamp(item.completed_at)}
</span>
<span className="text-xs font-medium text-green-600">
+{item.points_earned} XP
+4 -4
View File
@@ -30,7 +30,7 @@ interface LessonData {
}
export function LessonViewer({ courseId, lessonId }: LessonViewerProps) {
const { user, firebaseUser, isLoadingAuth, authMethod, token } = useAuth()
const { user, isLoadingAuth, authMethod, token } = useAuth()
const router = useRouter()
const [lesson, setLesson] = useState<LessonData | null>(null)
const [isLoadingLesson, setIsLoadingLesson] = useState(true)
@@ -38,7 +38,7 @@ export function LessonViewer({ courseId, lessonId }: LessonViewerProps) {
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!isLoadingAuth && !user && !firebaseUser) {
if (!isLoadingAuth && !user) {
toast.error("Please login to view lessons.")
router.push("/")
return
@@ -76,10 +76,10 @@ export function LessonViewer({ courseId, lessonId }: LessonViewerProps) {
}
}
if (user || firebaseUser) {
if (user) {
fetchLesson()
}
}, [user, firebaseUser, isLoadingAuth, router, courseId, lessonId, token])
}, [user, isLoadingAuth, router, courseId, lessonId, token])
const markLessonCompleted = async () => {
if (!lesson || lesson.completed || !token) {
@@ -0,0 +1,161 @@
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Loader2, X } from "lucide-react"
import { toast } from "react-hot-toast"
import api from "@/lib/api"
interface MetaMaskEmailModalProps {
isOpen: boolean
walletAddress: string
token: string
onSuccess: (user: any) => void
onCancel: () => void
}
export function MetaMaskEmailModal({
isOpen,
walletAddress,
token,
onSuccess,
onCancel,
}: MetaMaskEmailModalProps) {
const [email, setEmail] = useState("")
const [name, setName] = useState("")
const [isSubmitting, setIsSubmitting] = useState(false)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!email.trim()) {
toast.error("Please enter your email address")
return
}
if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)) {
toast.error("Please enter a valid email address")
return
}
setIsSubmitting(true)
try {
const response = await api.post(
"/api/auth/metamask/add-email",
{
email: email.toLowerCase(),
name: name.trim(),
},
{
headers: {
Authorization: `Bearer ${token}`,
},
}
)
if (response.data.success && response.data.user) {
toast.success("Email saved successfully!")
onSuccess(response.data.user)
} else {
toast.error(response.data.error || "Failed to save email")
}
} catch (error: any) {
console.error("Error saving email:", error)
toast.error(
error.response?.data?.error || "Failed to save email address"
)
} finally {
setIsSubmitting(false)
}
}
if (!isOpen) return null
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<Card className="w-full max-w-md shadow-2xl">
<CardHeader className="flex flex-row items-center justify-between space-y-0">
<CardTitle className="text-xl font-bold">Save Contact Email</CardTitle>
<button
onClick={onCancel}
className="p-1 hover:bg-gray-100 rounded-lg transition"
disabled={isSubmitting}
>
<X className="w-5 h-5 text-gray-500" />
</button>
</CardHeader>
<CardContent>
<div className="space-y-4 mb-6">
<p className="text-sm text-gray-600">
Connected wallet: <span className="font-mono font-semibold">{walletAddress.slice(0, 6)}...{walletAddress.slice(-4)}</span>
</p>
<p className="text-sm text-gray-600">
Add your contact email and name to complete your profile setup.
</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<Label htmlFor="name">Display Name (optional)</Label>
<Input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
disabled={isSubmitting}
/>
</div>
<div>
<Label htmlFor="email">Contact Email</Label>
<Input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email address"
disabled={isSubmitting}
required
/>
<p className="text-xs text-gray-500 mt-1">
We will use this to verify your account and send important updates
</p>
</div>
<div className="flex gap-3 pt-4">
<Button
type="submit"
disabled={isSubmitting || !email.trim()}
className="flex-1 bg-purple-600 hover:bg-purple-700"
>
{isSubmitting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Saving...
</>
) : (
"Save Email"
)}
</Button>
<Button
type="button"
onClick={onCancel}
disabled={isSubmitting}
variant="outline"
className="flex-1"
>
Skip for Now
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
)
}
+6 -6
View File
@@ -15,15 +15,15 @@ import { Loader2 } from "lucide-react"
import api from "@/lib/api" // Import api
export function QuizList() {
const { user, firebaseUser, isLoadingAuth, authMethod, token } = useAuth() // Check token for access
const { user, isLoadingAuth, authMethod, token } = useAuth() // Check token for access
const router = useRouter()
const [quizzes, setQuizzes] = useState<Quiz[]>([])
const [isLoadingQuizzes, setIsLoadingQuizzes] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!isLoadingAuth && !user && !firebaseUser) {
// Allow either MetaMask or Firebase user
if (!isLoadingAuth && !user) {
// Allow MetaMask or email auth
toast.error("Please login to view quizzes.")
router.push("/")
return
@@ -46,11 +46,11 @@ export function QuizList() {
}
}
if (user || firebaseUser) {
// Fetch if either user type is logged in
if (user) {
// Fetch if user is logged in
fetchQuizzes()
}
}, [user, firebaseUser, isLoadingAuth, router, token])
}, [user, isLoadingAuth, router, token])
const getDifficultyColor = (difficulty: Quiz["difficulty"]) => {
switch (difficulty) {
+10 -15
View File
@@ -20,7 +20,7 @@ import type { TestStartRequest, TestStartResponse, TestAnswerRequest, TestAnswer
type QuizState = "subject_selection" | "in_progress" | "showing_feedback" | "completed"
export function QuizRunner({ quizId }: { quizId?: string }) {
const { user, firebaseUser, isLoadingAuth, authMethod, token } = useAuth() // Use firebaseUser and authMethod
const { user, isLoadingAuth, authMethod, token } = useAuth() // Use authMethod and token
const router = useRouter()
const [quizState, setQuizState] = useState<QuizState>("subject_selection")
@@ -36,11 +36,11 @@ export function QuizRunner({ quizId }: { quizId?: string }) {
const availableSubjects = ["Math", "Science", "History", "Literature"] // Example subjects
useEffect(() => {
if (!isLoadingAuth && !user && !firebaseUser) {
if (!isLoadingAuth && !user) {
toast.error("Please login to take a quiz.")
router.push("/") // Redirect to home if not authenticated
}
}, [user, firebaseUser, isLoadingAuth, router])
}, [user, isLoadingAuth, router])
const startQuiz = async () => {
if (!selectedSubject) {
@@ -65,9 +65,9 @@ export function QuizRunner({ quizId }: { quizId?: string }) {
/*
// --- ORIGINAL API CALL (UNCOMMENT WHEN BACKEND IS READY) ---
*/
if (authMethod === "firebase" && !token) {
toast.error("Quiz progress and persistence require MetaMask authentication.")
return // Prevent API call for Firebase users without JWT
if (!token) {
toast.error("Authentication token missing. Please log in again.")
return // Prevent API call without JWT
}
setIsStartingQuiz(true)
@@ -130,9 +130,9 @@ export function QuizRunner({ quizId }: { quizId?: string }) {
/*
// --- ORIGINAL API CALL (UNCOMMENT WHEN BACKEND IS READY) ---
*/
if (authMethod === "firebase" && !token) {
toast.error("Quiz progress and persistence require MetaMask authentication.")
return // Prevent API call for Firebase users without JWT
if (!token) {
toast.error("Authentication token missing. Please log in again.")
return // Prevent API call without JWT
}
setIsSubmittingAnswer(true)
@@ -182,7 +182,7 @@ export function QuizRunner({ quizId }: { quizId?: string }) {
setFeedback(null)
}
if (isLoadingAuth || (!user && !firebaseUser)) {
if (isLoadingAuth || !user) {
return (
<div className="flex justify-center items-center min-h-[calc(100vh-64px)]">
<Loader2 className="h-8 w-8 animate-spin text-primary-purple" />
@@ -220,11 +220,6 @@ export function QuizRunner({ quizId }: { quizId?: string }) {
{isStartingQuiz && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Start Quiz
</Button>
{authMethod === "firebase" && !token && (
<p className="text-sm text-center text-warning dark:text-warning/80 mt-4">
Note: Quiz progress will not be saved without MetaMask authentication.
</p>
)}
</CardContent>
</Card>
)}
+1 -1
View File
@@ -29,7 +29,7 @@ function Calendar({
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
'bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent',
'bg-background group/calendar p-3 [--cell-size:2rem] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent',
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
+16 -8
View File
@@ -8,18 +8,26 @@ import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet"
import { Menu, Sun, Moon } from "lucide-react"
import { useTheme } from "next-themes"
import { useState, useEffect } from "react"
import { usePathname } from "next/navigation"
export function Navbar() {
const { user, firebaseUser, authMethod } = useAuth() // Use authMethod to determine display
const { theme, setTheme } = useTheme()
const { user, authMethod } = useAuth() // Use authMethod to determine display
const { resolvedTheme, setTheme } = useTheme()
const [mounted, setMounted] = useState(false)
const pathname = usePathname()
useEffect(() => {
setMounted(true)
}, [])
if (pathname.startsWith("/admin")) {
return null
}
const isDark = resolvedTheme === "dark"
return (
<header className="sticky top-0 z-40 w-full border-b bg-white/80 backdrop-blur-md dark:bg-gray-950/80">
<header className="sticky top-0 z-40 w-full border-b bg-white/80 backdrop-blur-md dark:bg-[#102a52]/90">
<div className="container flex h-16 items-center justify-between">
<Link href="/" className="text-2xl font-bold text-primary-purple">
OpenLearnX
@@ -59,10 +67,10 @@ export function Navbar() {
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
onClick={() => setTheme(isDark ? "light" : "dark")}
className="ml-2"
>
{mounted && (theme === "dark" ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />)}
{mounted && (isDark ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />)}
{!mounted && <div className="h-5 w-5" />} {/* Render a placeholder div to maintain layout */}
<span className="sr-only">Toggle theme</span>
</Button>
@@ -71,10 +79,10 @@ export function Navbar() {
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
onClick={() => setTheme(isDark ? "light" : "dark")}
className="mr-2"
>
{mounted && (theme === "dark" ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />)}
{mounted && (isDark ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />)}
{!mounted && <div className="h-5 w-5" />} {/* Render a placeholder div to maintain layout */}
<span className="sr-only">Toggle theme</span>
</Button>
@@ -85,7 +93,7 @@ export function Navbar() {
<span className="sr-only">Toggle navigation</span>
</Button>
</SheetTrigger>
<SheetContent side="right" className="w-[250px] sm:w-[300px] p-4 dark:bg-gray-900">
<SheetContent side="right" className="w-[250px] sm:w-[300px] p-4 dark:bg-[#1b3760]">
<nav className="flex flex-col gap-4">
<Link
href="/"