fully implemented email authentication

This commit is contained in:
Daniel
2023-07-12 13:26:34 -05:00
committed by GitHub
parent 8513ab7688
commit 0050e14e7f
18 changed files with 520 additions and 196 deletions
+35 -4
View File
@@ -2,6 +2,9 @@ import { prisma } from "@/lib/api/db";
import type { NextApiRequest, NextApiResponse } from "next";
import bcrypt from "bcrypt";
const EmailProvider =
process.env.EMAIL_FROM && process.env.EMAIL_SERVER ? true : false;
interface Data {
response: string | object;
}
@@ -9,6 +12,7 @@ interface Data {
interface User {
name: string;
username: string;
email?: string;
password: string;
}
@@ -18,17 +22,43 @@ export default async function Index(
) {
const body: User = req.body;
if (!body.username || !body.password || !body.name)
const checkHasEmptyFields = EmailProvider
? !body.username || !body.password || !body.name || !body.email
: !body.username || !body.password || !body.name;
if (checkHasEmptyFields)
return res
.status(400)
.json({ response: "Please fill out all the fields." });
const checkIfUserExists = await prisma.user.findFirst({
const tenMinutesAgo = new Date(Date.now() - 10 * 60 * 1000);
// Remove user's who aren't verified for more than 10 minutes
await prisma.user.deleteMany({
where: {
username: body.username.toLowerCase(),
createdAt: {
lt: tenMinutesAgo,
},
emailVerified: null,
},
});
const checkIfUserExists = await prisma.user.findFirst({
where: EmailProvider
? {
OR: [
{ username: body.username.toLowerCase() },
{
email: body.email?.toLowerCase(),
},
],
emailVerified: { not: null },
}
: {
username: body.username.toLowerCase(),
},
});
if (!checkIfUserExists) {
const saltRounds = 10;
@@ -38,12 +68,13 @@ export default async function Index(
data: {
name: body.name,
username: body.username.toLowerCase(),
email: body.email?.toLowerCase(),
password: hashedPassword,
},
});
res.status(201).json({ response: "User successfully created." });
} else if (checkIfUserExists) {
res.status(400).json({ response: "User already exists." });
res.status(400).json({ response: "Username and/or Email already exists." });
}
}