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

72 lines
1.5 KiB
TypeScript
Raw Normal View History

2021-03-24 15:03:04 +00:00
import prisma from '../../../lib/prisma';
import { hashPassword } from "../../../lib/auth";
export default async function handler(req, res) {
if (req.method !== 'POST') {
return;
}
2021-03-24 15:03:04 +00:00
const data = req.body;
const { username, email, password } = data;
2021-03-24 15:03:04 +00:00
if (!username) {
res.status(422).json({message: 'Invalid username'});
return;
}
if (!email || !email.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
},
{
email: email
2021-03-24 15:03:04 +00:00
}
],
AND: [
{
emailVerified: {
not: null,
},
}
]
2021-03-24 15:03:04 +00:00
}
});
2021-03-24 15:03:04 +00:00
if (existingUser) {
let message: string = (
existingUser.email !== email
) ? '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);
const user = await prisma.user.upsert({
where: { email, },
update: {
username,
password: hashedPassword,
emailVerified: new Date(Date.now()),
},
create: {
username,
email,
password: hashedPassword,
}
});
2021-03-24 15:03:04 +00:00
res.status(201).json({message: 'Created user'});
2021-03-24 15:03:04 +00:00
}