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

70 lines
2.0 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 NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { 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) {
return NextResponse.json({ message: 'Something went wrong.', error: error, value: null }, { status: 500 });
}
}
export async function DELETE(req: Request) {
try {
const user = await fetchUserWithImpersonation(req)
if (!user) {
return NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { status: 401 });
}
const { 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) {
return NextResponse.json({ message: 'Something went wrong.', error: error, value: null }, { 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);
randomstring += chars[rnum];
}
return randomstring;
}