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

72 lines
1.9 KiB
TypeScript

import fetchUserWithImpersonation from "@/lib/fetch-user-impersonation";
import { db } from "@/lib/db"
import { NextResponse } from "next/server";
export async function POST(req: Request) {
try {
const user = await fetchUserWithImpersonation(req)
if (!user) {
return new NextResponse("Unauthorized", { status: 401 });
}
let { userId, label } = await req.json();
if (userId == null) {
const user = await fetchUserWithImpersonation(req);
if (user != null) {
userId = user.id;
}
}
const id = generateToken()
const token = await db.apiKey.create({
data: {
id,
label,
userId: userId as string
}
});
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 {
const user = await fetchUserWithImpersonation(req)
if (!user) {
return new NextResponse("Unauthorized", { status: 401 });
}
let { id } = await req.json();
if (!id) {
return NextResponse.json(null)
}
const token = await db.apiKey.delete({
where: {
id,
userId: user?.id
}
});
return NextResponse.json(token);
} catch (error) {
console.log("[TOKEN/DELETE]", error);
return new NextResponse("Internal Error", { status: 500});
}
}
export function generateToken() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 32;
var randomstring = '';
for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars[rnum];
}
return randomstring;
}