hermes-web/app/api/token/route.ts

72 lines
1.9 KiB
TypeScript
Raw Normal View History

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({
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 });
}
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({
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});
}
}
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;
}