63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
|
import fetchUserUsingAPI from "@/lib/validate-api";
|
||
|
import { db } from "@/lib/db"
|
||
|
import { NextResponse } from "next/server";
|
||
|
|
||
|
export async function POST(req: Request) {
|
||
|
try {
|
||
|
let { userId, label } = await req.json();
|
||
|
|
||
|
if (userId == null) {
|
||
|
const user = await fetchUserUsingAPI(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 {
|
||
|
let { id } = await req.json();
|
||
|
const user = await fetchUserUsingAPI(req);
|
||
|
if (!id || !user) {
|
||
|
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;
|
||
|
}
|