cal.pub0.org/pages/api/auth/signup.ts

77 lines
1.7 KiB
TypeScript
Raw Normal View History

import { NextApiRequest, NextApiResponse } from "next";
import { hashPassword } from "@lib/auth";
import prisma from "@lib/prisma";
import slugify from "@lib/slugify";
2021-03-24 15:03:04 +00:00
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") {
return;
}
2021-03-24 15:03:04 +00:00
const data = req.body;
const { email, password } = data;
const username = slugify(data.username);
2021-10-25 09:29:54 +00:00
const userEmail = email.toLowerCase();
2021-03-24 15:03:04 +00:00
if (!username) {
res.status(422).json({ message: "Invalid username" });
return;
}
2021-10-25 09:29:54 +00:00
if (!userEmail || !userEmail.includes("@")) {
res.status(422).json({ message: "Invalid email" });
return;
}
if (!password || password.trim().length < 7) {
res.status(422).json({ message: "Invalid input - password should be at least 7 characters long." });
return;
}
2021-03-24 15:03:04 +00:00
const existingUser = await prisma.user.findFirst({
where: {
OR: [
{
username: username,
},
{
2021-10-25 09:29:54 +00:00
email: userEmail,
},
],
AND: [
{
emailVerified: {
not: null,
},
},
],
},
});
2021-03-24 15:03:04 +00:00
if (existingUser) {
const message: string =
2021-10-25 09:29:54 +00:00
existingUser.email !== userEmail ? "Username already taken" : "Email address is already registered";
2021-03-24 15:03:04 +00:00
return res.status(409).json({ message });
}
const hashedPassword = await hashPassword(password);
await prisma.user.upsert({
2021-10-25 09:29:54 +00:00
where: { email: userEmail },
update: {
username,
password: hashedPassword,
emailVerified: new Date(Date.now()),
},
create: {
username,
2021-10-25 09:29:54 +00:00
email: userEmail,
password: hashedPassword,
},
});
2021-03-24 15:03:04 +00:00
res.status(201).json({ message: "Created user" });
}