import { NextApiRequest } from "next"; import * as ldap from "@/ldap"; import prisma from "@/prisma"; type RequestBody = { username: string; displayName: string; email: string; password: string; avatarBase64: string | null; }; export async function POST(request: Request) { const authorization = request.headers .get("authorization") ?.replace("Bearer ", ""); if (authorization == null) return new Response(null, { status: 401 }); const user = await prisma.authTicket.findFirst({ where: { ticket: authorization } }); if (user == null) return new Response(null, { status: 401 }); const { username, displayName, email, password, avatarBase64 } = (await request.json()) as RequestBody; // runtime type verification when :pleading: if ( username == undefined || typeof username !== "string" || displayName == undefined || typeof displayName !== "string" || email == undefined || typeof email !== "string" || password == undefined || typeof password !== "string" ) { return new Response( JSON.stringify({ ok: false, error: "invalidBody" }), { status: 400 } ); } if (password.length < 12) { return new Response( JSON.stringify({ ok: false, error: "passwordShort" }), { status: 400 } ); } let avatarBuf: Buffer | undefined; if (avatarBase64 !== null && typeof avatarBase64 === "string") { avatarBuf = Buffer.from(avatarBase64, "base64"); if (avatarBuf.length > 1_000_000) { return new Response( JSON.stringify({ ok: false, error: "avatarBig" }), { status: 400 } ); } } const users = await ldap.getUsers(); for (const user of users) { if (user.id.toLowerCase() === username.toLowerCase()) { return new Response( JSON.stringify({ ok: false, error: "usernameTaken" }), { status: 400 } ); } } await ldap.createUser(username, displayName, email, avatarBuf); await ldap.setPassword(username, password); await prisma.authTicket.update({ where: { id: user.id }, data: { username: username } }); return new Response( JSON.stringify({ ok: true }), { status: 201 } ); }