21 lines
1.4 KiB
TypeScript
21 lines
1.4 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { getSession } from "@/lib/auth";
|
|
import { db, objectId } from "@/lib/db";
|
|
import { isSameOrigin } from "@/lib/validation";
|
|
|
|
export async function PUT(request: Request, context: { params: Promise<{ id: string }> }) {
|
|
if (!isSameOrigin(request)) return NextResponse.json({ error: "Invalid request origin." }, { status: 403 });
|
|
const session = await getSession();
|
|
if (!session || session.role !== "admin") return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
const { id } = await context.params;
|
|
if (id === session.id) return NextResponse.json({ error: "You cannot change your own administrator role." }, { status: 400 });
|
|
const userId = objectId(id); const organizationId = objectId(session.organizationId);
|
|
if (!userId || !organizationId) return NextResponse.json({ error: "Invalid user." }, { status: 400 });
|
|
const body = await request.json();
|
|
const role = body.role === "admin" ? "admin" : body.role === "member" ? "member" : null;
|
|
if (!role) return NextResponse.json({ error: "Invalid role." }, { status: 400 });
|
|
const result = await (await db()).collection("users").updateOne({ _id: userId, organizationId }, { $set: { role, updatedAt: new Date() } });
|
|
if (!result.matchedCount) return NextResponse.json({ error: "User not found." }, { status: 404 });
|
|
return NextResponse.json({ ok: true, role });
|
|
}
|