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
+64 -49
View File
@@ -5,64 +5,80 @@ import { AuthOptions, Session } from "next-auth";
import bcrypt from "bcrypt";
import EmailProvider from "next-auth/providers/email";
import { JWT } from "next-auth/jwt";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { Adapter } from "next-auth/adapters";
import sendVerificationRequest from "@/lib/api/sendVerificationRequest";
import { Provider } from "next-auth/providers";
const providers: Provider[] = [
CredentialsProvider({
type: "credentials",
credentials: {
username: {
label: "Username",
type: "text",
},
password: {
label: "Password",
type: "password",
},
},
async authorize(credentials, req) {
if (!credentials) return null;
const findUser = await prisma.user.findFirst({
where: {
OR: [
{
username: credentials.username.toLowerCase(),
},
{
email: credentials.username.toLowerCase(),
},
],
emailVerified: { not: null },
},
});
let passwordMatches: boolean = false;
if (findUser?.password) {
passwordMatches = bcrypt.compareSync(
credentials.password,
findUser.password
);
}
if (passwordMatches) {
return findUser;
} else return null as any;
},
}),
];
if (process.env.EMAIL_SERVER && process.env.EMAIL_FROM)
providers.push(
EmailProvider({
server: process.env.EMAIL_SERVER,
from: process.env.EMAIL_FROM,
maxAge: 600,
sendVerificationRequest(params) {
sendVerificationRequest(params);
},
})
);
export const authOptions: AuthOptions = {
adapter: PrismaAdapter(prisma) as Adapter,
session: {
strategy: "jwt",
},
providers: [
// EmailProvider({
// server: process.env.EMAIL_SERVER,
// from: process.env.EMAIL_FROM,
// }),
CredentialsProvider({
type: "credentials",
credentials: {
username: {
label: "Username",
type: "text",
},
password: {
label: "Password",
type: "password",
},
},
async authorize(credentials, req) {
if (!credentials) return null;
// const { username, password } = credentials as {
// id: number;
// username: string;
// password: string;
// };
const findUser = await prisma.user.findFirst({
where: {
username: credentials.username.toLowerCase(),
},
});
let passwordMatches: boolean = false;
if (findUser?.password) {
passwordMatches = bcrypt.compareSync(
credentials.password,
findUser.password
);
}
if (passwordMatches) {
return findUser;
} else return null as any;
},
}),
],
providers,
pages: {
signIn: "/login",
},
callbacks: {
session: async ({ session, token }: { session: Session; token: JWT }) => {
console.log(token);
session.user.id = parseInt(token.id as string);
session.user.username = token.username as string;
@@ -70,7 +86,6 @@ export const authOptions: AuthOptions = {
},
// Using the `...rest` parameter to be able to narrow down the type based on `trigger`
jwt({ token, trigger, session, user }) {
console.log(user);
if (trigger === "signIn") {
token.id = user.id;
token.username = (user as any).username;
+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." });
}
}