Integrate LiveKit SFU and harden booking workflow
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getPayload } from "payload";
|
||||
import config from "@payload-config";
|
||||
import { createLiveKitToken, getLiveKitClientUrl } from "@/lib/meeting/livekit";
|
||||
import { isMeetingParticipantKicked } from "@/lib/meeting/kicks";
|
||||
import { verifyMeetingToken } from "@/lib/meeting/token";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Args = { params: Promise<{ slug: string }> };
|
||||
|
||||
/** Exchanges the app's short-lived meeting credential for a LiveKit token. */
|
||||
export async function POST(request: Request, { params }: Args) {
|
||||
const { slug } = await params;
|
||||
const authorization = request.headers.get("authorization") ?? "";
|
||||
const appToken = authorization.startsWith("Bearer ") ? authorization.slice(7) : "";
|
||||
const meetingToken = verifyMeetingToken(appToken);
|
||||
if (!meetingToken || meetingToken.eventSlug !== slug) {
|
||||
return NextResponse.json({ error: "Die Meeting-Sitzung ist ungültig." }, { status: 401 });
|
||||
}
|
||||
if (isMeetingParticipantKicked(slug, meetingToken.participantId, meetingToken.clientId)) {
|
||||
return NextResponse.json({ error: "Du wurdest aus diesem Meeting entfernt." }, { status: 403 });
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await getPayload({ config });
|
||||
const { docs } = await payload.find({ collection: "events", where: { slug: { equals: slug } }, limit: 1 });
|
||||
if (!docs[0]?.isOnline) return NextResponse.json({ error: "Dieser Online-Termin wurde nicht gefunden." }, { status: 404 });
|
||||
|
||||
const participantToken = await createLiveKitToken({
|
||||
eventSlug: slug,
|
||||
participantId: meetingToken.participantId,
|
||||
name: meetingToken.name,
|
||||
role: meetingToken.role,
|
||||
clientId: meetingToken.clientId,
|
||||
});
|
||||
return NextResponse.json({ serverUrl: getLiveKitClientUrl(), participantToken });
|
||||
} catch (error) {
|
||||
console.error("meeting LiveKit connect failed", error);
|
||||
return NextResponse.json({ error: "Der Video-Server ist gerade nicht erreichbar." }, { status: 503 });
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,8 @@ import { getPayload } from "payload";
|
||||
import config from "@payload-config";
|
||||
import { createMeetingToken } from "@/lib/meeting/token";
|
||||
import { canJoinMeeting, combineDateAndTime, getMeetingStatus } from "@/lib/meeting/status";
|
||||
import { getIceServers } from "@/lib/meeting/iceServers";
|
||||
import { createLiveKitToken, getLiveKitClientUrl } from "@/lib/meeting/livekit";
|
||||
import { isMeetingParticipantKicked } from "@/lib/meeting/kicks";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -30,9 +31,12 @@ export async function POST(request: Request, { params }: Args) {
|
||||
const name = typeof body.name === "string" ? body.name.trim() : "";
|
||||
const password = typeof body.password === "string" ? body.password.trim() : "";
|
||||
const clientId = typeof body.clientId === "string" ? body.clientId.trim() : undefined;
|
||||
if (!name) {
|
||||
if (!name || name.length > 120) {
|
||||
return NextResponse.json({ error: "Bitte gib deinen Namen ein." }, { status: 400 });
|
||||
}
|
||||
if (password.length > 200) {
|
||||
return NextResponse.json({ error: "Das Meeting-Passwort ist ungültig." }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await getPayload({ config });
|
||||
@@ -50,7 +54,7 @@ export async function POST(request: Request, { params }: Args) {
|
||||
const { user } = await payload.auth({ headers: request.headers });
|
||||
// Must check the collection, not just presence — a logged-in customer
|
||||
// (collection "customers") must never be treated as host.
|
||||
const isHost = user?.collection === "users";
|
||||
const isHost = user?.collection === "users" && user.role === "admin";
|
||||
|
||||
if (!isHost) {
|
||||
if (!password) {
|
||||
@@ -88,7 +92,18 @@ export async function POST(request: Request, { params }: Args) {
|
||||
role: isHost ? "host" : "participant",
|
||||
// Only meaningful for participants — a host authenticates via a real
|
||||
// session already, so there's no need to anchor a kick to it (and
|
||||
// hosts can't be kicked in the first place, see signalingServer.ts).
|
||||
// hosts can't be kicked in the first place.
|
||||
clientId: isHost ? undefined : clientId,
|
||||
});
|
||||
|
||||
if (!isHost && isMeetingParticipantKicked(slug, participantId, clientId)) {
|
||||
return NextResponse.json({ error: "Du wurdest aus diesem Meeting entfernt." }, { status: 403 });
|
||||
}
|
||||
const participantToken = await createLiveKitToken({
|
||||
eventSlug: slug,
|
||||
participantId,
|
||||
name,
|
||||
role: isHost ? "host" : "participant",
|
||||
clientId: isHost ? undefined : clientId,
|
||||
});
|
||||
|
||||
@@ -97,7 +112,8 @@ export async function POST(request: Request, { params }: Args) {
|
||||
participantId,
|
||||
role: isHost ? "host" : "participant",
|
||||
eventTitle: event.title,
|
||||
iceServers: getIceServers(),
|
||||
participantToken,
|
||||
serverUrl: getLiveKitClientUrl(),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("meeting join failed", error);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getLiveKitRoomName, getLiveKitRoomService } from "@/lib/meeting/livekit";
|
||||
import { markMeetingParticipantKicked } from "@/lib/meeting/kicks";
|
||||
import { verifyMeetingToken } from "@/lib/meeting/token";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Args = { params: Promise<{ slug: string }> };
|
||||
|
||||
export async function POST(request: Request, { params }: Args) {
|
||||
const { slug } = await params;
|
||||
const authorization = request.headers.get("authorization") ?? "";
|
||||
const appToken = authorization.startsWith("Bearer ") ? authorization.slice(7) : "";
|
||||
const host = verifyMeetingToken(appToken);
|
||||
if (!host || host.eventSlug !== slug || host.role !== "host") {
|
||||
return NextResponse.json({ error: "Nur der Host darf Teilnehmer entfernen." }, { status: 403 });
|
||||
}
|
||||
|
||||
let body: { participantId?: unknown };
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Ungültige Anfrage." }, { status: 400 });
|
||||
}
|
||||
const participantId = typeof body.participantId === "string" ? body.participantId.trim() : "";
|
||||
if (!participantId || participantId.length > 100 || participantId === host.participantId) {
|
||||
return NextResponse.json({ error: "Ungültiger Teilnehmer." }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const roomService = getLiveKitRoomService();
|
||||
const room = getLiveKitRoomName(slug);
|
||||
const participant = (await roomService.listParticipants(room)).find((item) => item.identity === participantId);
|
||||
if (!participant) return NextResponse.json({ error: "Teilnehmer nicht gefunden." }, { status: 404 });
|
||||
|
||||
let clientId: string | undefined;
|
||||
try {
|
||||
const metadata = JSON.parse(participant.metadata || "{}") as { clientId?: unknown };
|
||||
if (typeof metadata.clientId === "string" && metadata.clientId.length <= 100) clientId = metadata.clientId;
|
||||
} catch {
|
||||
// Metadata is optional; the participant identity is still revoked below.
|
||||
}
|
||||
markMeetingParticipantKicked(slug, participantId, clientId);
|
||||
await roomService.removeParticipant(room, participantId);
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (error) {
|
||||
console.error("meeting participant kick failed", error);
|
||||
return NextResponse.json({ error: "Der Teilnehmer konnte nicht entfernt werden." }, { status: 503 });
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,40 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getPayload } from "payload";
|
||||
import config from "@payload-config";
|
||||
import { checkRateLimit, getClientIp } from "@/lib/auth/rateLimit";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Registration capacity is checked before the insert. Serialize registrations
|
||||
// for the same event so two simultaneous requests cannot both observe the
|
||||
// same free seat in this single-process deployment.
|
||||
const registrationLocks = new Map<string, Promise<void>>();
|
||||
|
||||
async function withEventRegistrationLock<T>(eventId: string, action: () => Promise<T>): Promise<T> {
|
||||
const previous = registrationLocks.get(eventId) ?? Promise.resolve();
|
||||
let release!: () => void;
|
||||
const current = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
registrationLocks.set(eventId, current);
|
||||
await previous;
|
||||
try {
|
||||
return await action();
|
||||
} finally {
|
||||
release();
|
||||
if (registrationLocks.get(eventId) === current) registrationLocks.delete(eventId);
|
||||
}
|
||||
}
|
||||
|
||||
type Args = { params: Promise<{ slug: string }> };
|
||||
|
||||
export async function POST(request: Request, { params }: Args) {
|
||||
const { slug } = await params;
|
||||
|
||||
if (!checkRateLimit(`event-registration:ip:${getClientIp(request)}`, { max: 20, windowMs: 60 * 60 * 1000 })) {
|
||||
return NextResponse.json({ error: "Zu viele Anmeldungen. Bitte versuche es später erneut." }, { status: 429 });
|
||||
}
|
||||
|
||||
let body: { name?: unknown; email?: unknown };
|
||||
try {
|
||||
body = await request.json();
|
||||
@@ -17,8 +43,8 @@ export async function POST(request: Request, { params }: Args) {
|
||||
}
|
||||
|
||||
const name = typeof body.name === "string" ? body.name.trim() : "";
|
||||
const email = typeof body.email === "string" ? body.email.trim() : "";
|
||||
if (!name || !email || !email.includes("@")) {
|
||||
const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
|
||||
if (!name || name.length > 120 || !email || email.length > 254 || !email.includes("@")) {
|
||||
return NextResponse.json({ error: "Bitte gib deinen Namen und eine gültige E-Mail-Adresse an." }, { status: 400 });
|
||||
}
|
||||
|
||||
@@ -31,41 +57,46 @@ export async function POST(request: Request, { params }: Args) {
|
||||
limit: 1,
|
||||
});
|
||||
const event = docs[0];
|
||||
if (!event) {
|
||||
if (!event || event._status !== "published" || !event.registrationRequired) {
|
||||
return NextResponse.json({ error: "Dieser Termin wurde nicht gefunden." }, { status: 404 });
|
||||
}
|
||||
|
||||
const { docs: existingForEmail } = await payload.find({
|
||||
collection: "event-registrations",
|
||||
where: {
|
||||
and: [
|
||||
{ event: { equals: event.id } },
|
||||
{ email: { equals: email } },
|
||||
{ status: { equals: "registered" } },
|
||||
],
|
||||
},
|
||||
limit: 1,
|
||||
});
|
||||
if (existingForEmail[0]) {
|
||||
return NextResponse.json({ ok: true, alreadyRegistered: true });
|
||||
if (!checkRateLimit(`event-registration:email:${event.id}:${email}`, { max: 3, windowMs: 60 * 60 * 1000 })) {
|
||||
return NextResponse.json({ error: "Zu viele Anmeldeversuche für diese Adresse. Bitte versuche es später erneut." }, { status: 429 });
|
||||
}
|
||||
|
||||
if (event.maxParticipants) {
|
||||
const { totalDocs } = await payload.count({
|
||||
return await withEventRegistrationLock(String(event.id), async () => {
|
||||
const { docs: existingForEmail } = await payload.find({
|
||||
collection: "event-registrations",
|
||||
where: { and: [{ event: { equals: event.id } }, { status: { equals: "registered" } }] },
|
||||
where: {
|
||||
and: [
|
||||
{ event: { equals: event.id } },
|
||||
{ email: { equals: email } },
|
||||
{ status: { equals: "registered" } },
|
||||
],
|
||||
},
|
||||
limit: 1,
|
||||
});
|
||||
if (totalDocs >= event.maxParticipants) {
|
||||
return NextResponse.json({ error: "Dieser Termin ist bereits ausgebucht." }, { status: 409 });
|
||||
if (existingForEmail[0]) {
|
||||
return NextResponse.json({ ok: true, alreadyRegistered: true });
|
||||
}
|
||||
}
|
||||
|
||||
await payload.create({
|
||||
collection: "event-registrations",
|
||||
data: { event: event.id, name, email, status: "registered" },
|
||||
if (event.maxParticipants) {
|
||||
const { totalDocs } = await payload.count({
|
||||
collection: "event-registrations",
|
||||
where: { and: [{ event: { equals: event.id } }, { status: { equals: "registered" } }] },
|
||||
});
|
||||
if (totalDocs >= event.maxParticipants) {
|
||||
return NextResponse.json({ error: "Dieser Termin ist bereits ausgebucht." }, { status: 409 });
|
||||
}
|
||||
}
|
||||
|
||||
await payload.create({
|
||||
collection: "event-registrations",
|
||||
data: { event: event.id, name, email, status: "registered" },
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (error) {
|
||||
console.error("event registration failed", error);
|
||||
return NextResponse.json({ error: "Die Anmeldung ist gerade nicht möglich. Bitte versuche es später erneut." }, { status: 500 });
|
||||
|
||||
Reference in New Issue
Block a user