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) {
|
2024-08-25 17:35:46 -04:00
|
|
|
return NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { status: 401 });
|
2024-01-04 16:57:32 -05:00
|
|
|
}
|
|
|
|
|
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) {
|
2024-08-25 17:35:46 -04:00
|
|
|
return NextResponse.json({ message: 'Something went wrong.', error: error, value: null }, { status: 500 });
|
2023-12-30 05:56:40 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function DELETE(req: Request) {
|
|
|
|
try {
|
2024-01-04 16:57:32 -05:00
|
|
|
const user = await fetchUserWithImpersonation(req)
|
|
|
|
if (!user) {
|
2024-08-25 17:35:46 -04:00
|
|
|
return NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { status: 401 });
|
2024-01-04 16:57:32 -05:00
|
|
|
}
|
|
|
|
|
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) {
|
2024-08-25 17:35:46 -04:00
|
|
|
return NextResponse.json({ message: 'Something went wrong.', error: error, value: null }, { status: 500 });
|
2023-12-30 05:56:40 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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;
|
|
|
|
}
|