Added impersonation for admins

This commit is contained in:
Tom
2024-01-04 21:57:32 +00:00
parent 320c826684
commit 8f7f18e069
25 changed files with 494 additions and 131 deletions

View File

@ -0,0 +1,91 @@
import { db } from "@/lib/db"
import { NextResponse } from "next/server";
import fetchUser from "@/lib/fetch-user";
export async function GET(req: Request) {
try {
const user = await fetchUser(req)
if (!user || user.role != "ADMIN") {
return new NextResponse("Unauthorized", { status: 401 });
}
const impersonation = await db.impersonation.findFirst({
where: {
sourceId: user.id
}
});
return NextResponse.json(impersonation);
} catch (error) {
console.log("[AUTH/ACCOUNT/IMPERSONATION]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
export async function POST(req: Request) {
try {
const user = await fetchUser(req)
if (!user || user.role != "ADMIN") {
return new NextResponse("Unauthorized", { status: 401 });
}
const { targetId } = await req.json();
const impersonation = await db.impersonation.create({
data: {
sourceId: user.id,
targetId
}
});
return NextResponse.json(impersonation);
} catch (error) {
console.log("[AUTH/ACCOUNT/IMPERSONATION]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
export async function PUT(req: Request) {
try {
const user = await fetchUser(req)
if (!user || user.role != "ADMIN") {
return new NextResponse("Unauthorized", { status: 401 });
}
const { targetId } = await req.json();
const impersonation = await db.impersonation.update({
where: {
sourceId: user.id,
},
data: {
targetId
}
});
return NextResponse.json(impersonation);
} catch (error) {
console.log("[AUTH/ACCOUNT/IMPERSONATION]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
export async function DELETE(req: Request) {
try {
const user = await fetchUser(req)
if (!user || user.role != "ADMIN") {
return new NextResponse("Unauthorized", { status: 401 });
}
const impersonation = await db.impersonation.delete({
where: {
sourceId: user.id
}
});
return NextResponse.json(impersonation)
} catch (error) {
console.log("[AUTH/ACCOUNT/IMPERSONATION]", error);
return new NextResponse("Internal Error" + error, { status: 500 });
}
}

View File

@ -1,12 +1,12 @@
import { db } from "@/lib/db"
import { NextResponse } from "next/server";
import { auth } from "@/auth";
import fetchUserUsingAPI from "@/lib/validate-api";
import fetchUser from "@/lib/fetch-user";
export async function GET(req: Request) {
try {
return NextResponse.json(await fetchUserUsingAPI(req))
return NextResponse.json(await fetchUser(req))
} catch (error) {
console.log("[ACCOUNT]", error);
return new NextResponse("Internal Error", { status: 500 });