mirror of
https://github.com/th30d4y/OpenLearnX.git
synced 2026-05-26 19:26:33 +00:00
feat: unify real activity tracking, admin monitoring, and error UX
This commit is contained in:
@@ -0,0 +1,295 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { Edit, Plus, Trash2 } from "lucide-react"
|
||||
|
||||
type Course = {
|
||||
id: string
|
||||
title: string
|
||||
subject: string
|
||||
description: string
|
||||
difficulty: string
|
||||
mentor: string
|
||||
video_url: string
|
||||
students: number
|
||||
}
|
||||
|
||||
const API_BASE = "http://127.0.0.1:5000"
|
||||
|
||||
export default function AdminCoursesPage() {
|
||||
const router = useRouter()
|
||||
const [ready, setReady] = useState(false)
|
||||
const [courses, setCourses] = useState<Course[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [showAdd, setShowAdd] = useState(false)
|
||||
const [editing, setEditing] = useState<Course | null>(null)
|
||||
|
||||
const getToken = () => localStorage.getItem("admin_token")
|
||||
const headers = () => {
|
||||
const token = getToken()
|
||||
return token
|
||||
? { "Content-Type": "application/json", Authorization: `Bearer ${token}` }
|
||||
: { "Content-Type": "application/json" }
|
||||
}
|
||||
|
||||
const ensureAuth = async () => {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
const resp = await fetch(`${API_BASE}/api/admin/test`, { headers: headers() })
|
||||
if (!resp.ok) {
|
||||
localStorage.removeItem("admin_token")
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const fetchCourses = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const resp = await fetch(`${API_BASE}/api/admin/courses`, { headers: headers() })
|
||||
if (resp.ok) {
|
||||
const data = await resp.json()
|
||||
setCourses(Array.isArray(data) ? data : [])
|
||||
} else {
|
||||
setCourses([])
|
||||
}
|
||||
} catch {
|
||||
setCourses([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const saveCourse = async (payload: Partial<Course>, courseId?: string) => {
|
||||
const url = courseId ? `${API_BASE}/api/admin/courses/${courseId}` : `${API_BASE}/api/admin/courses`
|
||||
const method = courseId ? "PUT" : "POST"
|
||||
|
||||
const resp = await fetch(url, {
|
||||
method,
|
||||
headers: headers(),
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
if (resp.ok) {
|
||||
setShowAdd(false)
|
||||
setEditing(null)
|
||||
await fetchCourses()
|
||||
} else {
|
||||
const err = await resp.json().catch(() => ({ error: "Operation failed" }))
|
||||
alert(err.error || "Operation failed")
|
||||
}
|
||||
}
|
||||
|
||||
const deleteCourse = async (courseId: string) => {
|
||||
if (!confirm("Delete this course and related modules/lessons?")) return
|
||||
const resp = await fetch(`${API_BASE}/api/admin/courses/${courseId}`, {
|
||||
method: "DELETE",
|
||||
headers: headers(),
|
||||
})
|
||||
if (resp.ok) {
|
||||
await fetchCourses()
|
||||
} else {
|
||||
alert("Failed to delete course")
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const init = async () => {
|
||||
const ok = await ensureAuth()
|
||||
if (!ok) return
|
||||
setReady(true)
|
||||
await fetchCourses()
|
||||
}
|
||||
init()
|
||||
}, [])
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-8 text-center dark:border-gray-800 dark:bg-gray-900">
|
||||
<p className="text-gray-600 dark:text-gray-300">Loading course management...</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">Course Management</h1>
|
||||
<p className="mt-1 text-sm text-gray-600 dark:text-gray-400">Manage real courses from database records.</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowAdd(true)}
|
||||
className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
Add Course
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800/50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">Title</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">Subject</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">Difficulty</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">Mentor</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">Students</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium uppercase text-gray-500">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100 dark:divide-gray-800">
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td className="px-4 py-4 text-sm text-gray-600" colSpan={6}>Loading courses...</td>
|
||||
</tr>
|
||||
) : courses.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-4 text-sm text-gray-500" colSpan={6}>No courses found.</td>
|
||||
</tr>
|
||||
) : (
|
||||
courses.map((course) => (
|
||||
<tr key={course.id}>
|
||||
<td className="px-4 py-3 text-sm font-medium text-gray-900 dark:text-white">{course.title}</td>
|
||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{course.subject}</td>
|
||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{course.difficulty}</td>
|
||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{course.mentor}</td>
|
||||
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{Number(course.students || 0).toLocaleString()}</td>
|
||||
<td className="px-4 py-3 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setEditing(course)}
|
||||
className="rounded p-1.5 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-950/30"
|
||||
title="Edit"
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => deleteCourse(course.id)}
|
||||
className="rounded p-1.5 text-red-600 hover:bg-red-50 dark:hover:bg-red-950/30"
|
||||
title="Delete"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(showAdd || editing) && (
|
||||
<CourseFormModal
|
||||
title={editing ? "Edit Course" : "Add Course"}
|
||||
initialData={editing || undefined}
|
||||
onClose={() => {
|
||||
setShowAdd(false)
|
||||
setEditing(null)
|
||||
}}
|
||||
onSubmit={(payload) => saveCourse(payload, editing?.id)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CourseFormModal({
|
||||
title,
|
||||
initialData,
|
||||
onClose,
|
||||
onSubmit,
|
||||
}: {
|
||||
title: string
|
||||
initialData?: Partial<Course>
|
||||
onClose: () => void
|
||||
onSubmit: (payload: Partial<Course>) => Promise<void>
|
||||
}) {
|
||||
const [form, setForm] = useState<Partial<Course>>({
|
||||
title: initialData?.title || "",
|
||||
subject: initialData?.subject || "",
|
||||
description: initialData?.description || "",
|
||||
difficulty: initialData?.difficulty || "Beginner",
|
||||
mentor: initialData?.mentor || "",
|
||||
video_url: initialData?.video_url || "",
|
||||
})
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setSaving(true)
|
||||
await onSubmit(form)
|
||||
setSaving(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/35 p-4">
|
||||
<div className="w-full max-w-xl rounded-xl border border-gray-200 bg-white p-5 shadow-xl dark:border-gray-800 dark:bg-gray-900">
|
||||
<h3 className="mb-4 text-lg font-semibold text-gray-900 dark:text-white">{title}</h3>
|
||||
<form onSubmit={submit} className="space-y-3">
|
||||
<input
|
||||
required
|
||||
placeholder="Title"
|
||||
value={form.title || ""}
|
||||
onChange={(e) => setForm({ ...form, title: e.target.value })}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<input
|
||||
required
|
||||
placeholder="Subject"
|
||||
value={form.subject || ""}
|
||||
onChange={(e) => setForm({ ...form, subject: e.target.value })}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<textarea
|
||||
required
|
||||
placeholder="Description"
|
||||
value={form.description || ""}
|
||||
onChange={(e) => setForm({ ...form, description: e.target.value })}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
rows={3}
|
||||
/>
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<input
|
||||
placeholder="Difficulty"
|
||||
value={form.difficulty || ""}
|
||||
onChange={(e) => setForm({ ...form, difficulty: e.target.value })}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<input
|
||||
placeholder="Mentor"
|
||||
value={form.mentor || ""}
|
||||
onChange={(e) => setForm({ ...form, mentor: e.target.value })}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
placeholder="Video URL"
|
||||
value={form.video_url || ""}
|
||||
onChange={(e) => setForm({ ...form, video_url: e.target.value })}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<button type="button" onClick={onClose} className="rounded-md bg-gray-100 px-3 py-2 text-sm hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700">
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" disabled={saving} className="rounded-md bg-blue-600 px-3 py-2 text-sm text-white hover:bg-blue-700 disabled:opacity-60">
|
||||
{saving ? "Saving..." : "Save"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
"use client"
|
||||
|
||||
import { FormEvent, useEffect, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
type CollectionInfo = { name: string; count: number }
|
||||
type DocumentRow = Record<string, unknown>
|
||||
|
||||
const API_BASE = "http://127.0.0.1:5000"
|
||||
|
||||
export default function AdminDatabasePage() {
|
||||
const router = useRouter()
|
||||
const [ready, setReady] = useState(false)
|
||||
const [collections, setCollections] = useState<CollectionInfo[]>([])
|
||||
const [selectedCollection, setSelectedCollection] = useState<string>("")
|
||||
const [documents, setDocuments] = useState<DocumentRow[]>([])
|
||||
const [search, setSearch] = useState("")
|
||||
const [loadingCollections, setLoadingCollections] = useState(false)
|
||||
const [loadingDocuments, setLoadingDocuments] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [message, setMessage] = useState("")
|
||||
const [pagination, setPagination] = useState({ page: 1, limit: 25, total: 0, pages: 1 })
|
||||
const [createJson, setCreateJson] = useState('{\n "key": "value"\n}')
|
||||
const [editDocId, setEditDocId] = useState("")
|
||||
const [editJson, setEditJson] = useState("{}")
|
||||
|
||||
const getToken = () => localStorage.getItem("admin_token")
|
||||
const headers = () => {
|
||||
const token = getToken()
|
||||
return token
|
||||
? { "Content-Type": "application/json", Authorization: `Bearer ${token}` }
|
||||
: { "Content-Type": "application/json" }
|
||||
}
|
||||
|
||||
const ensureAuth = async () => {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
const resp = await fetch(`${API_BASE}/api/admin/test`, { headers: headers() })
|
||||
if (!resp.ok) {
|
||||
localStorage.removeItem("admin_token")
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const fetchOverview = async () => {
|
||||
setLoadingCollections(true)
|
||||
setMessage("")
|
||||
try {
|
||||
const resp = await fetch(`${API_BASE}/api/admin/database/overview`, { headers: headers() })
|
||||
if (resp.ok) {
|
||||
const data = await resp.json()
|
||||
const list = Array.isArray(data.collections) ? data.collections : []
|
||||
setCollections(list)
|
||||
if (list.length > 0 && !selectedCollection) {
|
||||
setSelectedCollection(list[0].name)
|
||||
await fetchDocuments(list[0].name, 1)
|
||||
}
|
||||
} else {
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
setMessage(String(data.error || "Failed to load collections."))
|
||||
}
|
||||
} catch {
|
||||
setMessage("Network error while loading collections.")
|
||||
} finally {
|
||||
setLoadingCollections(false)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchDocuments = async (collection: string, page = 1, nextSearch = search) => {
|
||||
if (!collection) return
|
||||
setLoadingDocuments(true)
|
||||
setMessage("")
|
||||
try {
|
||||
const params = new URLSearchParams({ page: String(page), limit: String(pagination.limit) })
|
||||
if (nextSearch.trim()) params.set("search", nextSearch.trim())
|
||||
|
||||
const resp = await fetch(`${API_BASE}/api/admin/database/collections/${encodeURIComponent(collection)}?${params.toString()}`, { headers: headers() })
|
||||
if (resp.ok) {
|
||||
const data = await resp.json()
|
||||
setDocuments(Array.isArray(data.documents) ? data.documents : [])
|
||||
if (data.pagination) setPagination(data.pagination)
|
||||
} else {
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
setMessage(String(data.error || "Failed to load documents."))
|
||||
setDocuments([])
|
||||
}
|
||||
} catch {
|
||||
setMessage("Network error while loading documents.")
|
||||
setDocuments([])
|
||||
} finally {
|
||||
setLoadingDocuments(false)
|
||||
}
|
||||
}
|
||||
|
||||
const createDocument = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!selectedCollection) return
|
||||
|
||||
setSaving(true)
|
||||
setMessage("")
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(createJson)
|
||||
const resp = await fetch(`${API_BASE}/api/admin/database/collections/${encodeURIComponent(selectedCollection)}`, {
|
||||
method: "POST",
|
||||
headers: headers(),
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
|
||||
if (!resp.ok) {
|
||||
setMessage(String(data.error || "Failed to create document."))
|
||||
return
|
||||
}
|
||||
|
||||
setMessage("Document created successfully.")
|
||||
await fetchOverview()
|
||||
await fetchDocuments(selectedCollection, 1)
|
||||
} catch {
|
||||
setMessage("Invalid JSON for create payload.")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const startEditDocument = (doc: DocumentRow) => {
|
||||
const id = String(doc._id || "")
|
||||
if (!id) {
|
||||
setMessage("Selected document has no _id.")
|
||||
return
|
||||
}
|
||||
|
||||
const clone = { ...doc }
|
||||
delete clone._id
|
||||
setEditDocId(id)
|
||||
setEditJson(JSON.stringify(clone, null, 2))
|
||||
}
|
||||
|
||||
const saveEditDocument = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!selectedCollection || !editDocId) return
|
||||
|
||||
setSaving(true)
|
||||
setMessage("")
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(editJson)
|
||||
const resp = await fetch(
|
||||
`${API_BASE}/api/admin/database/collections/${encodeURIComponent(selectedCollection)}/${encodeURIComponent(editDocId)}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: headers(),
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
)
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
|
||||
if (!resp.ok) {
|
||||
setMessage(String(data.error || "Failed to update document."))
|
||||
return
|
||||
}
|
||||
|
||||
setMessage("Document updated successfully.")
|
||||
setEditDocId("")
|
||||
setEditJson("{}")
|
||||
await fetchDocuments(selectedCollection, pagination.page)
|
||||
} catch {
|
||||
setMessage("Invalid JSON for update payload.")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const deleteDocument = async (docId: string) => {
|
||||
if (!selectedCollection || !docId) return
|
||||
|
||||
setSaving(true)
|
||||
setMessage("")
|
||||
try {
|
||||
const resp = await fetch(
|
||||
`${API_BASE}/api/admin/database/collections/${encodeURIComponent(selectedCollection)}/${encodeURIComponent(docId)}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: headers(),
|
||||
},
|
||||
)
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
|
||||
if (!resp.ok) {
|
||||
setMessage(String(data.error || "Failed to delete document."))
|
||||
return
|
||||
}
|
||||
|
||||
setMessage("Document deleted successfully.")
|
||||
await fetchOverview()
|
||||
await fetchDocuments(selectedCollection, 1)
|
||||
} catch {
|
||||
setMessage("Network error while deleting document.")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const init = async () => {
|
||||
const ok = await ensureAuth()
|
||||
if (!ok) return
|
||||
setReady(true)
|
||||
await fetchOverview()
|
||||
}
|
||||
init()
|
||||
}, [])
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-8 text-center dark:border-gray-800 dark:bg-gray-900">
|
||||
<p className="text-gray-600 dark:text-gray-300">Loading database explorer...</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">Database Explorer</h1>
|
||||
<p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
|
||||
Browse all collections and perform create, update, and delete actions on documents.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<form
|
||||
onSubmit={createDocument}
|
||||
className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"
|
||||
>
|
||||
<h3 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">Create Document</h3>
|
||||
<p className="mb-2 text-xs text-gray-600 dark:text-gray-300">Collection: {selectedCollection || "None selected"}</p>
|
||||
<textarea
|
||||
value={createJson}
|
||||
onChange={(e) => setCreateJson(e.target.value)}
|
||||
rows={10}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 font-mono text-xs dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving || !selectedCollection}
|
||||
className="mt-3 rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-60"
|
||||
>
|
||||
{saving ? "Saving..." : "Create"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<form
|
||||
onSubmit={saveEditDocument}
|
||||
className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"
|
||||
>
|
||||
<h3 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">Edit Document</h3>
|
||||
<p className="mb-2 text-xs text-gray-600 dark:text-gray-300">Document ID: {editDocId || "Select a document below"}</p>
|
||||
<textarea
|
||||
value={editJson}
|
||||
onChange={(e) => setEditJson(e.target.value)}
|
||||
rows={10}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 font-mono text-xs dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving || !selectedCollection || !editDocId}
|
||||
className="rounded-md bg-emerald-600 px-4 py-2 text-sm font-medium text-white hover:bg-emerald-700 disabled:opacity-60"
|
||||
>
|
||||
{saving ? "Saving..." : "Update"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setEditDocId("")
|
||||
setEditJson("{}")
|
||||
}}
|
||||
className="rounded-md bg-gray-100 px-4 py-2 text-sm font-medium text-gray-800 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-100 dark:hover:bg-gray-700"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{message ? (
|
||||
<div className="rounded-xl border border-gray-200 bg-white px-4 py-3 text-sm text-gray-700 shadow-sm dark:border-gray-800 dark:bg-gray-900 dark:text-gray-200">
|
||||
{message}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 xl:grid-cols-4">
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<h3 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">Collections</h3>
|
||||
{loadingCollections ? (
|
||||
<p className="text-sm text-gray-600 dark:text-gray-300">Loading...</p>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{collections.map((item) => (
|
||||
<button
|
||||
key={item.name}
|
||||
onClick={() => {
|
||||
setSelectedCollection(item.name)
|
||||
fetchDocuments(item.name, 1)
|
||||
}}
|
||||
className={`flex w-full items-center justify-between rounded px-3 py-2 text-sm ${
|
||||
selectedCollection === item.name
|
||||
? "bg-blue-600 text-white"
|
||||
: "bg-gray-50 text-gray-800 hover:bg-gray-100 dark:bg-gray-800 dark:text-gray-100 dark:hover:bg-gray-700"
|
||||
}`}
|
||||
>
|
||||
<span className="truncate text-left">{item.name}</span>
|
||||
<span className="ml-2 text-xs">{item.count}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="xl:col-span-3 rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<div className="flex flex-wrap items-center gap-3 border-b border-gray-100 p-4 dark:border-gray-800">
|
||||
<input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Search inside documents"
|
||||
className="min-w-[260px] flex-1 rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<button
|
||||
onClick={() => fetchDocuments(selectedCollection, 1)}
|
||||
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
|
||||
>
|
||||
Search
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="max-h-[72vh] overflow-auto p-4">
|
||||
{loadingDocuments ? (
|
||||
<p className="text-sm text-gray-600 dark:text-gray-300">Loading documents...</p>
|
||||
) : documents.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">No documents to show.</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{documents.map((doc, idx) => (
|
||||
<div
|
||||
key={String(doc._id || idx)}
|
||||
className="rounded border border-gray-200 bg-gray-50 p-3 text-xs text-gray-800 dark:border-gray-700 dark:bg-gray-950 dark:text-gray-100"
|
||||
>
|
||||
<div className="mb-2 flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
onClick={() => startEditDocument(doc)}
|
||||
className="rounded bg-blue-600 px-2 py-1 text-white hover:bg-blue-700"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={() => deleteDocument(String(doc._id || ""))}
|
||||
className="rounded bg-red-700 px-2 py-1 text-white hover:bg-red-800"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
<span className="text-[11px] text-gray-600 dark:text-gray-300">ID: {String(doc._id || "unknown")}</span>
|
||||
</div>
|
||||
<pre className="overflow-auto">{JSON.stringify(doc, null, 2)}</pre>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between border-t border-gray-100 px-4 py-3 text-sm text-gray-600 dark:border-gray-800 dark:text-gray-300">
|
||||
<span>Page {pagination.page} of {pagination.pages} • Total {pagination.total}</span>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => fetchDocuments(selectedCollection, Math.max(1, pagination.page - 1))}
|
||||
disabled={pagination.page <= 1}
|
||||
className="rounded bg-gray-100 px-3 py-1.5 disabled:opacity-50 dark:bg-gray-800"
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
<button
|
||||
onClick={() => fetchDocuments(selectedCollection, Math.min(pagination.pages, pagination.page + 1))}
|
||||
disabled={pagination.page >= pagination.pages}
|
||||
className="rounded bg-gray-100 px-3 py-1.5 disabled:opacity-50 dark:bg-gray-800"
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
"use client"
|
||||
|
||||
import { FormEvent, useEffect, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
const API_BASE = "http://127.0.0.1:5000"
|
||||
|
||||
type FirewallRule = {
|
||||
id: string
|
||||
name?: string
|
||||
ip?: string
|
||||
method?: string
|
||||
path_pattern?: string
|
||||
action?: string
|
||||
enabled?: boolean
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
type RuleForm = {
|
||||
name: string
|
||||
ip: string
|
||||
method: string
|
||||
path_pattern: string
|
||||
action: "block" | "allow"
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
const initialRuleForm: RuleForm = {
|
||||
name: "",
|
||||
ip: "",
|
||||
method: "",
|
||||
path_pattern: "",
|
||||
action: "block",
|
||||
enabled: true,
|
||||
}
|
||||
|
||||
export default function AdminFirewallPage() {
|
||||
const router = useRouter()
|
||||
const [ready, setReady] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [rules, setRules] = useState<FirewallRule[]>([])
|
||||
const [message, setMessage] = useState("")
|
||||
const [form, setForm] = useState<RuleForm>(initialRuleForm)
|
||||
|
||||
const getToken = () => localStorage.getItem("admin_token")
|
||||
const headers = () => {
|
||||
const token = getToken()
|
||||
return token
|
||||
? { "Content-Type": "application/json", Authorization: `Bearer ${token}` }
|
||||
: { "Content-Type": "application/json" }
|
||||
}
|
||||
|
||||
const ensureAuth = async () => {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
const resp = await fetch(`${API_BASE}/api/admin/test`, { headers: headers() })
|
||||
if (!resp.ok) {
|
||||
localStorage.removeItem("admin_token")
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const fetchRules = async () => {
|
||||
setLoading(true)
|
||||
setMessage("")
|
||||
|
||||
try {
|
||||
const resp = await fetch(`${API_BASE}/api/admin/firewall/rules`, { headers: headers() })
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
if (!resp.ok) {
|
||||
setRules([])
|
||||
setMessage(String(data.error || "Failed to load firewall rules."))
|
||||
return
|
||||
}
|
||||
|
||||
setRules(Array.isArray(data.rules) ? data.rules : [])
|
||||
} catch {
|
||||
setRules([])
|
||||
setMessage("Network error while loading firewall rules.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const createRule = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
setSaving(true)
|
||||
setMessage("")
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
name: form.name.trim(),
|
||||
ip: form.ip.trim(),
|
||||
method: form.method.trim().toUpperCase(),
|
||||
path_pattern: form.path_pattern.trim(),
|
||||
action: form.action,
|
||||
enabled: form.enabled,
|
||||
}
|
||||
|
||||
const resp = await fetch(`${API_BASE}/api/admin/firewall/rules`, {
|
||||
method: "POST",
|
||||
headers: headers(),
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
|
||||
if (!resp.ok) {
|
||||
setMessage(String(data.error || "Failed to create firewall rule."))
|
||||
return
|
||||
}
|
||||
|
||||
setForm(initialRuleForm)
|
||||
setMessage("Firewall rule created.")
|
||||
await fetchRules()
|
||||
} catch {
|
||||
setMessage("Network error while creating firewall rule.")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const deleteRule = async (ruleId: string) => {
|
||||
if (!ruleId) return
|
||||
|
||||
setMessage("")
|
||||
try {
|
||||
const resp = await fetch(`${API_BASE}/api/admin/firewall/rules/${encodeURIComponent(ruleId)}`, {
|
||||
method: "DELETE",
|
||||
headers: headers(),
|
||||
})
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
|
||||
if (!resp.ok) {
|
||||
setMessage(String(data.error || "Failed to delete firewall rule."))
|
||||
return
|
||||
}
|
||||
|
||||
setMessage("Firewall rule deleted.")
|
||||
await fetchRules()
|
||||
} catch {
|
||||
setMessage("Network error while deleting firewall rule.")
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const init = async () => {
|
||||
const ok = await ensureAuth()
|
||||
if (!ok) return
|
||||
setReady(true)
|
||||
await fetchRules()
|
||||
}
|
||||
init()
|
||||
}, [])
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-8 text-center dark:border-gray-800 dark:bg-gray-900">
|
||||
<p className="text-gray-600 dark:text-gray-300">Loading firewall manager...</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">Manual Firewall</h1>
|
||||
<p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
|
||||
Add or remove manual allow/block rules by IP, method, and path pattern.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form
|
||||
onSubmit={createRule}
|
||||
className="grid gap-3 rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900 lg:grid-cols-6"
|
||||
>
|
||||
<input
|
||||
value={form.name}
|
||||
onChange={(e) => setForm((p) => ({ ...p, name: e.target.value }))}
|
||||
placeholder="Rule name"
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<input
|
||||
value={form.ip}
|
||||
onChange={(e) => setForm((p) => ({ ...p, ip: e.target.value }))}
|
||||
placeholder="IP (optional)"
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<input
|
||||
value={form.method}
|
||||
onChange={(e) => setForm((p) => ({ ...p, method: e.target.value }))}
|
||||
placeholder="Method (GET/POST...)"
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<input
|
||||
value={form.path_pattern}
|
||||
onChange={(e) => setForm((p) => ({ ...p, path_pattern: e.target.value }))}
|
||||
placeholder="Path pattern (optional)"
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<select
|
||||
value={form.action}
|
||||
onChange={(e) => setForm((p) => ({ ...p, action: e.target.value as "block" | "allow" }))}
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
>
|
||||
<option value="block">block</option>
|
||||
<option value="allow">allow</option>
|
||||
</select>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-60"
|
||||
>
|
||||
{saving ? "Adding..." : "Add Rule"}
|
||||
</button>
|
||||
|
||||
<label className="col-span-full inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.enabled}
|
||||
onChange={(e) => setForm((p) => ({ ...p, enabled: e.target.checked }))}
|
||||
/>
|
||||
Rule enabled
|
||||
</label>
|
||||
</form>
|
||||
|
||||
<div className="rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<div className="border-b border-gray-100 px-4 py-3 dark:border-gray-800">
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wide text-gray-500">Active Rules</h2>
|
||||
{message ? <p className="mt-2 text-sm text-gray-700 dark:text-gray-200">{message}</p> : null}
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800/60">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Name</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">IP</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Method</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Path Pattern</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Action</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Enabled</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Created</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100 dark:divide-gray-800">
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-4 py-4 text-sm text-gray-600 dark:text-gray-300">
|
||||
Loading rules...
|
||||
</td>
|
||||
</tr>
|
||||
) : rules.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-4 py-4 text-sm text-gray-500">
|
||||
No firewall rules configured.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
rules.map((rule) => (
|
||||
<tr key={rule.id}>
|
||||
<td className="px-3 py-2 text-xs text-gray-800 dark:text-gray-100">{rule.name || "-"}</td>
|
||||
<td className="px-3 py-2 text-xs text-gray-700 dark:text-gray-300">{rule.ip || "-"}</td>
|
||||
<td className="px-3 py-2 text-xs text-gray-700 dark:text-gray-300">{rule.method || "-"}</td>
|
||||
<td className="px-3 py-2 text-xs text-gray-700 dark:text-gray-300">{rule.path_pattern || "-"}</td>
|
||||
<td className="px-3 py-2 text-xs text-gray-700 dark:text-gray-300">{rule.action || "block"}</td>
|
||||
<td className="px-3 py-2 text-xs text-gray-700 dark:text-gray-300">{rule.enabled ? "true" : "false"}</td>
|
||||
<td className="px-3 py-2 text-xs text-gray-700 dark:text-gray-300">{String(rule.created_at || "-")}</td>
|
||||
<td className="px-3 py-2 text-xs">
|
||||
<button
|
||||
onClick={() => deleteRule(rule.id)}
|
||||
className="rounded bg-red-700 px-2 py-1 text-white hover:bg-red-800"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"use client"
|
||||
|
||||
import Link from "next/link"
|
||||
import { usePathname, useRouter } from "next/navigation"
|
||||
import { useEffect, useMemo, useState, type ComponentType } from "react"
|
||||
import { BarChart3, BookOpen, Database, FileText, LayoutDashboard, LogOut, Shield, Users } from "lucide-react"
|
||||
|
||||
type NavItem = {
|
||||
href: string
|
||||
label: string
|
||||
icon: ComponentType<{ className?: string }>
|
||||
}
|
||||
|
||||
const navItems: NavItem[] = [
|
||||
{ href: "/admin", label: "Dashboard", icon: LayoutDashboard },
|
||||
{ href: "/admin/courses", label: "Courses", icon: BookOpen },
|
||||
{ href: "/admin/users", label: "Users", icon: Users },
|
||||
{ href: "/admin/logs", label: "Logs", icon: FileText },
|
||||
{ href: "/admin/reports", label: "Reports", icon: BarChart3 },
|
||||
{ href: "/admin/database", label: "Database", icon: Database },
|
||||
{ href: "/admin/firewall", label: "Firewall", icon: Shield },
|
||||
]
|
||||
|
||||
export default function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname()
|
||||
const router = useRouter()
|
||||
const [ready, setReady] = useState(false)
|
||||
|
||||
const isLoginPage = useMemo(() => pathname === "/admin/login", [pathname])
|
||||
|
||||
useEffect(() => {
|
||||
setReady(true)
|
||||
}, [])
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem("admin_token")
|
||||
router.push("/admin/login")
|
||||
}
|
||||
|
||||
if (!ready) return null
|
||||
if (isLoginPage) return <>{children}</>
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900">
|
||||
<div className="flex w-full">
|
||||
<aside className="sticky top-0 h-screen w-72 shrink-0 border-r border-gray-200 bg-white/90 p-5 backdrop-blur-sm dark:border-gray-800 dark:bg-gray-900/90">
|
||||
<div className="mb-6 border-b border-gray-200 pb-4 dark:border-gray-800">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">OpenLearnX Admin</h2>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">Professional control panel</p>
|
||||
</div>
|
||||
|
||||
<nav className="space-y-1">
|
||||
{navItems.map((item) => {
|
||||
const active = pathname === item.href
|
||||
const Icon = item.icon
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
|
||||
active
|
||||
? "bg-blue-600 text-white"
|
||||
: "text-gray-700 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-gray-800"
|
||||
}`}
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
<span>{item.label}</span>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<div className="mt-8 rounded-lg border border-blue-200 bg-blue-50 p-3 dark:border-blue-900 dark:bg-blue-950/40">
|
||||
<div className="flex items-center gap-2 text-blue-700 dark:text-blue-300">
|
||||
<BarChart3 className="h-4 w-4" />
|
||||
<p className="text-xs font-medium">Live Data Enabled</p>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-gray-600 dark:text-gray-400">
|
||||
Stats, logs, and actions are loaded directly from backend collections.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="mt-6 inline-flex w-full items-center justify-center gap-2 rounded-lg bg-red-600 px-3 py-2 text-sm font-medium text-white hover:bg-red-700"
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
Logout
|
||||
</button>
|
||||
</aside>
|
||||
|
||||
<section className="min-w-0 flex-1 p-5 lg:p-7">{children}</section>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -137,7 +137,7 @@ export default function AdminLogin() {
|
||||
{/* Error Message */}
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 text-red-600 px-3 py-2 rounded text-sm">
|
||||
⚠️ {error}
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -153,7 +153,7 @@ export default function AdminLogin() {
|
||||
Authenticating...
|
||||
</div>
|
||||
) : (
|
||||
'🔐 Login to Admin Panel'
|
||||
'Login to Admin Panel'
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
@@ -162,7 +162,7 @@ export default function AdminLogin() {
|
||||
<div className="mt-6 pt-4 border-t border-gray-100">
|
||||
<div className="text-center">
|
||||
<p className="text-xs text-gray-500">
|
||||
🔒 Secure access only - Contact administrator for credentials
|
||||
Secure access only - Contact administrator for credentials
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -171,7 +171,7 @@ export default function AdminLogin() {
|
||||
{/* Footer */}
|
||||
<div className="text-center mt-4">
|
||||
<p className="text-sm text-gray-500">
|
||||
Welcome back, <span className="font-medium text-gray-700">5t4l1n</span>! 👋
|
||||
Welcome back, <span className="font-medium text-gray-700">5t4l1n</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
type AdminLog = {
|
||||
id: string
|
||||
timestamp: string
|
||||
event_type: string
|
||||
action: string
|
||||
status_code: number
|
||||
severity: string
|
||||
method: string
|
||||
ip: string
|
||||
path: string
|
||||
user_agent?: string
|
||||
metadata?: Record<string, unknown>
|
||||
request_body?: unknown
|
||||
response_body?: unknown
|
||||
usage?: Record<string, unknown>
|
||||
query?: Record<string, unknown>
|
||||
duration_ms?: number
|
||||
origin?: string
|
||||
}
|
||||
|
||||
const API_BASE = "http://127.0.0.1:5000"
|
||||
|
||||
export default function AdminLogsPage() {
|
||||
const router = useRouter()
|
||||
const [ready, setReady] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const [message, setMessage] = useState("")
|
||||
const [logs, setLogs] = useState<AdminLog[]>([])
|
||||
const [selectedLog, setSelectedLog] = useState<AdminLog | null>(null)
|
||||
|
||||
const safeJson = (value: unknown) => {
|
||||
if (value === null || value === undefined || value === "") return "No data"
|
||||
if (typeof value === "string") {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(value), null, 2)
|
||||
} catch {
|
||||
return value
|
||||
}
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(value, null, 2)
|
||||
} catch {
|
||||
return String(value)
|
||||
}
|
||||
}
|
||||
|
||||
const copyText = async (value: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value)
|
||||
setMessage("Copied to clipboard")
|
||||
} catch {
|
||||
setMessage("Copy failed")
|
||||
}
|
||||
}
|
||||
|
||||
const selectedRequestData = selectedLog
|
||||
? selectedLog.request_body
|
||||
?? (selectedLog.metadata && (selectedLog.metadata as any).request_body)
|
||||
?? (selectedLog.metadata && (selectedLog.metadata as any).request_details)
|
||||
?? selectedLog.query
|
||||
?? null
|
||||
: null
|
||||
|
||||
const selectedResponseData = selectedLog
|
||||
? selectedLog.response_body
|
||||
?? (selectedLog.metadata && (selectedLog.metadata as any).response_body)
|
||||
?? (selectedLog.metadata && (selectedLog.metadata as any).response_details)
|
||||
?? null
|
||||
: null
|
||||
|
||||
const selectedUsageData = selectedLog
|
||||
? selectedLog.usage
|
||||
?? (selectedLog.metadata && (selectedLog.metadata as any).usage)
|
||||
?? {
|
||||
duration_ms: selectedLog.duration_ms ?? 0,
|
||||
note: "Usage metrics not captured for this log entry",
|
||||
}
|
||||
: null
|
||||
const [filters, setFilters] = useState({
|
||||
event_type: "",
|
||||
severity: "",
|
||||
status_code: "",
|
||||
search: "",
|
||||
})
|
||||
const [pagination, setPagination] = useState({ page: 1, limit: 50, total: 0, pages: 1 })
|
||||
|
||||
const getToken = () => localStorage.getItem("admin_token")
|
||||
const headers = () => {
|
||||
const token = getToken()
|
||||
return token
|
||||
? { "Content-Type": "application/json", Authorization: `Bearer ${token}` }
|
||||
: { "Content-Type": "application/json" }
|
||||
}
|
||||
|
||||
const ensureAuth = async () => {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
const resp = await fetch(`${API_BASE}/api/admin/test`, { headers: headers() })
|
||||
if (!resp.ok) {
|
||||
localStorage.removeItem("admin_token")
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const fetchLogs = async (page = 1, nextFilters = filters) => {
|
||||
setLoading(true)
|
||||
setMessage("")
|
||||
const params = new URLSearchParams()
|
||||
params.set("page", String(page))
|
||||
params.set("limit", String(pagination.limit))
|
||||
if (nextFilters.event_type) params.set("event_type", nextFilters.event_type)
|
||||
if (nextFilters.severity) params.set("severity", nextFilters.severity)
|
||||
if (nextFilters.status_code) params.set("status_code", nextFilters.status_code)
|
||||
if (nextFilters.search) params.set("search", nextFilters.search)
|
||||
|
||||
try {
|
||||
const resp = await fetch(`${API_BASE}/api/admin/logs?${params.toString()}`, { headers: headers() })
|
||||
if (resp.ok) {
|
||||
const data = await resp.json()
|
||||
setLogs(Array.isArray(data.logs) ? data.logs : [])
|
||||
if (data.pagination) {
|
||||
setPagination(data.pagination)
|
||||
}
|
||||
} else {
|
||||
setLogs([])
|
||||
}
|
||||
} catch {
|
||||
setLogs([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const triggerDownload = (content: string, filename: string, mimeType: string) => {
|
||||
const blob = new Blob([content], { type: mimeType })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement("a")
|
||||
anchor.href = url
|
||||
anchor.download = filename
|
||||
document.body.appendChild(anchor)
|
||||
anchor.click()
|
||||
anchor.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
const exportLogs = async (format: "json" | "csv") => {
|
||||
setExporting(true)
|
||||
setMessage("")
|
||||
|
||||
const params = new URLSearchParams()
|
||||
params.set("type", "logs")
|
||||
params.set("format", format)
|
||||
params.set("limit", "5000")
|
||||
if (filters.event_type) params.set("event_type", filters.event_type)
|
||||
if (filters.severity) params.set("severity", filters.severity)
|
||||
if (filters.status_code) params.set("status_code", filters.status_code)
|
||||
if (filters.search) params.set("search", filters.search)
|
||||
|
||||
try {
|
||||
const resp = await fetch(`${API_BASE}/api/admin/reports/export?${params.toString()}`, { headers: headers() })
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
|
||||
if (!resp.ok) {
|
||||
setMessage(String(data.error || "Failed to export logs."))
|
||||
return
|
||||
}
|
||||
|
||||
const stamp = new Date().toISOString().replace(/[.:]/g, "-")
|
||||
if (format === "json") {
|
||||
triggerDownload(JSON.stringify(data, null, 2), `admin-logs-${stamp}.json`, "application/json")
|
||||
} else {
|
||||
triggerDownload(String(data.content || ""), `admin-logs-${stamp}.csv`, "text/csv")
|
||||
}
|
||||
|
||||
setMessage(`Logs exported as ${format.toUpperCase()}.`)
|
||||
} catch {
|
||||
setMessage("Network error while exporting logs.")
|
||||
} finally {
|
||||
setExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const init = async () => {
|
||||
const ok = await ensureAuth()
|
||||
if (!ok) return
|
||||
setReady(true)
|
||||
await fetchLogs(1)
|
||||
}
|
||||
init()
|
||||
}, [])
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-8 text-center dark:border-gray-800 dark:bg-gray-900">
|
||||
<p className="text-gray-600 dark:text-gray-300">Loading logs...</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">Security and Activity Logs</h1>
|
||||
<p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
|
||||
Filter authentication, access-control, suspicious payload, and admin activity events.
|
||||
</p>
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
<button
|
||||
onClick={() => exportLogs("json")}
|
||||
disabled={exporting}
|
||||
className="rounded-md bg-emerald-600 px-3 py-2 text-sm font-medium text-white hover:bg-emerald-700 disabled:opacity-60"
|
||||
>
|
||||
Export Logs JSON
|
||||
</button>
|
||||
<button
|
||||
onClick={() => exportLogs("csv")}
|
||||
disabled={exporting}
|
||||
className="rounded-md bg-emerald-700 px-3 py-2 text-sm font-medium text-white hover:bg-emerald-800 disabled:opacity-60"
|
||||
>
|
||||
Export Logs CSV
|
||||
</button>
|
||||
</div>
|
||||
{message ? <p className="mt-2 text-sm text-gray-700 dark:text-gray-200">{message}</p> : null}
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<div className="grid grid-cols-1 gap-3 border-b border-gray-100 p-4 md:grid-cols-6 dark:border-gray-800">
|
||||
<input
|
||||
placeholder="Search action, path, IP"
|
||||
value={filters.search}
|
||||
onChange={(e) => setFilters({ ...filters, search: e.target.value })}
|
||||
className="md:col-span-2 rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<select
|
||||
value={filters.event_type}
|
||||
onChange={(e) => setFilters({ ...filters, event_type: e.target.value })}
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
>
|
||||
<option value="">All Event Types</option>
|
||||
<option value="admin_panel">Admin Panel</option>
|
||||
<option value="admin_panel_visit">Admin Visit</option>
|
||||
<option value="signin">Sign In</option>
|
||||
<option value="signup">Sign Up</option>
|
||||
<option value="course_join">Course Join</option>
|
||||
<option value="attendance">Attendance</option>
|
||||
<option value="forbidden_access">403 Forbidden</option>
|
||||
<option value="suspicious_payload">Suspicious Payload</option>
|
||||
</select>
|
||||
<select
|
||||
value={filters.severity}
|
||||
onChange={(e) => setFilters({ ...filters, severity: e.target.value })}
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
>
|
||||
<option value="">All Severity</option>
|
||||
<option value="info">Info</option>
|
||||
<option value="warning">Warning</option>
|
||||
<option value="error">Error</option>
|
||||
</select>
|
||||
<input
|
||||
placeholder="Status code"
|
||||
value={filters.status_code}
|
||||
onChange={(e) => setFilters({ ...filters, status_code: e.target.value })}
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => fetchLogs(1)}
|
||||
className="w-full rounded-md bg-blue-600 px-3 py-2 text-sm font-medium text-white hover:bg-blue-700"
|
||||
>
|
||||
Apply
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
const reset = { event_type: "", severity: "", status_code: "", search: "" }
|
||||
setFilters(reset)
|
||||
fetchLogs(1, reset)
|
||||
}}
|
||||
className="w-full rounded-md bg-gray-200 px-3 py-2 text-sm font-medium text-gray-900 hover:bg-gray-300 dark:bg-gray-700 dark:text-gray-100"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800/50">
|
||||
<tr>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium uppercase text-gray-500">Time</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium uppercase text-gray-500">Event</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium uppercase text-gray-500">Action</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium uppercase text-gray-500">Status</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium uppercase text-gray-500">IP</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium uppercase text-gray-500">Path</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100 dark:divide-gray-800">
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td className="px-4 py-4 text-sm text-gray-600" colSpan={6}>Loading logs...</td>
|
||||
</tr>
|
||||
) : logs.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-4 text-sm text-gray-500" colSpan={6}>No logs found for selected filters.</td>
|
||||
</tr>
|
||||
) : (
|
||||
logs.map((log) => (
|
||||
<tr
|
||||
key={log.id}
|
||||
onClick={() => setSelectedLog(log)}
|
||||
className="cursor-pointer hover:bg-blue-50 dark:hover:bg-gray-800/60"
|
||||
title="Click to view request and response details"
|
||||
>
|
||||
<td className="px-4 py-3 text-xs text-gray-700 dark:text-gray-300">{new Date(log.timestamp).toLocaleString()}</td>
|
||||
<td className="px-4 py-3 text-xs font-medium text-gray-900 dark:text-white">{log.event_type}</td>
|
||||
<td className="px-4 py-3 text-xs text-gray-700 dark:text-gray-300">{log.action}</td>
|
||||
<td className="px-4 py-3 text-xs">
|
||||
<span className={`rounded px-2 py-1 ${log.status_code >= 400 ? "bg-red-100 text-red-700" : "bg-green-100 text-green-700"}`}>
|
||||
{log.status_code}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-xs text-gray-700 dark:text-gray-300">{log.ip}</td>
|
||||
<td className="px-4 py-3 text-xs text-gray-700 dark:text-gray-300">{log.path}</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between border-t border-gray-100 px-4 py-3 text-sm text-gray-600 dark:border-gray-800 dark:text-gray-300">
|
||||
<span>
|
||||
Page {pagination.page} of {pagination.pages} • Total {pagination.total}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => fetchLogs(Math.max(1, pagination.page - 1))}
|
||||
disabled={pagination.page <= 1}
|
||||
className="rounded bg-gray-100 px-3 py-1.5 disabled:opacity-50 dark:bg-gray-800"
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
<button
|
||||
onClick={() => fetchLogs(Math.min(pagination.pages, pagination.page + 1))}
|
||||
disabled={pagination.page >= pagination.pages}
|
||||
className="rounded bg-gray-100 px-3 py-1.5 disabled:opacity-50 dark:bg-gray-800"
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedLog ? (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||
<div className="w-full max-w-4xl rounded-xl border border-gray-200 bg-white shadow-xl dark:border-gray-800 dark:bg-gray-900">
|
||||
<div className="flex items-center justify-between border-b border-gray-100 p-4 dark:border-gray-800">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">Log Request and Response Details</h2>
|
||||
<button
|
||||
onClick={() => setSelectedLog(null)}
|
||||
className="rounded-md bg-gray-200 px-3 py-1.5 text-sm text-gray-900 hover:bg-gray-300 dark:bg-gray-700 dark:text-gray-100"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="max-h-[75vh] space-y-4 overflow-auto p-4">
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<div className="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<p className="text-xs font-semibold uppercase text-gray-500">Event</p>
|
||||
<p className="mt-1 text-sm text-gray-900 dark:text-white">{selectedLog.event_type}</p>
|
||||
</div>
|
||||
<div className="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<p className="text-xs font-semibold uppercase text-gray-500">Action</p>
|
||||
<p className="mt-1 text-sm text-gray-900 dark:text-white">{selectedLog.action}</p>
|
||||
</div>
|
||||
<div className="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<p className="text-xs font-semibold uppercase text-gray-500">Path</p>
|
||||
<p className="mt-1 text-sm break-all text-gray-900 dark:text-white">{selectedLog.path}</p>
|
||||
</div>
|
||||
<div className="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<p className="text-xs font-semibold uppercase text-gray-500">Method and Status</p>
|
||||
<p className="mt-1 text-sm text-gray-900 dark:text-white">{selectedLog.method} {selectedLog.status_code}</p>
|
||||
</div>
|
||||
<div className="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<p className="text-xs font-semibold uppercase text-gray-500">Duration</p>
|
||||
<p className="mt-1 text-sm text-gray-900 dark:text-white">
|
||||
{selectedLog.duration_ms ?? (selectedLog.metadata && (selectedLog.metadata as any).duration_ms) ?? 0} ms
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<p className="text-xs font-semibold uppercase text-gray-500">Client</p>
|
||||
<p className="mt-1 text-sm break-all text-gray-900 dark:text-white">{selectedLog.ip}</p>
|
||||
<p className="mt-1 text-xs break-all text-gray-600 dark:text-gray-300">{selectedLog.user_agent || "Unknown user agent"}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-xs font-semibold uppercase text-gray-500">Request Body</p>
|
||||
<button
|
||||
onClick={() => copyText(safeJson(selectedRequestData))}
|
||||
className="rounded bg-blue-600 px-2 py-1 text-xs text-white hover:bg-blue-700"
|
||||
>
|
||||
Copy
|
||||
</button>
|
||||
</div>
|
||||
<pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded bg-gray-50 p-3 text-sm leading-6 text-gray-800 dark:bg-gray-800 dark:text-gray-100">
|
||||
{safeJson(selectedRequestData)}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-xs font-semibold uppercase text-gray-500">Response Body</p>
|
||||
<button
|
||||
onClick={() => copyText(safeJson(selectedResponseData))}
|
||||
className="rounded bg-emerald-600 px-2 py-1 text-xs text-white hover:bg-emerald-700"
|
||||
>
|
||||
Copy
|
||||
</button>
|
||||
</div>
|
||||
<pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded bg-gray-50 p-3 text-sm leading-6 text-gray-800 dark:bg-gray-800 dark:text-gray-100">
|
||||
{safeJson(selectedResponseData)}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<p className="text-xs font-semibold uppercase text-gray-500">Usage Monitoring</p>
|
||||
<pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded bg-gray-50 p-3 text-sm leading-6 text-gray-800 dark:bg-gray-800 dark:text-gray-100">
|
||||
{safeJson(selectedUsageData)}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-gray-200 p-3 dark:border-gray-700">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-xs font-semibold uppercase text-gray-500">Full Metadata</p>
|
||||
<button
|
||||
onClick={() => copyText(safeJson(selectedLog.metadata ?? {}))}
|
||||
className="rounded bg-gray-700 px-2 py-1 text-xs text-white hover:bg-gray-800"
|
||||
>
|
||||
Copy
|
||||
</button>
|
||||
</div>
|
||||
<pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded bg-gray-50 p-3 text-sm leading-6 text-gray-800 dark:bg-gray-800 dark:text-gray-100">
|
||||
{safeJson(selectedLog.metadata ?? {})}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+262
-1140
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,251 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
const API_BASE = "http://127.0.0.1:5000"
|
||||
|
||||
type UsageReport = Record<string, string | number>
|
||||
type SecurityReport = {
|
||||
generated_at?: string
|
||||
login_attempts?: number
|
||||
suspicious_events?: number
|
||||
error_events?: number
|
||||
blocked_events?: number
|
||||
top_ips?: Array<{ ip: string; count: number }>
|
||||
}
|
||||
|
||||
export default function AdminReportsPage() {
|
||||
const router = useRouter()
|
||||
const [ready, setReady] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const [message, setMessage] = useState("")
|
||||
const [usageReport, setUsageReport] = useState<UsageReport>({})
|
||||
const [securityReport, setSecurityReport] = useState<SecurityReport>({})
|
||||
|
||||
const getToken = () => localStorage.getItem("admin_token")
|
||||
const headers = () => {
|
||||
const token = getToken()
|
||||
return token
|
||||
? { "Content-Type": "application/json", Authorization: `Bearer ${token}` }
|
||||
: { "Content-Type": "application/json" }
|
||||
}
|
||||
|
||||
const ensureAuth = async () => {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
const resp = await fetch(`${API_BASE}/api/admin/test`, { headers: headers() })
|
||||
if (!resp.ok) {
|
||||
localStorage.removeItem("admin_token")
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const fetchReports = async () => {
|
||||
setLoading(true)
|
||||
setMessage("")
|
||||
|
||||
try {
|
||||
const [usageResp, securityResp] = await Promise.all([
|
||||
fetch(`${API_BASE}/api/admin/reports/usage`, { headers: headers() }),
|
||||
fetch(`${API_BASE}/api/admin/reports/security`, { headers: headers() }),
|
||||
])
|
||||
|
||||
const usageData = await usageResp.json().catch(() => ({}))
|
||||
const securityData = await securityResp.json().catch(() => ({}))
|
||||
|
||||
if (!usageResp.ok || !securityResp.ok) {
|
||||
setMessage(String(usageData.error || securityData.error || "Failed to fetch reports."))
|
||||
return
|
||||
}
|
||||
|
||||
setUsageReport(usageData.report || {})
|
||||
setSecurityReport(securityData.report || {})
|
||||
} catch {
|
||||
setMessage("Network error while fetching reports.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const triggerDownload = (content: string, filename: string, mimeType: string) => {
|
||||
const blob = new Blob([content], { type: mimeType })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement("a")
|
||||
anchor.href = url
|
||||
anchor.download = filename
|
||||
document.body.appendChild(anchor)
|
||||
anchor.click()
|
||||
anchor.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
const exportReport = async (reportType: "usage" | "security", format: "json" | "csv") => {
|
||||
setExporting(true)
|
||||
setMessage("")
|
||||
|
||||
try {
|
||||
const resp = await fetch(
|
||||
`${API_BASE}/api/admin/reports/export?type=${encodeURIComponent(reportType)}&format=${encodeURIComponent(format)}`,
|
||||
{ headers: headers() },
|
||||
)
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
|
||||
if (!resp.ok) {
|
||||
setMessage(String(data.error || "Export failed."))
|
||||
return
|
||||
}
|
||||
|
||||
const stamp = new Date().toISOString().replace(/[.:]/g, "-")
|
||||
if (format === "json") {
|
||||
triggerDownload(JSON.stringify(data, null, 2), `${reportType}-report-${stamp}.json`, "application/json")
|
||||
} else {
|
||||
triggerDownload(String(data.content || "key,value\n"), `${reportType}-report-${stamp}.csv`, "text/csv")
|
||||
}
|
||||
|
||||
setMessage(`${reportType} report exported as ${format.toUpperCase()}.`)
|
||||
} catch {
|
||||
setMessage("Network error while exporting report.")
|
||||
} finally {
|
||||
setExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const init = async () => {
|
||||
const ok = await ensureAuth()
|
||||
if (!ok) return
|
||||
setReady(true)
|
||||
await fetchReports()
|
||||
}
|
||||
init()
|
||||
}, [])
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-8 text-center dark:border-gray-800 dark:bg-gray-900">
|
||||
<p className="text-gray-600 dark:text-gray-300">Loading reports...</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">Reports and Analytics</h1>
|
||||
<p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
|
||||
Usage and security reporting with downloadable JSON and CSV exports.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
onClick={() => fetchReports()}
|
||||
disabled={loading}
|
||||
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-60"
|
||||
>
|
||||
{loading ? "Refreshing..." : "Refresh Reports"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => exportReport("usage", "json")}
|
||||
disabled={exporting}
|
||||
className="rounded-md bg-emerald-600 px-3 py-2 text-sm font-medium text-white hover:bg-emerald-700 disabled:opacity-60"
|
||||
>
|
||||
Export Usage JSON
|
||||
</button>
|
||||
<button
|
||||
onClick={() => exportReport("usage", "csv")}
|
||||
disabled={exporting}
|
||||
className="rounded-md bg-emerald-700 px-3 py-2 text-sm font-medium text-white hover:bg-emerald-800 disabled:opacity-60"
|
||||
>
|
||||
Export Usage CSV
|
||||
</button>
|
||||
<button
|
||||
onClick={() => exportReport("security", "json")}
|
||||
disabled={exporting}
|
||||
className="rounded-md bg-indigo-600 px-3 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-60"
|
||||
>
|
||||
Export Security JSON
|
||||
</button>
|
||||
<button
|
||||
onClick={() => exportReport("security", "csv")}
|
||||
disabled={exporting}
|
||||
className="rounded-md bg-indigo-700 px-3 py-2 text-sm font-medium text-white hover:bg-indigo-800 disabled:opacity-60"
|
||||
>
|
||||
Export Security CSV
|
||||
</button>
|
||||
</div>
|
||||
{message ? <p className="mt-3 text-sm text-gray-700 dark:text-gray-200">{message}</p> : null}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">Usage Report</h2>
|
||||
{loading ? (
|
||||
<p className="text-sm text-gray-600 dark:text-gray-300">Loading usage report...</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{Object.entries(usageReport).map(([key, value]) => (
|
||||
<div key={key} className="flex items-center justify-between rounded border border-gray-100 px-3 py-2 text-sm dark:border-gray-800">
|
||||
<span className="text-gray-600 dark:text-gray-300">{key}</span>
|
||||
<span className="font-medium text-gray-900 dark:text-gray-100">{String(value)}</span>
|
||||
</div>
|
||||
))}
|
||||
{Object.keys(usageReport).length === 0 ? (
|
||||
<p className="text-sm text-gray-500">No usage data available.</p>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">Security Report</h2>
|
||||
{loading ? (
|
||||
<p className="text-sm text-gray-600 dark:text-gray-300">Loading security report...</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="rounded border border-gray-100 px-3 py-2 text-sm dark:border-gray-800">
|
||||
<span className="text-gray-600 dark:text-gray-300">Login attempts:</span>{" "}
|
||||
<span className="font-medium text-gray-900 dark:text-gray-100">{securityReport.login_attempts || 0}</span>
|
||||
</div>
|
||||
<div className="rounded border border-gray-100 px-3 py-2 text-sm dark:border-gray-800">
|
||||
<span className="text-gray-600 dark:text-gray-300">Suspicious events:</span>{" "}
|
||||
<span className="font-medium text-gray-900 dark:text-gray-100">{securityReport.suspicious_events || 0}</span>
|
||||
</div>
|
||||
<div className="rounded border border-gray-100 px-3 py-2 text-sm dark:border-gray-800">
|
||||
<span className="text-gray-600 dark:text-gray-300">Error events:</span>{" "}
|
||||
<span className="font-medium text-gray-900 dark:text-gray-100">{securityReport.error_events || 0}</span>
|
||||
</div>
|
||||
<div className="rounded border border-gray-100 px-3 py-2 text-sm dark:border-gray-800">
|
||||
<span className="text-gray-600 dark:text-gray-300">Blocked by firewall:</span>{" "}
|
||||
<span className="font-medium text-gray-900 dark:text-gray-100">{securityReport.blocked_events || 0}</span>
|
||||
</div>
|
||||
|
||||
<div className="rounded border border-gray-100 p-3 text-sm dark:border-gray-800">
|
||||
<p className="mb-2 font-medium text-gray-900 dark:text-gray-100">Top Source IPs</p>
|
||||
<div className="space-y-1">
|
||||
{(securityReport.top_ips || []).map((entry) => (
|
||||
<div key={`${entry.ip}-${entry.count}`} className="flex items-center justify-between text-xs">
|
||||
<span className="text-gray-600 dark:text-gray-300">{entry.ip}</span>
|
||||
<span className="font-medium text-gray-900 dark:text-gray-100">{entry.count}</span>
|
||||
</div>
|
||||
))}
|
||||
{(securityReport.top_ips || []).length === 0 ? (
|
||||
<p className="text-xs text-gray-500">No IP analytics available.</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,621 @@
|
||||
"use client"
|
||||
|
||||
import { FormEvent, useEffect, useMemo, useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
type UserDoc = Record<string, unknown>
|
||||
|
||||
type UserFormState = {
|
||||
email: string
|
||||
username: string
|
||||
name: string
|
||||
wallet_address: string
|
||||
role: string
|
||||
password: string
|
||||
}
|
||||
|
||||
const API_BASE = "http://127.0.0.1:5000"
|
||||
|
||||
const initialUserForm: UserFormState = {
|
||||
email: "",
|
||||
username: "",
|
||||
name: "",
|
||||
wallet_address: "",
|
||||
role: "student",
|
||||
password: "",
|
||||
}
|
||||
|
||||
const getUserId = (user: UserDoc) => String(user._id || user.id || "")
|
||||
|
||||
export default function AdminUsersPage() {
|
||||
const router = useRouter()
|
||||
const [ready, setReady] = useState(false)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [actionLoadingId, setActionLoadingId] = useState<string>("")
|
||||
const [users, setUsers] = useState<UserDoc[]>([])
|
||||
const [selectedUser, setSelectedUser] = useState<UserDoc | null>(null)
|
||||
const [search, setSearch] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState("all")
|
||||
const [roleFilter, setRoleFilter] = useState("all")
|
||||
const [pagination, setPagination] = useState({ page: 1, limit: 25, total: 0, pages: 1 })
|
||||
const [message, setMessage] = useState("")
|
||||
|
||||
const [createForm, setCreateForm] = useState<UserFormState>(initialUserForm)
|
||||
const [editMode, setEditMode] = useState(false)
|
||||
const [editId, setEditId] = useState("")
|
||||
const [editForm, setEditForm] = useState<UserFormState>(initialUserForm)
|
||||
|
||||
const getToken = () => localStorage.getItem("admin_token")
|
||||
|
||||
const headers = () => {
|
||||
const token = getToken()
|
||||
return token
|
||||
? { "Content-Type": "application/json", Authorization: `Bearer ${token}` }
|
||||
: { "Content-Type": "application/json" }
|
||||
}
|
||||
|
||||
const ensureAuth = async () => {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
|
||||
const resp = await fetch(`${API_BASE}/api/admin/test`, { headers: headers() })
|
||||
if (!resp.ok) {
|
||||
localStorage.removeItem("admin_token")
|
||||
router.push("/admin/login")
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const fetchUsers = async (page = 1, nextSearch = search, nextStatus = statusFilter, nextRole = roleFilter) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
page: String(page),
|
||||
limit: String(pagination.limit),
|
||||
})
|
||||
|
||||
if (nextSearch.trim()) params.set("search", nextSearch.trim())
|
||||
if (nextStatus !== "all") params.set("status", nextStatus)
|
||||
if (nextRole !== "all") params.set("role", nextRole)
|
||||
|
||||
const resp = await fetch(`${API_BASE}/api/admin/users?${params.toString()}`, { headers: headers() })
|
||||
if (!resp.ok) {
|
||||
setUsers([])
|
||||
setMessage("Failed to load users.")
|
||||
return
|
||||
}
|
||||
|
||||
const data = await resp.json()
|
||||
setUsers(Array.isArray(data.users) ? data.users : [])
|
||||
if (data.pagination) setPagination(data.pagination)
|
||||
setMessage("")
|
||||
} catch {
|
||||
setUsers([])
|
||||
setMessage("Network error while loading users.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreateUser = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
setSaving(true)
|
||||
setMessage("")
|
||||
|
||||
try {
|
||||
const payload: Record<string, unknown> = {
|
||||
email: createForm.email.trim(),
|
||||
username: createForm.username.trim(),
|
||||
name: createForm.name.trim(),
|
||||
wallet_address: createForm.wallet_address.trim(),
|
||||
role: createForm.role,
|
||||
}
|
||||
|
||||
if (createForm.password.trim()) payload.password = createForm.password
|
||||
|
||||
const resp = await fetch(`${API_BASE}/api/admin/users`, {
|
||||
method: "POST",
|
||||
headers: headers(),
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
if (!resp.ok) {
|
||||
setMessage(String(data.error || "Failed to create user."))
|
||||
return
|
||||
}
|
||||
|
||||
setCreateForm(initialUserForm)
|
||||
setMessage("User created successfully.")
|
||||
await fetchUsers(1)
|
||||
} catch {
|
||||
setMessage("Network error while creating user.")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const startEdit = (user: UserDoc) => {
|
||||
setEditMode(true)
|
||||
setEditId(getUserId(user))
|
||||
setEditForm({
|
||||
email: String(user.email || ""),
|
||||
username: String(user.username || ""),
|
||||
name: String(user.name || ""),
|
||||
wallet_address: String(user.wallet_address || ""),
|
||||
role: String(user.role || "student"),
|
||||
password: "",
|
||||
})
|
||||
}
|
||||
|
||||
const submitEdit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!editId) return
|
||||
|
||||
setSaving(true)
|
||||
setMessage("")
|
||||
|
||||
try {
|
||||
const payload: Record<string, unknown> = {
|
||||
email: editForm.email.trim(),
|
||||
username: editForm.username.trim(),
|
||||
name: editForm.name.trim(),
|
||||
wallet_address: editForm.wallet_address.trim(),
|
||||
role: editForm.role,
|
||||
}
|
||||
if (editForm.password.trim()) payload.password = editForm.password
|
||||
|
||||
const resp = await fetch(`${API_BASE}/api/admin/users/${editId}`, {
|
||||
method: "PUT",
|
||||
headers: headers(),
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
if (!resp.ok) {
|
||||
setMessage(String(data.error || "Failed to update user."))
|
||||
return
|
||||
}
|
||||
|
||||
setEditMode(false)
|
||||
setEditId("")
|
||||
setEditForm(initialUserForm)
|
||||
setMessage("User updated successfully.")
|
||||
await fetchUsers(pagination.page)
|
||||
} catch {
|
||||
setMessage("Network error while updating user.")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const quickAction = async (
|
||||
userId: string,
|
||||
action: "suspend" | "ban" | "activate" | "delete" | "reset-password",
|
||||
role?: string,
|
||||
) => {
|
||||
if (!userId) return
|
||||
|
||||
setActionLoadingId(`${userId}:${action}`)
|
||||
setMessage("")
|
||||
|
||||
try {
|
||||
let endpoint = `${API_BASE}/api/admin/users/${userId}/${action}`
|
||||
let method: "POST" | "DELETE" = "POST"
|
||||
let body: string | undefined
|
||||
|
||||
if (action === "delete") method = "DELETE"
|
||||
if (action === "reset-password") body = JSON.stringify({ new_password: "TempPass@123" })
|
||||
if (action === "suspend" || action === "ban" || action === "activate") {
|
||||
endpoint = `${API_BASE}/api/admin/users/${userId}/status`
|
||||
const statusMap: Record<string, string> = { suspend: "suspended", ban: "banned", activate: "active" }
|
||||
body = JSON.stringify({ status: statusMap[action] })
|
||||
}
|
||||
if (role) {
|
||||
endpoint = `${API_BASE}/api/admin/users/${userId}/role`
|
||||
body = JSON.stringify({ role })
|
||||
}
|
||||
|
||||
const resp = await fetch(endpoint, {
|
||||
method,
|
||||
headers: headers(),
|
||||
body,
|
||||
})
|
||||
|
||||
const data = await resp.json().catch(() => ({}))
|
||||
if (!resp.ok) {
|
||||
setMessage(String(data.error || "Action failed."))
|
||||
return
|
||||
}
|
||||
|
||||
setMessage(role ? `Role updated to ${role}.` : `User action ${action} completed.`)
|
||||
await fetchUsers(pagination.page)
|
||||
} catch {
|
||||
setMessage("Network error while running action.")
|
||||
} finally {
|
||||
setActionLoadingId("")
|
||||
}
|
||||
}
|
||||
|
||||
const roleSet = useMemo(() => {
|
||||
const roles = new Set<string>()
|
||||
for (const user of users) {
|
||||
const value = String(user.role || "").trim()
|
||||
if (value) roles.add(value)
|
||||
}
|
||||
return Array.from(roles)
|
||||
}, [users])
|
||||
|
||||
useEffect(() => {
|
||||
const init = async () => {
|
||||
const ok = await ensureAuth()
|
||||
if (!ok) return
|
||||
setReady(true)
|
||||
await fetchUsers(1)
|
||||
}
|
||||
init()
|
||||
}, [])
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-8 text-center dark:border-gray-800 dark:bg-gray-900">
|
||||
<p className="text-gray-600 dark:text-gray-300">Loading users...</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">User Management</h1>
|
||||
<p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
|
||||
Manage accounts, roles, access status, and student progress from real database records.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<form
|
||||
onSubmit={handleCreateUser}
|
||||
className="space-y-3 rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"
|
||||
>
|
||||
<h2 className="text-sm font-semibold text-gray-900 dark:text-gray-100">Create User</h2>
|
||||
<input
|
||||
value={createForm.email}
|
||||
onChange={(e) => setCreateForm((p) => ({ ...p, email: e.target.value }))}
|
||||
placeholder="Email"
|
||||
required
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<input
|
||||
value={createForm.username}
|
||||
onChange={(e) => setCreateForm((p) => ({ ...p, username: e.target.value }))}
|
||||
placeholder="Username"
|
||||
required
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<input
|
||||
value={createForm.name}
|
||||
onChange={(e) => setCreateForm((p) => ({ ...p, name: e.target.value }))}
|
||||
placeholder="Full name"
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<input
|
||||
value={createForm.wallet_address}
|
||||
onChange={(e) => setCreateForm((p) => ({ ...p, wallet_address: e.target.value }))}
|
||||
placeholder="Wallet address"
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<select
|
||||
value={createForm.role}
|
||||
onChange={(e) => setCreateForm((p) => ({ ...p, role: e.target.value }))}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
>
|
||||
<option value="student">student</option>
|
||||
<option value="instructor">instructor</option>
|
||||
<option value="admin">admin</option>
|
||||
</select>
|
||||
<input
|
||||
value={createForm.password}
|
||||
onChange={(e) => setCreateForm((p) => ({ ...p, password: e.target.value }))}
|
||||
placeholder="Password (optional)"
|
||||
type="password"
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-60"
|
||||
>
|
||||
{saving ? "Saving..." : "Create User"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<form
|
||||
onSubmit={submitEdit}
|
||||
className="space-y-3 rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-900"
|
||||
>
|
||||
<h2 className="text-sm font-semibold text-gray-900 dark:text-gray-100">Edit User</h2>
|
||||
{!editMode ? (
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">Select a user from the table to edit details.</p>
|
||||
) : (
|
||||
<>
|
||||
<input
|
||||
value={editForm.email}
|
||||
onChange={(e) => setEditForm((p) => ({ ...p, email: e.target.value }))}
|
||||
placeholder="Email"
|
||||
required
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<input
|
||||
value={editForm.username}
|
||||
onChange={(e) => setEditForm((p) => ({ ...p, username: e.target.value }))}
|
||||
placeholder="Username"
|
||||
required
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<input
|
||||
value={editForm.name}
|
||||
onChange={(e) => setEditForm((p) => ({ ...p, name: e.target.value }))}
|
||||
placeholder="Full name"
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<input
|
||||
value={editForm.wallet_address}
|
||||
onChange={(e) => setEditForm((p) => ({ ...p, wallet_address: e.target.value }))}
|
||||
placeholder="Wallet address"
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<select
|
||||
value={editForm.role}
|
||||
onChange={(e) => setEditForm((p) => ({ ...p, role: e.target.value }))}
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
>
|
||||
<option value="student">student</option>
|
||||
<option value="instructor">instructor</option>
|
||||
<option value="admin">admin</option>
|
||||
</select>
|
||||
<input
|
||||
value={editForm.password}
|
||||
onChange={(e) => setEditForm((p) => ({ ...p, password: e.target.value }))}
|
||||
placeholder="Set new password (optional)"
|
||||
type="password"
|
||||
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="rounded-md bg-emerald-600 px-4 py-2 text-sm font-medium text-white hover:bg-emerald-700 disabled:opacity-60"
|
||||
>
|
||||
{saving ? "Saving..." : "Save Changes"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setEditMode(false)
|
||||
setEditId("")
|
||||
setEditForm(initialUserForm)
|
||||
}}
|
||||
className="rounded-md bg-gray-200 px-4 py-2 text-sm font-medium text-gray-800 hover:bg-gray-300 dark:bg-gray-800 dark:text-gray-100 dark:hover:bg-gray-700"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900">
|
||||
<div className="flex flex-wrap items-center gap-2 border-b border-gray-100 p-4 dark:border-gray-800">
|
||||
<input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Search email, username, full name"
|
||||
className="min-w-[220px] flex-1 rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
/>
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
>
|
||||
<option value="all">All status</option>
|
||||
<option value="active">Active</option>
|
||||
<option value="suspended">Suspended</option>
|
||||
<option value="banned">Banned</option>
|
||||
</select>
|
||||
<select
|
||||
value={roleFilter}
|
||||
onChange={(e) => setRoleFilter(e.target.value)}
|
||||
className="rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-gray-700 dark:bg-gray-800"
|
||||
>
|
||||
<option value="all">All roles</option>
|
||||
<option value="student">student</option>
|
||||
<option value="instructor">instructor</option>
|
||||
<option value="admin">admin</option>
|
||||
{roleSet
|
||||
.filter((r) => r !== "student" && r !== "instructor" && r !== "admin")
|
||||
.map((role) => (
|
||||
<option key={role} value={role}>
|
||||
{role}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
onClick={() => fetchUsers(1, search, statusFilter, roleFilter)}
|
||||
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
|
||||
>
|
||||
Apply
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{message ? (
|
||||
<div className="border-b border-gray-100 px-4 py-2 text-sm text-gray-700 dark:border-gray-800 dark:text-gray-200">
|
||||
{message}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800/60">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Email</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Username</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Role</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Status</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Progress</th>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100 dark:divide-gray-800">
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-4 py-4 text-sm text-gray-600 dark:text-gray-300">
|
||||
Loading users...
|
||||
</td>
|
||||
</tr>
|
||||
) : users.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-4 py-4 text-sm text-gray-500">
|
||||
No users found.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
users.map((user, idx) => {
|
||||
const userId = getUserId(user)
|
||||
const status = String(user.status || "active")
|
||||
const progress = Number(user.progress_percent || user.progress || 0)
|
||||
|
||||
return (
|
||||
<tr key={userId || String(idx)}>
|
||||
<td className="px-3 py-2 text-xs text-gray-800 dark:text-gray-100">{String(user.email || "-")}</td>
|
||||
<td className="px-3 py-2 text-xs text-gray-700 dark:text-gray-300">{String(user.username || user.name || "-")}</td>
|
||||
<td className="px-3 py-2 text-xs text-gray-700 dark:text-gray-300">{String(user.role || "student")}</td>
|
||||
<td className="px-3 py-2 text-xs text-gray-700 dark:text-gray-300">{status}</td>
|
||||
<td className="px-3 py-2 text-xs text-gray-700 dark:text-gray-300">{Number.isFinite(progress) ? `${progress}%` : "0%"}</td>
|
||||
<td className="px-3 py-2 text-xs">
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<button
|
||||
onClick={() => setSelectedUser(user)}
|
||||
className="rounded bg-gray-100 px-2 py-1 text-gray-800 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-100 dark:hover:bg-gray-700"
|
||||
>
|
||||
View
|
||||
</button>
|
||||
<button
|
||||
onClick={() => startEdit(user)}
|
||||
className="rounded bg-blue-600 px-2 py-1 text-white hover:bg-blue-700"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
disabled={actionLoadingId === `${userId}:suspend`}
|
||||
onClick={() => quickAction(userId, "suspend")}
|
||||
className="rounded bg-amber-600 px-2 py-1 text-white hover:bg-amber-700 disabled:opacity-60"
|
||||
>
|
||||
Suspend
|
||||
</button>
|
||||
<button
|
||||
disabled={actionLoadingId === `${userId}:ban`}
|
||||
onClick={() => quickAction(userId, "ban")}
|
||||
className="rounded bg-rose-600 px-2 py-1 text-white hover:bg-rose-700 disabled:opacity-60"
|
||||
>
|
||||
Ban
|
||||
</button>
|
||||
<button
|
||||
disabled={actionLoadingId === `${userId}:activate`}
|
||||
onClick={() => quickAction(userId, "activate")}
|
||||
className="rounded bg-emerald-600 px-2 py-1 text-white hover:bg-emerald-700 disabled:opacity-60"
|
||||
>
|
||||
Activate
|
||||
</button>
|
||||
<button
|
||||
disabled={actionLoadingId === `${userId}:reset-password`}
|
||||
onClick={() => quickAction(userId, "reset-password")}
|
||||
className="rounded bg-purple-600 px-2 py-1 text-white hover:bg-purple-700 disabled:opacity-60"
|
||||
>
|
||||
Reset Password
|
||||
</button>
|
||||
<button
|
||||
onClick={() => quickAction(userId, "activate", "student")}
|
||||
className="rounded bg-slate-600 px-2 py-1 text-white hover:bg-slate-700"
|
||||
>
|
||||
Set Student
|
||||
</button>
|
||||
<button
|
||||
onClick={() => quickAction(userId, "activate", "instructor")}
|
||||
className="rounded bg-slate-600 px-2 py-1 text-white hover:bg-slate-700"
|
||||
>
|
||||
Set Instructor
|
||||
</button>
|
||||
<button
|
||||
onClick={() => quickAction(userId, "activate", "admin")}
|
||||
className="rounded bg-slate-900 px-2 py-1 text-white hover:bg-black"
|
||||
>
|
||||
Set Admin
|
||||
</button>
|
||||
<button
|
||||
disabled={actionLoadingId === `${userId}:delete`}
|
||||
onClick={() => quickAction(userId, "delete")}
|
||||
className="rounded bg-red-800 px-2 py-1 text-white hover:bg-red-900 disabled:opacity-60"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between border-t border-gray-100 px-4 py-3 text-sm text-gray-600 dark:border-gray-800 dark:text-gray-300">
|
||||
<span>
|
||||
Page {pagination.page} of {pagination.pages} | Total {pagination.total}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => fetchUsers(Math.max(1, pagination.page - 1), search, statusFilter, roleFilter)}
|
||||
disabled={pagination.page <= 1}
|
||||
className="rounded bg-gray-100 px-3 py-1.5 disabled:opacity-50 dark:bg-gray-800"
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
<button
|
||||
onClick={() => fetchUsers(Math.min(pagination.pages, pagination.page + 1), search, statusFilter, roleFilter)}
|
||||
disabled={pagination.page >= pagination.pages}
|
||||
className="rounded bg-gray-100 px-3 py-1.5 disabled:opacity-50 dark:bg-gray-800"
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedUser ? (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
|
||||
<div className="w-full max-w-4xl rounded-xl border border-gray-200 bg-white p-4 shadow-xl dark:border-gray-800 dark:bg-gray-900">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">Full User Document</h3>
|
||||
<button
|
||||
onClick={() => setSelectedUser(null)}
|
||||
className="rounded bg-gray-100 px-3 py-1.5 text-sm hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
<pre className="max-h-[70vh] overflow-auto rounded bg-gray-50 p-3 text-xs text-gray-800 dark:bg-gray-950 dark:text-gray-100">
|
||||
{JSON.stringify(selectedUser, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user