Initial commit: EduBox V2 platform
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
FROM node:24-alpine
|
||||
WORKDIR /app
|
||||
RUN apk add --no-cache openssl
|
||||
COPY package.json package-lock.json* ./
|
||||
COPY prisma ./prisma
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
CMD ["node_modules/.bin/next", "start"]
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function LoginForm() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
const res = await signIn("credentials", { email, password, redirect: false });
|
||||
setLoading(false);
|
||||
if (res?.error) {
|
||||
setError("Email ou mot de passe invalide");
|
||||
} else {
|
||||
router.push("/dashboard");
|
||||
router.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && <div className="text-sm text-destructive text-center">{error}</div>}
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Email</label>
|
||||
<Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Mot de passe</label>
|
||||
<Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading ? "Connexion..." : "Se connecter"}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import LoginForm from "./LoginForm";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-50">
|
||||
<div className="w-full max-w-md p-8 space-y-6 bg-white rounded-lg shadow-md">
|
||||
<h1 className="text-2xl font-bold text-center text-gray-900">EduBox V2</h1>
|
||||
<p className="text-center text-muted-foreground">Connexion à la plateforme</p>
|
||||
<LoginForm />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import NextAuth from "next-auth";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
|
||||
const handler = NextAuth(authOptions);
|
||||
|
||||
export { handler as GET, handler as POST };
|
||||
@@ -0,0 +1,24 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const establishmentId = searchParams.get("establishmentId");
|
||||
if (!establishmentId) return NextResponse.json({ error: "Missing establishmentId" }, { status: 400 });
|
||||
|
||||
const classes = await prisma.class.findMany({
|
||||
where: { establishmentId },
|
||||
include: { _count: { select: { students: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return NextResponse.json(classes);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json();
|
||||
const { establishmentId, name, level } = body;
|
||||
const cls = await prisma.class.create({
|
||||
data: { establishmentId, name, level },
|
||||
});
|
||||
return NextResponse.json(cls, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json({
|
||||
windows: "/agent/edubox-agent.exe",
|
||||
linux: "/agent/edubox-agent",
|
||||
mac: "/agent/edubox-agent-mac",
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { hashPassword } from "@/lib/auth";
|
||||
|
||||
export async function GET() {
|
||||
const establishments = await prisma.establishment.findMany({
|
||||
include: { subscription: true, _count: { select: { users: true, classes: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return NextResponse.json(establishments);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json();
|
||||
const { name, slug, adminEmail, adminPassword } = body;
|
||||
|
||||
const establishment = await prisma.establishment.create({
|
||||
data: { name, slug },
|
||||
});
|
||||
|
||||
await prisma.subscription.create({
|
||||
data: { establishmentId: establishment.id, plan: "trial", status: "active" },
|
||||
});
|
||||
|
||||
if (adminEmail && adminPassword) {
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
email: adminEmail,
|
||||
password: await hashPassword(adminPassword),
|
||||
role: "admin",
|
||||
establishmentId: establishment.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json(establishment, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { sendToNode } from "@/lib/websocket";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const nodeId = searchParams.get("nodeId");
|
||||
const establishmentId = searchParams.get("establishmentId");
|
||||
|
||||
let where: any = {};
|
||||
if (nodeId) where.nodeId = nodeId;
|
||||
if (establishmentId) {
|
||||
const classes = await prisma.class.findMany({ where: { establishmentId }, select: { id: true } });
|
||||
const students = await prisma.student.findMany({ where: { classId: { in: classes.map((c) => c.id) } }, select: { id: true } });
|
||||
const nodes = await prisma.node.findMany({ where: { studentId: { in: students.map((s) => s.id) } }, select: { id: true } });
|
||||
where.nodeId = { in: nodes.map((n) => n.id) };
|
||||
}
|
||||
|
||||
const instances = await prisma.instance.findMany({
|
||||
where,
|
||||
include: { node: { include: { student: { include: { class: true } } } }, template: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return NextResponse.json(instances);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json();
|
||||
const { nodeId, templateId, port } = body;
|
||||
|
||||
const template = await prisma.template.findUnique({ where: { id: templateId } });
|
||||
if (!template) return NextResponse.json({ error: "Template not found" }, { status: 404 });
|
||||
|
||||
const instance = await prisma.instance.create({
|
||||
data: { nodeId, templateId, port: port || 8080, status: "stopped" },
|
||||
});
|
||||
|
||||
const sent = sendToNode(nodeId, {
|
||||
action: "start",
|
||||
instanceId: instance.id,
|
||||
type: template.type,
|
||||
port: instance.port,
|
||||
composeConfig: template.composeConfig.replace(/{PORT}/g, String(instance.port)).replace(/{INSTANCE_ID}/g, instance.id),
|
||||
});
|
||||
|
||||
if (!sent) {
|
||||
await prisma.instance.update({ where: { id: instance.id }, data: { status: "error" } });
|
||||
}
|
||||
|
||||
return NextResponse.json(instance, { status: 201 });
|
||||
}
|
||||
|
||||
export async function PATCH(req: NextRequest) {
|
||||
const body = await req.json();
|
||||
const { id, action } = body;
|
||||
const instance = await prisma.instance.findUnique({ where: { id }, include: { template: true } });
|
||||
if (!instance) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
if (action === "stop") {
|
||||
sendToNode(instance.nodeId, { action: "stop", instanceId: instance.id });
|
||||
await prisma.instance.update({ where: { id }, data: { status: "stopped" } });
|
||||
} else if (action === "start") {
|
||||
const sent = sendToNode(instance.nodeId, {
|
||||
action: "start",
|
||||
instanceId: instance.id,
|
||||
type: instance.template.type,
|
||||
port: instance.port,
|
||||
composeConfig: instance.template.composeConfig.replace(/{PORT}/g, String(instance.port)).replace(/{INSTANCE_ID}/g, instance.id),
|
||||
});
|
||||
if (!sent) await prisma.instance.update({ where: { id }, data: { status: "error" } });
|
||||
} else if (action === "reset") {
|
||||
sendToNode(instance.nodeId, { action: "reset", instanceId: instance.id });
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const id = searchParams.get("id");
|
||||
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
|
||||
const instance = await prisma.instance.findUnique({ where: { id } });
|
||||
if (instance) sendToNode(instance.nodeId, { action: "stop", instanceId: instance.id });
|
||||
await prisma.instance.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const establishmentId = searchParams.get("establishmentId");
|
||||
|
||||
let where: any = {};
|
||||
if (establishmentId) {
|
||||
const classes = await prisma.class.findMany({ where: { establishmentId }, select: { id: true } });
|
||||
const students = await prisma.student.findMany({ where: { classId: { in: classes.map((c) => c.id) } }, select: { id: true } });
|
||||
where.studentId = { in: students.map((s) => s.id) };
|
||||
}
|
||||
|
||||
const nodes = await prisma.node.findMany({
|
||||
where,
|
||||
include: { student: { include: { class: true } }, instances: true },
|
||||
orderBy: { lastSeen: "desc" },
|
||||
});
|
||||
return NextResponse.json(nodes);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
function generateCode(length = 6) {
|
||||
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
let code = "";
|
||||
for (let i = 0; i < length; i++) code += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
return code;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const classId = searchParams.get("classId");
|
||||
const establishmentId = searchParams.get("establishmentId");
|
||||
|
||||
const where: any = {};
|
||||
if (classId) where.classId = classId;
|
||||
if (establishmentId) {
|
||||
const classes = await prisma.class.findMany({ where: { establishmentId }, select: { id: true } });
|
||||
where.classId = { in: classes.map((c) => c.id) };
|
||||
}
|
||||
|
||||
const students = await prisma.student.findMany({
|
||||
where,
|
||||
include: { class: true, nodes: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return NextResponse.json(students);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json();
|
||||
const { classId, firstName, lastName, email } = body;
|
||||
const student = await prisma.student.create({
|
||||
data: {
|
||||
classId,
|
||||
firstName,
|
||||
lastName,
|
||||
email,
|
||||
activationCode: generateCode(),
|
||||
},
|
||||
});
|
||||
return NextResponse.json(student, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const establishmentId = searchParams.get("establishmentId");
|
||||
|
||||
const templates = await prisma.template.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ isPublic: true },
|
||||
...(establishmentId ? [{ establishmentId }] : []),
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return NextResponse.json(templates);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json();
|
||||
const { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy } = body;
|
||||
const template = await prisma.template.create({
|
||||
data: { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy },
|
||||
});
|
||||
return NextResponse.json(template, { status: 201 });
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest) {
|
||||
const body = await req.json();
|
||||
const { id, ...data } = body;
|
||||
const template = await prisma.template.update({ where: { id }, data });
|
||||
return NextResponse.json(template);
|
||||
}
|
||||
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const id = searchParams.get("id");
|
||||
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
|
||||
await prisma.template.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { hashPassword } from "@/lib/auth";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const establishmentId = searchParams.get("establishmentId");
|
||||
const role = searchParams.get("role");
|
||||
|
||||
const where: any = {};
|
||||
if (establishmentId) where.establishmentId = establishmentId;
|
||||
if (role) where.role = role;
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return NextResponse.json(users);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json();
|
||||
const { email, password, role, establishmentId } = body;
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
password: await hashPassword(password),
|
||||
role,
|
||||
establishmentId,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(user, { status: 201 });
|
||||
}
|
||||
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const id = searchParams.get("id");
|
||||
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
|
||||
await prisma.user.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { WebSocketServer } from "ws";
|
||||
import { initWebSocketServer } from "@/lib/websocket";
|
||||
|
||||
const globalWss = globalThis as typeof globalThis & { __eduboxWss?: WebSocketServer };
|
||||
|
||||
if (!globalWss.__eduboxWss) {
|
||||
try {
|
||||
globalWss.__eduboxWss = new WebSocketServer({ port: 3001 });
|
||||
initWebSocketServer(globalWss.__eduboxWss);
|
||||
} catch {
|
||||
// Port may be in use during build or hot reload
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
return new Response("WebSocket server running on port 3001", { status: 200 });
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { signOut } from "next-auth/react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const links = [
|
||||
{ href: "/dashboard", label: "Accueil" },
|
||||
{ href: "/dashboard/classes", label: "Classes" },
|
||||
{ href: "/dashboard/students", label: "Étudiants" },
|
||||
{ href: "/dashboard/nodes", label: "Nœuds" },
|
||||
{ href: "/dashboard/instances", label: "Instances" },
|
||||
{ href: "/dashboard/templates", label: "Templates" },
|
||||
{ href: "/dashboard/download", label: "Téléchargements" },
|
||||
];
|
||||
|
||||
const superadminLinks = [
|
||||
{ href: "/superadmin", label: "Super Admin" },
|
||||
{ href: "/superadmin/establishments", label: "Établissements" },
|
||||
];
|
||||
|
||||
export default function DashboardNav({ role }: { role: string }) {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<nav className="w-64 bg-white border-r flex flex-col">
|
||||
<div className="p-6 border-b">
|
||||
<h2 className="text-xl font-bold text-primary">EduBox</h2>
|
||||
</div>
|
||||
<div className="flex-1 p-4 space-y-1">
|
||||
{links.map((link) => (
|
||||
<Link
|
||||
key={link.href}
|
||||
href={link.href}
|
||||
className={cn(
|
||||
"block px-3 py-2 rounded-md text-sm font-medium transition-colors",
|
||||
pathname === link.href ? "bg-primary text-primary-foreground" : "text-gray-700 hover:bg-gray-100"
|
||||
)}
|
||||
>
|
||||
{link.label}
|
||||
</Link>
|
||||
))}
|
||||
{role === "superadmin" && (
|
||||
<div className="pt-4 mt-4 border-t">
|
||||
<p className="px-3 text-xs font-semibold text-muted-foreground uppercase mb-2">Super Admin</p>
|
||||
{superadminLinks.map((link) => (
|
||||
<Link
|
||||
key={link.href}
|
||||
href={link.href}
|
||||
className={cn(
|
||||
"block px-3 py-2 rounded-md text-sm font-medium transition-colors",
|
||||
pathname === link.href ? "bg-primary text-primary-foreground" : "text-gray-700 hover:bg-gray-100"
|
||||
)}
|
||||
>
|
||||
{link.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="p-4 border-t">
|
||||
<button
|
||||
onClick={() => signOut({ callbackUrl: "/login" })}
|
||||
className="w-full text-left px-3 py-2 text-sm font-medium text-destructive hover:bg-destructive/10 rounded-md transition-colors"
|
||||
>
|
||||
Déconnexion
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function ClassesPage() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");
|
||||
|
||||
const establishmentId = session.user.establishmentId;
|
||||
const classes = await prisma.class.findMany({
|
||||
where: establishmentId ? { establishmentId } : {},
|
||||
include: { _count: { select: { students: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-3xl font-bold">Classes</h1>
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Nom</TableHead>
|
||||
<TableHead>Niveau</TableHead>
|
||||
<TableHead>Étudiants</TableHead>
|
||||
<TableHead>Créée le</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{classes.map((cls) => (
|
||||
<TableRow key={cls.id}>
|
||||
<TableCell className="font-medium">{cls.name}</TableCell>
|
||||
<TableCell>{cls.level}</TableCell>
|
||||
<TableCell>{cls._count.students}</TableCell>
|
||||
<TableCell>{new Date(cls.createdAt).toLocaleDateString("fr-FR")}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{classes.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="text-center text-muted-foreground">Aucune classe</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default function DownloadPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-3xl font-bold">Téléchargements Agent</h1>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Windows</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground mb-4">Agent EduBox pour Windows (64 bits)</p>
|
||||
<a href="/agent/edubox-agent.exe" download className="inline-flex items-center justify-center rounded-md text-sm font-medium bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-4 py-2 w-full">Télécharger (.exe)</a>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Linux</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground mb-4">Agent EduBox pour Linux (64 bits)</p>
|
||||
<a href="/agent/edubox-agent" download className="inline-flex items-center justify-center rounded-md text-sm font-medium bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-4 py-2 w-full">Télécharger</a>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>macOS</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground mb-4">Agent EduBox pour macOS (Intel & Apple Silicon)</p>
|
||||
<a href="/agent/edubox-agent-mac" download className="inline-flex items-center justify-center rounded-md text-sm font-medium bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-4 py-2 w-full">Télécharger</a>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function InstanceActions({ instanceId, status }: { instanceId: string; status: string }) {
|
||||
const [loading, setLoading] = useState<string | null>(null);
|
||||
|
||||
async function action(type: string) {
|
||||
setLoading(type);
|
||||
await fetch("/api/instances", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ id: instanceId, action: type }),
|
||||
});
|
||||
setLoading(null);
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
{status !== "running" && (
|
||||
<Button size="sm" variant="outline" onClick={() => action("start")} disabled={!!loading}>
|
||||
{loading === "start" ? "..." : "Démarrer"}
|
||||
</Button>
|
||||
)}
|
||||
{status === "running" && (
|
||||
<Button size="sm" variant="outline" onClick={() => action("stop")} disabled={!!loading}>
|
||||
{loading === "stop" ? "..." : "Arrêter"}
|
||||
</Button>
|
||||
)}
|
||||
<Button size="sm" variant="outline" onClick={() => action("reset")} disabled={!!loading}>
|
||||
{loading === "reset" ? "..." : "Réinitialiser"}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Select } from "@/components/ui/select";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export default function AssignForm({ templates, nodes }: { templates: any[]; nodes: any[] }) {
|
||||
const [templateId, setTemplateId] = useState("");
|
||||
const [nodeId, setNodeId] = useState("");
|
||||
const [port, setPort] = useState("8080");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
await fetch("/api/instances", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ templateId, nodeId, port: parseInt(port) }),
|
||||
});
|
||||
setLoading(false);
|
||||
router.push("/dashboard/instances");
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4 bg-white p-6 rounded-lg border shadow-sm">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Template</label>
|
||||
<Select value={templateId} onChange={(e) => setTemplateId(e.target.value)} required>
|
||||
<option value="">Choisir un template</option>
|
||||
{templates.map((t) => (
|
||||
<option key={t.id} value={t.id}>{t.name}</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Nœud (étudiant)</label>
|
||||
<Select value={nodeId} onChange={(e) => setNodeId(e.target.value)} required>
|
||||
<option value="">Choisir un nœud</option>
|
||||
{nodes.map((n) => (
|
||||
<option key={n.id} value={n.id}>
|
||||
{n.id} {n.student ? `- ${n.student.firstName} ${n.student.lastName}` : ""}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Port</label>
|
||||
<Input type="number" value={port} onChange={(e) => setPort(e.target.value)} required />
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading ? "Attribution..." : "Attribuer"}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
import AssignForm from "./AssignForm";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function AssignPage() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");
|
||||
|
||||
const establishmentId = session.user.establishmentId;
|
||||
const templates = await prisma.template.findMany({
|
||||
where: { OR: [{ isPublic: true }, ...(establishmentId ? [{ establishmentId }] : [])] },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
const nodes = await prisma.node.findMany({
|
||||
where: establishmentId
|
||||
? { student: { class: { establishmentId } } }
|
||||
: {},
|
||||
include: { student: { include: { class: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-xl">
|
||||
<h1 className="text-3xl font-bold">Attribuer une instance</h1>
|
||||
<AssignForm templates={templates} nodes={nodes} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import InstanceActions from "./InstanceActions";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function InstancesPage() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");
|
||||
|
||||
const establishmentId = session.user.establishmentId;
|
||||
const instances = await prisma.instance.findMany({
|
||||
where: establishmentId
|
||||
? { node: { student: { class: { establishmentId } } } }
|
||||
: {},
|
||||
include: { node: { include: { student: { include: { class: true } } } }, template: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-3xl font-bold">Instances</h1>
|
||||
<Link href="/dashboard/instances/assign">
|
||||
<Button>Attribuer une instance</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>ID</TableHead>
|
||||
<TableHead>Template</TableHead>
|
||||
<TableHead>Nœud</TableHead>
|
||||
<TableHead>Étudiant</TableHead>
|
||||
<TableHead>Port</TableHead>
|
||||
<TableHead>Statut</TableHead>
|
||||
<TableHead>Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{instances.map((inst) => (
|
||||
<TableRow key={inst.id}>
|
||||
<TableCell className="font-medium">{inst.id.slice(0, 8)}...</TableCell>
|
||||
<TableCell>{inst.template.name}</TableCell>
|
||||
<TableCell>{inst.node.id.slice(0, 8)}...</TableCell>
|
||||
<TableCell>{inst.node.student ? `${inst.node.student.firstName} ${inst.node.student.lastName}` : "-"}</TableCell>
|
||||
<TableCell>{inst.port}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={inst.status === "running" ? "success" : inst.status === "error" ? "destructive" : "secondary"}>{inst.status}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<InstanceActions instanceId={inst.id} status={inst.status} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{instances.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} className="text-center text-muted-foreground">Aucune instance</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
import DashboardNav from "./DashboardNav";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen bg-gray-50">
|
||||
<DashboardNav role={session.user.role} />
|
||||
<main className="flex-1 p-6 overflow-auto">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function NodesPage() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");
|
||||
|
||||
const establishmentId = session.user.establishmentId;
|
||||
const nodes = await prisma.node.findMany({
|
||||
where: establishmentId
|
||||
? { student: { class: { establishmentId } } }
|
||||
: {},
|
||||
include: { student: { include: { class: true } }, instances: true },
|
||||
orderBy: { lastSeen: "desc" },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-3xl font-bold">Nœuds</h1>
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>ID</TableHead>
|
||||
<TableHead>Étudiant</TableHead>
|
||||
<TableHead>IP Tailscale</TableHead>
|
||||
<TableHead>Statut</TableHead>
|
||||
<TableHead>Instances</TableHead>
|
||||
<TableHead>Dernière vue</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{nodes.map((n) => (
|
||||
<TableRow key={n.id}>
|
||||
<TableCell className="font-medium">{n.id}</TableCell>
|
||||
<TableCell>{n.student ? `${n.student.firstName} ${n.student.lastName}` : "-"}</TableCell>
|
||||
<TableCell>{n.tailscaleIp || "-"}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={n.status === "online" ? "success" : "secondary"}>{n.status}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{n.instances.length}</TableCell>
|
||||
<TableCell>{n.lastSeen ? new Date(n.lastSeen).toLocaleString("fr-FR") : "-"}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{nodes.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="text-center text-muted-foreground">Aucun nœud</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
|
||||
const isSuperadmin = session.user.role === "superadmin";
|
||||
const establishmentId = session.user.establishmentId;
|
||||
|
||||
const where = isSuperadmin ? {} : { establishmentId };
|
||||
|
||||
const nodesCount = await prisma.node.count({
|
||||
where: isSuperadmin ? {} : { student: { class: { establishmentId } } },
|
||||
});
|
||||
const onlineNodes = await prisma.node.count({
|
||||
where: isSuperadmin ? { status: "online" } : { status: "online", student: { class: { establishmentId } } },
|
||||
});
|
||||
const instancesRunning = await prisma.instance.count({
|
||||
where: isSuperadmin ? { status: "running" } : { status: "running", node: { student: { class: { establishmentId } } } },
|
||||
});
|
||||
const studentsCount = await prisma.student.count({
|
||||
where: isSuperadmin ? {} : { class: { establishmentId } },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-3xl font-bold">Tableau de bord</h1>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Nœuds</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-3xl font-bold">{nodesCount}</div>
|
||||
<Badge variant="success" className="mt-2">{onlineNodes} en ligne</Badge>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Instances actives</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-3xl font-bold">{instancesRunning}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Étudiants</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-3xl font-bold">{studentsCount}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Statut</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Badge variant="success">Opérationnel</Badge>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function StudentsPage() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");
|
||||
|
||||
const establishmentId = session.user.establishmentId;
|
||||
const students = await prisma.student.findMany({
|
||||
where: establishmentId ? { class: { establishmentId } } : {},
|
||||
include: { class: true, nodes: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-3xl font-bold">Étudiants</h1>
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Nom</TableHead>
|
||||
<TableHead>Classe</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Code activation</TableHead>
|
||||
<TableHead>Nœud</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{students.map((s) => {
|
||||
const node = s.nodes[0];
|
||||
return (
|
||||
<TableRow key={s.id}>
|
||||
<TableCell className="font-medium">{s.firstName} {s.lastName}</TableCell>
|
||||
<TableCell>{s.class.name}</TableCell>
|
||||
<TableCell>{s.email}</TableCell>
|
||||
<TableCell>{s.activationCode || "-"}</TableCell>
|
||||
<TableCell>
|
||||
{node ? (
|
||||
<Badge variant={node.status === "online" ? "success" : "secondary"}>{node.status}</Badge>
|
||||
) : (
|
||||
<Badge variant="outline">Non lié</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
{students.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center text-muted-foreground">Aucun étudiant</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function TemplatesPage() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
|
||||
const establishmentId = session.user.establishmentId;
|
||||
const templates = await prisma.template.findMany({
|
||||
where: { OR: [{ isPublic: true }, ...(establishmentId ? [{ establishmentId }] : [])] },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-3xl font-bold">Templates</h1>
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Nom</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead>Image Docker</TableHead>
|
||||
<TableHead>Visibilité</TableHead>
|
||||
<TableHead>Créé par</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{templates.map((t) => (
|
||||
<TableRow key={t.id}>
|
||||
<TableCell className="font-medium">{t.name}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="secondary">{t.type}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{t.dockerImage}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={t.isPublic ? "success" : "outline"}>{t.isPublic ? "Public" : "Privé"}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{t.createdBy}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{templates.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center text-muted-foreground">Aucun template</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 222.2 84% 4.9%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 222.2 84% 4.9%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 222.2 84% 4.9%;
|
||||
--primary: 221.2 83.2% 53.3%;
|
||||
--primary-foreground: 210 40% 98%;
|
||||
--secondary: 210 40% 96.1%;
|
||||
--secondary-foreground: 222.2 47.4% 11.2%;
|
||||
--muted: 210 40% 96.1%;
|
||||
--muted-foreground: 215.4 16.3% 46.9%;
|
||||
--accent: 210 40% 96.1%;
|
||||
--accent-foreground: 222.2 47.4% 11.2%;
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
--border: 214.3 31.8% 91.4%;
|
||||
--input: 214.3 31.8% 91.4%;
|
||||
--ring: 221.2 83.2% 53.3%;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Inter } from "next/font/google";
|
||||
import "./globals.css";
|
||||
|
||||
const inter = Inter({ subsets: ["latin"] });
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "EduBox V2",
|
||||
description: "Plateforme de gestion d'instances pour l'enseignement BTS",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="fr">
|
||||
<body className={inter.className}>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { redirect } from 'next/navigation'
|
||||
|
||||
export default function Home() {
|
||||
redirect('/dashboard')
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function EstablishmentsPage() {
|
||||
const establishments = await prisma.establishment.findMany({
|
||||
include: { subscription: true, _count: { select: { users: true, classes: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-3xl font-bold">Établissements</h1>
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Nom</TableHead>
|
||||
<TableHead>Slug</TableHead>
|
||||
<TableHead>Plan</TableHead>
|
||||
<TableHead>Statut</TableHead>
|
||||
<TableHead>Utilisateurs</TableHead>
|
||||
<TableHead>Classes</TableHead>
|
||||
<TableHead>Expiration</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{establishments.map((e) => (
|
||||
<TableRow key={e.id}>
|
||||
<TableCell className="font-medium">{e.name}</TableCell>
|
||||
<TableCell>{e.slug}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="secondary">{e.subscription?.plan || "-"}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={e.subscription?.status === "active" ? "success" : "destructive"}>{e.subscription?.status || "-"}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{e._count.users}</TableCell>
|
||||
<TableCell>{e._count.classes}</TableCell>
|
||||
<TableCell>{e.subscription?.expiresAt ? new Date(e.subscription.expiresAt).toLocaleDateString("fr-FR") : "-"}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{establishments.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} className="text-center text-muted-foreground">Aucun établissement</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function SuperAdminLayout({ children }: { children: React.ReactNode }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user || session.user.role !== "superadmin") redirect("/dashboard");
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function SuperAdminPage() {
|
||||
const establishments = await prisma.establishment.count();
|
||||
const users = await prisma.user.count();
|
||||
const students = await prisma.student.count();
|
||||
const nodesOnline = await prisma.node.count({ where: { status: "online" } });
|
||||
const instancesRunning = await prisma.instance.count({ where: { status: "running" } });
|
||||
const activeSubs = await prisma.subscription.count({ where: { status: "active" } });
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-3xl font-bold">Super Admin — Vue globale</h1>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-3 gap-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Établissements</CardTitle></CardHeader>
|
||||
<CardContent><div className="text-3xl font-bold">{establishments}</div></CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Utilisateurs</CardTitle></CardHeader>
|
||||
<CardContent><div className="text-3xl font-bold">{users}</div></CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Étudiants</CardTitle></CardHeader>
|
||||
<CardContent><div className="text-3xl font-bold">{students}</div></CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Nœuds en ligne</CardTitle></CardHeader>
|
||||
<CardContent><div className="text-3xl font-bold">{nodesOnline}</div></CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Instances running</CardTitle></CardHeader>
|
||||
<CardContent><div className="text-3xl font-bold">{instancesRunning}</div></CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Abonnements actifs</CardTitle></CardHeader>
|
||||
<CardContent><div className="text-3xl font-bold">{activeSubs}</div></CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface BadgeProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
variant?: "default" | "secondary" | "destructive" | "outline" | "success";
|
||||
}
|
||||
|
||||
function Badge({ className, variant = "default", ...props }: BadgeProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
variant === "default" && "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
|
||||
variant === "secondary" && "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
variant === "destructive" && "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
|
||||
variant === "outline" && "text-foreground",
|
||||
variant === "success" && "border-transparent bg-green-100 text-green-800 hover:bg-green-200",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Badge };
|
||||
@@ -0,0 +1,36 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: "default" | "outline" | "ghost" | "destructive";
|
||||
size?: "default" | "sm" | "lg";
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant = "default", size = "default", asChild = false, children, ...props }, ref) => {
|
||||
const Comp = asChild ? "span" : "button";
|
||||
return (
|
||||
<Comp
|
||||
className={cn(
|
||||
"inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
|
||||
variant === "default" && "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
variant === "outline" && "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
variant === "ghost" && "hover:bg-accent hover:text-accent-foreground",
|
||||
variant === "destructive" && "bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
size === "default" && "h-10 px-4 py-2",
|
||||
size === "sm" && "h-9 rounded-md px-3",
|
||||
size === "lg" && "h-11 rounded-md px-8",
|
||||
className
|
||||
)}
|
||||
ref={ref as any}
|
||||
{...props as any}
|
||||
>
|
||||
{children}
|
||||
</Comp>
|
||||
);
|
||||
}
|
||||
);
|
||||
Button.displayName = "Button";
|
||||
|
||||
export { Button };
|
||||
@@ -0,0 +1,24 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)} {...props} />
|
||||
));
|
||||
Card.displayName = "Card";
|
||||
|
||||
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
|
||||
));
|
||||
CardHeader.displayName = "CardHeader";
|
||||
|
||||
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(({ className, ...props }, ref) => (
|
||||
<h3 ref={ref} className={cn("text-2xl font-semibold leading-none tracking-tight", className)} {...props} />
|
||||
));
|
||||
CardTitle.displayName = "CardTitle";
|
||||
|
||||
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
|
||||
));
|
||||
CardContent.displayName = "CardContent";
|
||||
|
||||
export { Card, CardHeader, CardTitle, CardContent };
|
||||
@@ -0,0 +1,29 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Dialog = ({ open, onOpenChange, children }: { open?: boolean; onOpenChange?: (v: boolean) => void; children: React.ReactNode }) => {
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={() => onOpenChange?.(false)}>
|
||||
<div className={cn("relative z-50 grid w-full max-w-lg gap-4 border bg-background p-6 shadow-lg rounded-lg")} onClick={(e) => e.stopPropagation()}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const DialogContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("grid gap-4", className)} {...props} />
|
||||
));
|
||||
DialogContent.displayName = "DialogContent";
|
||||
|
||||
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
|
||||
);
|
||||
|
||||
const DialogTitle = React.forwardRef<HTMLHeadingElement, React.HTMLAttributes<HTMLHeadingElement>>(({ className, ...props }, ref) => (
|
||||
<h3 ref={ref} className={cn("text-lg font-semibold leading-none tracking-tight", className)} {...props} />
|
||||
));
|
||||
DialogTitle.displayName = "DialogTitle";
|
||||
|
||||
export { Dialog, DialogContent, DialogHeader, DialogTitle };
|
||||
@@ -0,0 +1,21 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Input.displayName = "Input";
|
||||
|
||||
export { Input };
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Select = React.forwardRef<HTMLSelectElement, React.SelectHTMLAttributes<HTMLSelectElement>>(
|
||||
({ className, ...props }, ref) => {
|
||||
return (
|
||||
<select
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Select.displayName = "Select";
|
||||
|
||||
export { Select };
|
||||
@@ -0,0 +1,36 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(({ className, ...props }, ref) => (
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
|
||||
</div>
|
||||
));
|
||||
Table.displayName = "Table";
|
||||
|
||||
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(({ className, ...props }, ref) => (
|
||||
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
|
||||
));
|
||||
TableHeader.displayName = "TableHeader";
|
||||
|
||||
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(({ className, ...props }, ref) => (
|
||||
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
|
||||
));
|
||||
TableBody.displayName = "TableBody";
|
||||
|
||||
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(({ className, ...props }, ref) => (
|
||||
<tr ref={ref} className={cn("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", className)} {...props} />
|
||||
));
|
||||
TableRow.displayName = "TableRow";
|
||||
|
||||
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(({ className, ...props }, ref) => (
|
||||
<th ref={ref} className={cn("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0", className)} {...props} />
|
||||
));
|
||||
TableHead.displayName = "TableHead";
|
||||
|
||||
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(({ className, ...props }, ref) => (
|
||||
<td ref={ref} className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)} {...props} />
|
||||
));
|
||||
TableCell.displayName = "TableCell";
|
||||
|
||||
export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
|
||||
@@ -0,0 +1,28 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Tabs = ({ children, className }: { children: React.ReactNode; className?: string }) => (
|
||||
<div className={cn("w-full", className)}>{children}</div>
|
||||
);
|
||||
|
||||
const TabsList = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground", className)} {...props} />
|
||||
));
|
||||
TabsList.displayName = "TabsList";
|
||||
|
||||
const TabsTrigger = React.forwardRef<HTMLButtonElement, React.ButtonHTMLAttributes<HTMLButtonElement> & { active?: boolean }>(
|
||||
({ className, active, ...props }, ref) => (
|
||||
<button
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
|
||||
active && "bg-background text-foreground shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
TabsTrigger.displayName = "TabsTrigger";
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger };
|
||||
@@ -0,0 +1,45 @@
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
import { prisma } from "./prisma";
|
||||
import { verifyPassword } from "./auth";
|
||||
|
||||
export const authOptions = {
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
name: "Credentials",
|
||||
credentials: {
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Password", type: "password" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
if (!credentials?.email || !credentials?.password) return null;
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: credentials.email },
|
||||
});
|
||||
if (!user) return null;
|
||||
const valid = await verifyPassword(credentials.password, user.password);
|
||||
if (!valid) return null;
|
||||
return { id: user.id, email: user.email, role: user.role, establishmentId: user.establishmentId ?? undefined };
|
||||
},
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
async jwt({ token, user }: any) {
|
||||
if (user) {
|
||||
token.role = user.role;
|
||||
token.establishmentId = user.establishmentId;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }: any) {
|
||||
session.user.role = token.role;
|
||||
session.user.establishmentId = token.establishmentId;
|
||||
return session;
|
||||
},
|
||||
},
|
||||
pages: {
|
||||
signIn: "/login",
|
||||
},
|
||||
session: {
|
||||
strategy: "jwt" as const,
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import { prisma } from "./prisma";
|
||||
import bcrypt from "bcryptjs";
|
||||
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
return bcrypt.hash(password, 12);
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, hashed: string): Promise<boolean> {
|
||||
return bcrypt.compare(password, hashed);
|
||||
}
|
||||
|
||||
export function requireRole(user: { role: string }, ...allowed: string[]) {
|
||||
if (!allowed.includes(user.role)) {
|
||||
throw new Error("Forbidden");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
|
||||
|
||||
export const prisma = globalForPrisma.prisma || new PrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
||||
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { WebSocketServer, WebSocket } from "ws";
|
||||
import { prisma } from "./prisma";
|
||||
|
||||
interface NodeMessage {
|
||||
action: string;
|
||||
nodeId?: string;
|
||||
code?: string;
|
||||
instanceId?: string;
|
||||
type?: string;
|
||||
port?: number;
|
||||
composeConfig?: string;
|
||||
studentName?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
const nodes = new Map<string, WebSocket>();
|
||||
|
||||
export function initWebSocketServer(wss: WebSocketServer) {
|
||||
wss.on("connection", (ws: WebSocket) => {
|
||||
let nodeId: string | null = null;
|
||||
|
||||
ws.on("message", async (raw) => {
|
||||
try {
|
||||
const msg: NodeMessage = JSON.parse(raw.toString());
|
||||
|
||||
if (msg.action === "register" && msg.nodeId) {
|
||||
nodeId = msg.nodeId;
|
||||
nodes.set(nodeId, ws);
|
||||
await prisma.node.upsert({
|
||||
where: { id: nodeId },
|
||||
update: { status: "online", lastSeen: new Date() },
|
||||
create: { id: nodeId, status: "online", lastSeen: new Date() },
|
||||
});
|
||||
ws.send(JSON.stringify({ action: "registered" }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.action === "activate" && msg.code && msg.nodeId) {
|
||||
nodeId = msg.nodeId;
|
||||
const student = await prisma.student.findUnique({
|
||||
where: { activationCode: msg.code },
|
||||
});
|
||||
if (!student) {
|
||||
ws.send(JSON.stringify({ action: "activation_failed", error: "Invalid code" }));
|
||||
return;
|
||||
}
|
||||
await prisma.node.upsert({
|
||||
where: { id: nodeId },
|
||||
update: { studentId: student.id, status: "online", lastSeen: new Date() },
|
||||
create: { id: nodeId, studentId: student.id, status: "online", lastSeen: new Date() },
|
||||
});
|
||||
ws.send(JSON.stringify({ action: "activated", studentName: `${student.firstName} ${student.lastName}` }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.action === "heartbeat" && nodeId) {
|
||||
await prisma.node.upsert({
|
||||
where: { id: nodeId },
|
||||
update: { lastSeen: new Date() },
|
||||
create: { id: nodeId, status: "online", lastSeen: new Date() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.action === "instance_started" && msg.instanceId) {
|
||||
await prisma.instance.update({
|
||||
where: { id: msg.instanceId },
|
||||
data: { status: "running" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.action === "instance_error" && msg.instanceId) {
|
||||
await prisma.instance.update({
|
||||
where: { id: msg.instanceId },
|
||||
data: { status: "error" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("WS error:", err);
|
||||
}
|
||||
});
|
||||
|
||||
ws.on("close", async () => {
|
||||
if (nodeId) {
|
||||
nodes.delete(nodeId);
|
||||
await prisma.node.upsert({
|
||||
where: { id: nodeId },
|
||||
update: { status: "offline" },
|
||||
create: { id: nodeId, status: "offline" },
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function sendToNode(nodeId: string, message: object) {
|
||||
const ws = nodes.get(nodeId);
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify(message));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { withAuth } from "next-auth/middleware";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export default withAuth(
|
||||
function middleware(req) {
|
||||
const { pathname } = req.nextUrl;
|
||||
const role = req.nextauth.token?.role as string;
|
||||
|
||||
if (pathname.startsWith("/superadmin")) {
|
||||
if (role !== "superadmin") {
|
||||
return NextResponse.redirect(new URL("/dashboard", req.url));
|
||||
}
|
||||
}
|
||||
|
||||
if (pathname.startsWith("/dashboard")) {
|
||||
if (!role || (role !== "admin" && role !== "teacher" && role !== "superadmin")) {
|
||||
return NextResponse.redirect(new URL("/login", req.url));
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
},
|
||||
{
|
||||
callbacks: {
|
||||
authorized({ req, token }) {
|
||||
if (req.nextUrl.pathname.startsWith("/login")) return true;
|
||||
return !!token;
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export const config = {
|
||||
matcher: ["/dashboard/:path*", "/superadmin/:path*", "/api/protected/:path*"],
|
||||
};
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/types/routes.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
@@ -0,0 +1,4 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {}
|
||||
|
||||
module.exports = nextConfig
|
||||
Generated
+2687
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "edubox-server",
|
||||
"version": "2.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"postinstall": "prisma generate"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/client": "^5.0.0",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.0",
|
||||
"lucide-react": "^1.17.0",
|
||||
"next": "^16.0.0",
|
||||
"next-auth": "^4.24.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"tailwind-merge": "^2.2.0",
|
||||
"ws": "^8.16.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/node": "^20.0.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@types/ws": "^8.5.10",
|
||||
"autoprefixer": "^10.4.0",
|
||||
"postcss": "^8.4.0",
|
||||
"prisma": "^5.0.0",
|
||||
"tailwindcss": "^3.4.0",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"ts-node": "^10.9.0",
|
||||
"typescript": "^5.3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,97 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model Establishment {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
slug String @unique
|
||||
createdAt DateTime @default(now())
|
||||
subscription Subscription?
|
||||
users User[]
|
||||
classes Class[]
|
||||
templates Template[]
|
||||
}
|
||||
|
||||
model Subscription {
|
||||
id String @id @default(cuid())
|
||||
establishmentId String @unique
|
||||
establishment Establishment @relation(fields: [establishmentId], references: [id], onDelete: Cascade)
|
||||
plan String @default("trial")
|
||||
status String @default("active")
|
||||
expiresAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
email String @unique
|
||||
password String
|
||||
role String
|
||||
establishmentId String?
|
||||
establishment Establishment? @relation(fields: [establishmentId], references: [id], onDelete: SetNull)
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model Class {
|
||||
id String @id @default(cuid())
|
||||
establishmentId String
|
||||
establishment Establishment @relation(fields: [establishmentId], references: [id], onDelete: Cascade)
|
||||
name String
|
||||
level String
|
||||
createdAt DateTime @default(now())
|
||||
students Student[]
|
||||
}
|
||||
|
||||
model Student {
|
||||
id String @id @default(cuid())
|
||||
classId String
|
||||
class Class @relation(fields: [classId], references: [id], onDelete: Cascade)
|
||||
firstName String
|
||||
lastName String
|
||||
email String
|
||||
activationCode String? @unique
|
||||
createdAt DateTime @default(now())
|
||||
nodes Node[]
|
||||
}
|
||||
|
||||
model Node {
|
||||
id String @id
|
||||
studentId String?
|
||||
student Student? @relation(fields: [studentId], references: [id], onDelete: SetNull)
|
||||
tailscaleIp String?
|
||||
status String @default("offline")
|
||||
lastSeen DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
instances Instance[]
|
||||
}
|
||||
|
||||
model Instance {
|
||||
id String @id @default(cuid())
|
||||
nodeId String
|
||||
node Node @relation(fields: [nodeId], references: [id], onDelete: Cascade)
|
||||
templateId String
|
||||
template Template @relation(fields: [templateId], references: [id], onDelete: Restrict)
|
||||
status String @default("stopped")
|
||||
port Int
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model Template {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
type String
|
||||
dockerImage String
|
||||
composeConfig String
|
||||
isPublic Boolean @default(true)
|
||||
establishmentId String?
|
||||
establishment Establishment? @relation(fields: [establishmentId], references: [id], onDelete: Cascade)
|
||||
createdBy String
|
||||
createdAt DateTime @default(now())
|
||||
instances Instance[]
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import bcrypt from "bcryptjs";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
const superadminEmail = process.env.SUPERADMIN_EMAIL || "admin@edudeploy.fr";
|
||||
const superadminPassword = process.env.SUPERADMIN_PASSWORD || "CHANGE_ME";
|
||||
|
||||
const hashedPassword = await bcrypt.hash(superadminPassword, 12);
|
||||
|
||||
await prisma.user.upsert({
|
||||
where: { email: superadminEmail },
|
||||
update: {},
|
||||
create: {
|
||||
email: superadminEmail,
|
||||
password: hashedPassword,
|
||||
role: "superadmin",
|
||||
},
|
||||
});
|
||||
|
||||
const templates = [
|
||||
{ name: "WordPress latest vierge", type: "wordpress", dockerImage: "wordpress:latest" },
|
||||
{ name: "WordPress 6.7 vierge", type: "wordpress", dockerImage: "wordpress:6.7" },
|
||||
{ name: "WordPress 6.4 vierge", type: "wordpress", dockerImage: "wordpress:6.4" },
|
||||
{ name: "PrestaShop latest vierge", type: "prestashop", dockerImage: "prestashop/prestashop:latest" },
|
||||
{ name: "PrestaShop 8.1 vierge", type: "prestashop", dockerImage: "prestashop/prestashop:8.1" },
|
||||
];
|
||||
|
||||
for (const t of templates) {
|
||||
const composeConfig = `services:
|
||||
app:
|
||||
image: ${t.dockerImage}
|
||||
ports:
|
||||
- "127.0.0.1:{PORT}:80"
|
||||
environment:
|
||||
INSTANCE_ID: {INSTANCE_ID}
|
||||
restart: unless-stopped
|
||||
`;
|
||||
await prisma.template.upsert({
|
||||
where: { id: `${t.type}-${t.dockerImage.replace(/[:\/]/g, "-")}` },
|
||||
update: {},
|
||||
create: {
|
||||
id: `${t.type}-${t.dockerImage.replace(/[:\/]/g, "-")}`,
|
||||
name: t.name,
|
||||
type: t.type,
|
||||
dockerImage: t.dockerImage,
|
||||
composeConfig,
|
||||
isPublic: true,
|
||||
createdBy: "system",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
console.log("Seed completed.");
|
||||
}
|
||||
|
||||
main()
|
||||
.then(async () => {
|
||||
await prisma.$disconnect();
|
||||
})
|
||||
.catch(async (e) => {
|
||||
console.error(e);
|
||||
await prisma.$disconnect();
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { Config } from "tailwindcss";
|
||||
|
||||
const config: Config = {
|
||||
darkMode: ["class"],
|
||||
content: [
|
||||
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
"./components/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
"./app/**/*.{js,ts,jsx,tsx,mdx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
border: "hsl(var(--border))",
|
||||
input: "hsl(var(--input))",
|
||||
ring: "hsl(var(--ring))",
|
||||
background: "hsl(var(--background))",
|
||||
foreground: "hsl(var(--foreground))",
|
||||
primary: {
|
||||
DEFAULT: "hsl(var(--primary))",
|
||||
foreground: "hsl(var(--primary-foreground))",
|
||||
},
|
||||
secondary: {
|
||||
DEFAULT: "hsl(var(--secondary))",
|
||||
foreground: "hsl(var(--secondary-foreground))",
|
||||
},
|
||||
destructive: {
|
||||
DEFAULT: "hsl(var(--destructive))",
|
||||
foreground: "hsl(var(--destructive-foreground))",
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: "hsl(var(--muted))",
|
||||
foreground: "hsl(var(--muted-foreground))",
|
||||
},
|
||||
accent: {
|
||||
DEFAULT: "hsl(var(--accent))",
|
||||
foreground: "hsl(var(--accent-foreground))",
|
||||
},
|
||||
popover: {
|
||||
DEFAULT: "hsl(var(--popover))",
|
||||
foreground: "hsl(var(--popover-foreground))",
|
||||
},
|
||||
card: {
|
||||
DEFAULT: "hsl(var(--card))",
|
||||
foreground: "hsl(var(--card-foreground))",
|
||||
},
|
||||
},
|
||||
borderRadius: {
|
||||
lg: "var(--radius)",
|
||||
md: "calc(var(--radius) - 2px)",
|
||||
sm: "calc(var(--radius) - 4px)",
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [require("tailwindcss-animate")],
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./*"
|
||||
]
|
||||
},
|
||||
"target": "ES2017"
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
Vendored
+26
@@ -0,0 +1,26 @@
|
||||
import "next-auth";
|
||||
|
||||
declare module "next-auth" {
|
||||
interface Session {
|
||||
user: {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
establishmentId?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
establishmentId?: string;
|
||||
}
|
||||
}
|
||||
|
||||
declare module "next-auth/jwt" {
|
||||
interface JWT {
|
||||
role?: string;
|
||||
establishmentId?: string;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user