2024-01-04 16:57:32 -05:00
|
|
|
import fetchUserWithImpersonation from "@/lib/fetch-user-impersonation";
|
2023-12-30 05:56:40 -05:00
|
|
|
import { db } from "@/lib/db"
|
|
|
|
import { NextResponse } from "next/server";
|
|
|
|
|
|
|
|
export async function POST(req: Request) {
|
|
|
|
try {
|
2024-01-04 16:57:32 -05:00
|
|
|
const user = await fetchUserWithImpersonation(req)
|
|
|
|
if (!user) {
|
|
|
|
return new NextResponse("Unauthorized", { status: 401 });
|
|
|
|
}
|
|
|
|
|
2023-12-30 05:56:40 -05:00
|
|
|
let { userId, label } = await req.json();
|
|
|
|
|
|
|
|
if (userId == null) {
|
2024-01-04 16:57:32 -05:00
|
|
|
const user = await fetchUserWithImpersonation(req);
|
2023-12-30 05:56:40 -05:00
|
|
|
if (user != null) {
|
|
|
|
userId = user.id;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const id = generateToken()
|
|
|
|
const token = await db.apiKey.create({
|
2024-06-24 18:16:55 -04:00
|
|
|
data: {
|
|
|
|
id,
|
|
|
|
label,
|
|
|
|
userId: userId as string
|
|
|
|
}
|
2023-12-30 05:56:40 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
return NextResponse.json(token);
|
|
|
|
} catch (error) {
|
|
|
|
console.log("[TOKEN/POST]", error);
|
|
|
|
return new NextResponse("Internal Error", { status: 500});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function DELETE(req: Request) {
|
|
|
|
try {
|
2024-01-04 16:57:32 -05:00
|
|
|
const user = await fetchUserWithImpersonation(req)
|
|
|
|
if (!user) {
|
|
|
|
return new NextResponse("Unauthorized", { status: 401 });
|
|
|
|
}
|
|
|
|
|
2024-06-24 18:16:55 -04:00
|
|
|
const { id } = await req.json();
|
2024-01-04 16:57:32 -05:00
|
|
|
if (!id) {
|
2023-12-30 05:56:40 -05:00
|
|
|
return NextResponse.json(null)
|
|
|
|
}
|
|
|
|
|
|
|
|
const token = await db.apiKey.delete({
|
2024-06-24 18:16:55 -04:00
|
|
|
where: {
|
|
|
|
id,
|
|
|
|
userId: user?.id
|
|
|
|
}
|
2023-12-30 05:56:40 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
return NextResponse.json(token);
|
|
|
|
} catch (error) {
|
|
|
|
console.log("[TOKEN/DELETE]", error);
|
|
|
|
return new NextResponse("Internal Error", { status: 500});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-24 18:16:55 -04:00
|
|
|
function generateToken() {
|
|
|
|
let chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
|
|
|
|
let string_length = 32;
|
|
|
|
let randomstring = '';
|
|
|
|
for (let i = 0; i < string_length; i++) {
|
|
|
|
let rnum = Math.floor(Math.random() * chars.length);
|
2023-12-30 05:56:40 -05:00
|
|
|
randomstring += chars[rnum];
|
|
|
|
}
|
|
|
|
return randomstring;
|
|
|
|
}
|