next/server/api/auth/register.post.ts

46 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-10-01 19:25:40 -04:00
import { weirdToNormalChars as w2nc } from "weird-to-normal-chars";
import crypto from "crypto";
import { usernameRegex } from "~/lib/server/constants";
import { User } from "~/models/user";
import mongoose from "mongoose";
import captcha from "~/lib/server/middlewareButNotReally/captcha";
export default eventHandler(async (event) => {
const body = await readBody(event);
console.log(typeof body);
console.log(body);
if (!body.username || !body.password || !body.email) {
throw createError({ statusCode: 400 });
}
await captcha(event);
console.log("fields exist");
const user = await User.findOne({
$or: [
{ username: usernameRegex(body.username) },
{ email: (body.email as string).toLowerCase() },
],
});
console.log("after f0", user);
if (user)
throw createError({
statusCode: 400,
message: "A user with that username or email already exists.",
});
let nuser = new User({
email: body.email.toLowerCase(),
username: w2nc(body.username.trim()),
password: User.generateHash(body.password),
auth: {
activationKey: crypto.randomBytes(256).toString("hex"),
emailVerified: false,
},
});
console.log("nu", nuser);
console.log("nnibg", mongoose.connections);
await nuser.save();
console.log("savey", await nuser.save());
return {
success: true,
};
});