Added user authentication.

This commit is contained in:
Daniel
2023-02-06 21:29:23 +03:30
parent 882bbd64d1
commit e5ed2ec5db
16 changed files with 657 additions and 83 deletions
+63
View File
@@ -0,0 +1,63 @@
import { prisma } from "@/lib/db";
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";
import { AuthOptions } from "next-auth";
import bcrypt from "bcrypt";
export const authOptions: AuthOptions = {
session: {
strategy: "jwt",
},
providers: [
CredentialsProvider({
type: "credentials",
credentials: {},
async authorize(credentials, req) {
const { email, password } = credentials as {
email: string;
password: string;
};
console.log(email, password);
const findUser = await prisma.user.findFirst({
where: {
email: email,
},
});
console.log(findUser);
// const findUser = await prisma.user.findMany({
// where: {
// email: email,
// },
// include: {
// collections: {
// include: {
// collection: true,
// },
// },
// },
// });
// console.log("BOOM!", findUser[0].collections);
let passwordMatches: boolean = false;
if (findUser?.password) {
passwordMatches = bcrypt.compareSync(password, findUser.password);
}
if (passwordMatches) {
return { name: findUser?.name, email: findUser?.email };
} else return null as any;
},
}),
],
pages: {
signIn: "/auth/login",
},
};
export default NextAuth(authOptions);
+56
View File
@@ -0,0 +1,56 @@
import { prisma } from "@/lib/db";
import type { NextApiRequest, NextApiResponse } from "next";
import bcrypt from "bcrypt";
interface Data {
message: string | object;
}
interface User {
name: string;
email: string;
password: string;
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const body: User = req.body;
const checkIfUserExists = await prisma.user.findFirst({
where: {
email: body.email,
},
});
if (!checkIfUserExists) {
const saltRounds = 10;
const hashedPassword = bcrypt.hashSync(body.password, saltRounds);
await prisma.user.create({
data: {
name: body.name,
email: body.email,
password: hashedPassword,
collections: {
create: [
{
role: "owner",
collection: {
create: {
name: "First Collection",
},
},
},
],
},
},
});
res.status(201).json({ message: "User successfully created." });
} else {
res.status(400).json({ message: "User already exists." });
}
}