feat(agent): v0.3.5 Windows inbound forwarding, UI actions, lifecycle
- Configure tailscale serve automatically for each instance on Windows userspace networking. - Add local UI buttons: start/stop/reset/delete instances (stop/start preserve volumes). - Clean shutdown: stop tailscaled and instances, notify server with instance_stopped. - Restart tailscaled on agent boot using persisted state when pre-auth key is absent. - Sync instance stopped/deleted status to dashboard (server/lib/websocket.ts). - Security: include prior authz/scoping changes across API routes, ephemeral pre-auth keys, ACL policy, internal API key. - Update SUIVI_VPN_ONDEMAND.md and docs/ONBOARDING_CLIENT.md. - Bump agent version to 0.3.5.
This commit is contained in:
@@ -1,13 +1,20 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { requireAuth, requireRole, getScopedEstablishmentId, forbidden } from "@/lib/api-auth";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const { searchParams } = new URL(req.url);
|
||||
const establishmentId = searchParams.get("establishmentId");
|
||||
if (!establishmentId) return NextResponse.json({ error: "Missing establishmentId" }, { status: 400 });
|
||||
const requestedId = searchParams.get("establishmentId");
|
||||
const establishmentId = getScopedEstablishmentId(user, requestedId);
|
||||
if (establishmentId instanceof NextResponse) return establishmentId;
|
||||
|
||||
const where = establishmentId ? { establishmentId } : {};
|
||||
|
||||
const classes = await prisma.class.findMany({
|
||||
where: { establishmentId },
|
||||
where,
|
||||
include: { _count: { select: { students: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
@@ -15,8 +22,19 @@ export async function GET(req: NextRequest) {
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const denied = requireRole(user, "superadmin", "admin");
|
||||
if (denied) return denied;
|
||||
|
||||
const body = await req.json();
|
||||
const { establishmentId, name, level } = body;
|
||||
const requestedId = body.establishmentId;
|
||||
const establishmentId = getScopedEstablishmentId(user, requestedId);
|
||||
if (establishmentId instanceof NextResponse) return establishmentId;
|
||||
if (!establishmentId) return forbidden();
|
||||
|
||||
const { name, level } = body;
|
||||
const cls = await prisma.class.create({
|
||||
data: { establishmentId, name, level },
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
const AGENT_VERSION = "0.3.0";
|
||||
const AGENT_VERSION = "0.3.4";
|
||||
const AGENT_BIN_NAME = "studioE5-agent";
|
||||
|
||||
export async function GET() {
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { hashPassword } from "@/lib/auth";
|
||||
import { requireAuth, requireRole } from "@/lib/api-auth";
|
||||
|
||||
export async function GET() {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const where = user.role === "superadmin" ? {} : { id: user.establishmentId };
|
||||
const establishments = await prisma.establishment.findMany({
|
||||
where,
|
||||
include: { subscription: true, _count: { select: { users: true, classes: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
@@ -11,6 +17,12 @@ export async function GET() {
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const denied = requireRole(user, "superadmin");
|
||||
if (denied) return denied;
|
||||
|
||||
const body = await req.json();
|
||||
const { name, slug, adminEmail, adminPassword } = body;
|
||||
|
||||
|
||||
@@ -1,16 +1,54 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { sendToNode } from "@/lib/websocket";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
|
||||
async function requireAuth() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) return null;
|
||||
return session.user as { id: string; email: string; role: string; establishmentId?: string };
|
||||
}
|
||||
|
||||
function userCanAccessNode(user: { role: string; establishmentId?: string }, node: any) {
|
||||
if (user.role === "superadmin") return true;
|
||||
const establishmentId = node?.student?.class?.establishmentId;
|
||||
return establishmentId && establishmentId === user.establishmentId;
|
||||
}
|
||||
|
||||
function userCanAccessInstance(user: { role: string; establishmentId?: string }, instance: any) {
|
||||
if (user.role === "superadmin") return true;
|
||||
const establishmentId = instance?.node?.student?.class?.establishmentId;
|
||||
return establishmentId && establishmentId === user.establishmentId;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const { searchParams } = new URL(req.url);
|
||||
const nodeId = searchParams.get("nodeId");
|
||||
const establishmentId = searchParams.get("establishmentId");
|
||||
const establishmentIdParam = searchParams.get("establishmentId");
|
||||
|
||||
let where: any = {};
|
||||
if (nodeId) where.nodeId = nodeId;
|
||||
if (establishmentId) {
|
||||
const classes = await prisma.class.findMany({ where: { establishmentId }, select: { id: true } });
|
||||
|
||||
if (user.role !== "superadmin") {
|
||||
const classes = await prisma.class.findMany({
|
||||
where: { establishmentId: user.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) };
|
||||
} else if (establishmentIdParam) {
|
||||
const classes = await prisma.class.findMany({ where: { establishmentId: establishmentIdParam }, 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) };
|
||||
@@ -39,12 +77,8 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
const enriched = instances.map((inst) => {
|
||||
const domain = inst.node.student?.class.establishment?.domain;
|
||||
const publicUrl = domain
|
||||
? `https://${inst.id}.${domain}`
|
||||
: null;
|
||||
const localUrl = inst.node.tailscaleIp
|
||||
? `http://${inst.node.tailscaleIp}:${inst.port}`
|
||||
: null;
|
||||
const publicUrl = domain ? `https://${inst.id}.${domain}` : null;
|
||||
const localUrl = inst.node.tailscaleIp ? `http://${inst.node.tailscaleIp}:${inst.port}` : null;
|
||||
return {
|
||||
...inst,
|
||||
publicUrl,
|
||||
@@ -56,22 +90,32 @@ export async function GET(req: NextRequest) {
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const body = await req.json();
|
||||
const { nodeId, templateId, port } = body;
|
||||
if (!nodeId || !templateId) {
|
||||
return NextResponse.json({ error: "Missing nodeId or templateId" }, { status: 400 });
|
||||
}
|
||||
|
||||
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 node = await prisma.node.findUnique({
|
||||
where: { id: nodeId },
|
||||
include: { student: { include: { class: { include: { establishment: true } } } } },
|
||||
});
|
||||
if (!node) return NextResponse.json({ error: "Node not found" }, { status: 404 });
|
||||
if (!userCanAccessNode(user, node)) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
const domain = node?.student?.class.establishment?.domain;
|
||||
const instance = await prisma.instance.create({
|
||||
data: { nodeId, templateId, port: port || 8080, status: "stopped" },
|
||||
});
|
||||
|
||||
const domain = node.student?.class.establishment?.domain;
|
||||
const publicDomain = domain ? `${instance.id}.${domain}` : "localhost";
|
||||
const publicUrl = domain ? `https://${publicDomain}` : null;
|
||||
const sent = sendToNode(nodeId, {
|
||||
@@ -94,14 +138,28 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
export async function PATCH(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const body = await req.json();
|
||||
const { id, action } = body;
|
||||
const instance = await prisma.instance.findUnique({ where: { id }, include: { template: true, node: { include: { student: { include: { class: { include: { establishment: true } } } } } } } });
|
||||
if (!id || !action) {
|
||||
return NextResponse.json({ error: "Missing id or action" }, { status: 400 });
|
||||
}
|
||||
|
||||
const instance = await prisma.instance.findUnique({
|
||||
where: { id },
|
||||
include: { template: true, node: { include: { student: { include: { class: { include: { establishment: true } } } } } } },
|
||||
});
|
||||
if (!instance) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
if (!userCanAccessInstance(user, instance)) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
const domain = instance.node.student?.class.establishment?.domain;
|
||||
const publicDomain = domain ? `${instance.id}.${domain}` : "localhost";
|
||||
const publicUrl = domain ? `https://${publicDomain}` : null;
|
||||
|
||||
if (action === "stop") {
|
||||
sendToNode(instance.nodeId, { action: "delete", instanceId: instance.id });
|
||||
await prisma.instance.update({ where: { id }, data: { status: "stopped" } });
|
||||
@@ -131,16 +189,30 @@ export async function PATCH(req: NextRequest) {
|
||||
.replace(/{PUBLIC_DOMAIN}/g, "localhost"),
|
||||
});
|
||||
if (!sent) await prisma.instance.update({ where: { id }, data: { status: "error" } });
|
||||
} else {
|
||||
return NextResponse.json({ error: "Invalid action" }, { status: 400 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
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 } });
|
||||
|
||||
const instance = await prisma.instance.findUnique({
|
||||
where: { id },
|
||||
include: { node: { include: { student: { include: { class: { include: { establishment: true } } } } } } },
|
||||
});
|
||||
if (!instance) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
if (!userCanAccessInstance(user, instance)) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
if (instance) sendToNode(instance.nodeId, { action: "delete", instanceId: instance.id });
|
||||
await prisma.instance.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true });
|
||||
|
||||
@@ -1,7 +1,22 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { sendToNode } from "@/lib/websocket";
|
||||
|
||||
function getBearerToken(req: NextRequest): string | null {
|
||||
const auth = req.headers.get("authorization") || "";
|
||||
const match = auth.match(/^Bearer\s+(\S+)$/i);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const apiKey = process.env.INTERNAL_API_KEY;
|
||||
if (!apiKey) {
|
||||
return NextResponse.json({ error: "Internal API key not configured" }, { status: 500 });
|
||||
}
|
||||
const token = getBearerToken(req);
|
||||
if (!token || token !== apiKey) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
const { nodeId, message } = body;
|
||||
if (!nodeId || !message) {
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { requireAuth, getScopedEstablishmentId, forbidden } from "@/lib/api-auth";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const { searchParams } = new URL(req.url);
|
||||
const establishmentId = searchParams.get("establishmentId");
|
||||
const requestedId = searchParams.get("establishmentId");
|
||||
const establishmentId = getScopedEstablishmentId(user, requestedId);
|
||||
if (establishmentId instanceof NextResponse) return establishmentId;
|
||||
|
||||
let where: any = {};
|
||||
if (establishmentId) {
|
||||
|
||||
@@ -1,7 +1,22 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
function getBearerToken(req: NextRequest): string | null {
|
||||
const auth = req.headers.get("authorization") || "";
|
||||
const match = auth.match(/^Bearer\s+(\S+)$/i);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const apiKey = process.env.INTERNAL_API_KEY;
|
||||
if (!apiKey) {
|
||||
return NextResponse.json({ error: "Internal API key not configured" }, { status: 500 });
|
||||
}
|
||||
const token = getBearerToken(req);
|
||||
if (!token || token !== apiKey) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(req.url);
|
||||
const subdomain = searchParams.get("subdomain");
|
||||
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
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;
|
||||
}
|
||||
import { generateUniqueActivationCode } from "@/lib/activation";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
@@ -31,13 +25,15 @@ export async function GET(req: NextRequest) {
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json();
|
||||
const { classId, firstName, lastName, email } = body;
|
||||
const { code, expiresAt } = await generateUniqueActivationCode();
|
||||
const student = await prisma.student.create({
|
||||
data: {
|
||||
classId,
|
||||
firstName,
|
||||
lastName,
|
||||
email,
|
||||
activationCode: generateCode(),
|
||||
activationCode: code,
|
||||
activationCodeExpiresAt: expiresAt,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(student, { status: 201 });
|
||||
|
||||
@@ -1,25 +1,57 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { requireAuth, requireRole, forbidden } from "@/lib/api-auth";
|
||||
|
||||
function templateAccessWhere(user: { role: string; establishmentId?: string }, establishmentId?: string | null) {
|
||||
if (user.role === "superadmin" && establishmentId) {
|
||||
return { OR: [{ isPublic: true }, { establishmentId }] };
|
||||
}
|
||||
if (user.establishmentId) {
|
||||
return { OR: [{ isPublic: true }, { establishmentId: user.establishmentId }] };
|
||||
}
|
||||
return { isPublic: true };
|
||||
}
|
||||
|
||||
async function canManageTemplate(user: { role: string; establishmentId?: string }, id: string) {
|
||||
if (user.role === "superadmin") return true;
|
||||
const template = await prisma.template.findUnique({ where: { id } });
|
||||
if (!template) return false;
|
||||
return template.establishmentId === user.establishmentId;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const { searchParams } = new URL(req.url);
|
||||
const establishmentId = searchParams.get("establishmentId");
|
||||
const requestedEst = searchParams.get("establishmentId");
|
||||
|
||||
const where = user.role === "superadmin" && !requestedEst ? {} : templateAccessWhere(user, requestedEst);
|
||||
|
||||
const templates = await prisma.template.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ isPublic: true },
|
||||
...(establishmentId ? [{ establishmentId }] : []),
|
||||
],
|
||||
},
|
||||
where,
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
return NextResponse.json(templates);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const denied = requireRole(user, "superadmin", "admin");
|
||||
if (denied) return denied;
|
||||
|
||||
const body = await req.json();
|
||||
const { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy } = body;
|
||||
let { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy } = body;
|
||||
|
||||
if (user.role !== "superadmin") {
|
||||
if (establishmentId && establishmentId !== user.establishmentId) {
|
||||
return forbidden();
|
||||
}
|
||||
establishmentId = user.establishmentId;
|
||||
}
|
||||
|
||||
const template = await prisma.template.create({
|
||||
data: { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy },
|
||||
});
|
||||
@@ -27,16 +59,39 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
export async function PUT(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const denied = requireRole(user, "superadmin", "admin");
|
||||
if (denied) return denied;
|
||||
|
||||
const body = await req.json();
|
||||
const { id, ...data } = body;
|
||||
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
|
||||
|
||||
if (!(await canManageTemplate(user, id))) return forbidden();
|
||||
|
||||
if (user.role !== "superadmin" && data.establishmentId && data.establishmentId !== user.establishmentId) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
const template = await prisma.template.update({ where: { id }, data });
|
||||
return NextResponse.json(template);
|
||||
}
|
||||
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const denied = requireRole(user, "superadmin", "admin");
|
||||
if (denied) return denied;
|
||||
|
||||
const { searchParams } = new URL(req.url);
|
||||
const id = searchParams.get("id");
|
||||
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
|
||||
|
||||
if (!(await canManageTemplate(user, id))) return forbidden();
|
||||
|
||||
await prisma.template.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
@@ -1,14 +1,25 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { hashPassword } from "@/lib/auth";
|
||||
import { requireAuth, requireRole, forbidden } from "@/lib/api-auth";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const { searchParams } = new URL(req.url);
|
||||
const establishmentId = searchParams.get("establishmentId");
|
||||
const role = searchParams.get("role");
|
||||
|
||||
if (user.role !== "superadmin") {
|
||||
if (establishmentId && establishmentId !== user.establishmentId) {
|
||||
return forbidden();
|
||||
}
|
||||
}
|
||||
|
||||
const where: any = {};
|
||||
if (establishmentId) where.establishmentId = establishmentId;
|
||||
else if (user.role !== "superadmin") where.establishmentId = user.establishmentId;
|
||||
if (role) where.role = role;
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
@@ -19,23 +30,56 @@ export async function GET(req: NextRequest) {
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const denied = requireRole(user, "superadmin", "admin");
|
||||
if (denied) return denied;
|
||||
|
||||
const body = await req.json();
|
||||
const { email, password, role, establishmentId } = body;
|
||||
const user = await prisma.user.create({
|
||||
|
||||
if (!email || !password || !role) {
|
||||
return NextResponse.json({ error: "Missing email, password or role" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (user.role === "admin") {
|
||||
if (role === "superadmin") return forbidden();
|
||||
if (establishmentId && establishmentId !== user.establishmentId) return forbidden();
|
||||
}
|
||||
|
||||
const finalEstablishmentId = user.role === "superadmin" ? establishmentId : user.establishmentId;
|
||||
|
||||
const newUser = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
password: await hashPassword(password),
|
||||
role,
|
||||
establishmentId,
|
||||
establishmentId: finalEstablishmentId,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(user, { status: 201 });
|
||||
return NextResponse.json(newUser, { status: 201 });
|
||||
}
|
||||
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const user = await requireAuth();
|
||||
if (user instanceof NextResponse) return user;
|
||||
|
||||
const denied = requireRole(user, "superadmin", "admin");
|
||||
if (denied) return denied;
|
||||
|
||||
const { searchParams } = new URL(req.url);
|
||||
const id = searchParams.get("id");
|
||||
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
|
||||
|
||||
const target = await prisma.user.findUnique({ where: { id } });
|
||||
if (!target) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
if (user.role === "admin") {
|
||||
if (target.role === "superadmin") return forbidden();
|
||||
if (target.establishmentId !== user.establishmentId) return forbidden();
|
||||
}
|
||||
|
||||
await prisma.user.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
@@ -3,17 +3,9 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { generateUniqueActivationCode } from "@/lib/activation";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
function generateCode(): string {
|
||||
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
let code = "";
|
||||
for (let i = 0; i < 6; i++) {
|
||||
code += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
export async function deleteStudent(formData: FormData) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session?.user) redirect("/login");
|
||||
@@ -54,9 +46,10 @@ export async function generateActivationCodeAction(formData: FormData) {
|
||||
|
||||
if (!student) return;
|
||||
|
||||
const { code, expiresAt } = await generateUniqueActivationCode();
|
||||
await prisma.student.update({
|
||||
where: { id },
|
||||
data: { activationCode: generateCode() },
|
||||
data: { activationCode: code, activationCodeExpiresAt: expiresAt },
|
||||
});
|
||||
|
||||
redirect(`/dashboard/students/${id}`);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "@/lib/auth-config";
|
||||
import { generateUniqueActivationCode } from "@/lib/activation";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -17,15 +18,6 @@ const schema = z.object({
|
||||
classId: z.string().min(1),
|
||||
});
|
||||
|
||||
function generateActivationCode(): string {
|
||||
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
let code = "";
|
||||
for (let i = 0; i < 6; i++) {
|
||||
code += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
async function createStudent(formData: FormData) {
|
||||
"use server";
|
||||
const session = await getServerSession(authOptions);
|
||||
@@ -35,13 +27,15 @@ async function createStudent(formData: FormData) {
|
||||
const parsed = schema.safeParse(Object.fromEntries(formData));
|
||||
if (!parsed.success) return;
|
||||
|
||||
const { code, expiresAt } = await generateUniqueActivationCode();
|
||||
await prisma.student.create({
|
||||
data: {
|
||||
firstName: parsed.data.firstName,
|
||||
lastName: parsed.data.lastName,
|
||||
email: parsed.data.email,
|
||||
classId: parsed.data.classId,
|
||||
activationCode: generateActivationCode(),
|
||||
activationCode: code,
|
||||
activationCodeExpiresAt: expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user