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
+4 -4
View File
@@ -1,17 +1,17 @@
import "@/styles/globals.css";
import { SessionProvider } from "next-auth/react";
import type { AppProps } from "next/app";
import Head from "next/head";
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<SessionProvider session={pageProps.session}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<title>Linkwarden</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Component {...pageProps} />
</>
</SessionProvider>
);
}
+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." });
}
}
+16 -3
View File
@@ -1,13 +1,26 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]";
type Data = {
name: string;
message: string;
data?: object;
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
console.log("Triggered hello.ts");
res.status(200).json({ name: "John Doe" });
const session = await getServerSession(req, res, authOptions);
console.log(session);
if (!session) {
res.status(401).json({ message: "You must be logged in." });
return;
}
return res.json({
message: "Success",
});
}
-43
View File
@@ -1,43 +0,0 @@
import { prisma } from "@/lib/db";
import type { NextApiRequest, NextApiResponse } from "next";
interface Data {
name: string;
}
interface User {
name: string;
username: string;
password: string;
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const data: User = req.body;
const createUser = await prisma.user.create({
data: {
name: data.name,
username: data.username,
password: data.password,
collections: {
create: [
{
role: "owner",
collection: {
create: {
name: "First Collection",
},
},
},
],
},
},
});
console.log(createUser);
res.status(200).json(createUser);
}
@@ -0,0 +1,26 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]";
type Data = {
message: string;
data?: object;
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const session = await getServerSession(req, res, authOptions);
if (!session) {
res.status(401).json({ message: "You must be logged in." });
return;
}
console.log(session?.user?.email);
return res.json({
message: "Success",
});
}
+80
View File
@@ -0,0 +1,80 @@
import { signIn } from "next-auth/react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
interface FormData {
email: string;
password: string;
}
export default function Login() {
const session = useSession();
const router = useRouter();
useEffect(() => {
if (session.status === "authenticated") {
router.push("/");
console.log("Already logged in.");
}
}, []);
const [form, setForm] = useState<FormData>({
email: "",
password: "",
});
async function loginUser() {
console.log(form);
if (form.email != "" && form.password != "") {
const res = await signIn("credentials", {
email: form.email,
password: form.password,
redirect: false,
});
if (res?.ok) {
setForm({
email: "",
password: "",
});
router.push("/");
} else {
console.log("User not found or password does not match.", res);
}
} else {
console.log("Please fill out all the fields.");
}
}
return (
<div className="p-5">
<p className="text-3xl font-bold text-center mb-10">Linkwarden</p>
<input
type="text"
placeholder="Email"
value={form.email}
onChange={(e) => setForm({ ...form, email: e.target.value })}
className="border border-gray-700 rounded block m-2 mx-auto p-2"
/>
<input
type="text"
placeholder="Password"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
className="border border-gray-700 rounded block m-2 mx-auto p-2"
/>
<div
className="mx-auto bg-black w-min p-3 m-5 text-white rounded cursor-pointer"
onClick={loginUser}
>
Login
</div>
<Link href={"/auth/register"} className="block mx-auto w-min">
Register
</Link>
</div>
);
}
+43 -16
View File
@@ -1,34 +1,58 @@
import { useState } from "react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
interface FormData {
name: string;
username: string;
email: string;
password: string;
}
export default function Register() {
const session = useSession();
const router = useRouter();
useEffect(() => {
if (session.status === "authenticated") {
router.push("/");
console.log("Already logged in.");
}
}, [session]);
const [form, setForm] = useState<FormData>({
name: "",
username: "",
email: "",
password: "",
});
function registerUser() {
async function registerUser() {
let success: boolean = false;
console.log(form);
if (form.name != "" && form.username != "" && form.password != "") {
fetch("/api/register", {
if (form.name != "" && form.email != "" && form.password != "") {
await fetch("/api/auth/register", {
body: JSON.stringify(form),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
})
.then((res) => {
success = res.ok;
return res.json();
})
.then((data) => console.log(data));
setForm({
name: "",
username: "",
password: "",
});
if (success) {
setForm({
name: "",
email: "",
password: "",
});
router.push("/auth/login");
}
} else {
console.log("Please fill out all the fields.");
}
@@ -46,9 +70,9 @@ export default function Register() {
/>
<input
type="text"
placeholder="Username"
value={form.username}
onChange={(e) => setForm({ ...form, username: e.target.value })}
placeholder="Email"
value={form.email}
onChange={(e) => setForm({ ...form, email: e.target.value })}
className="border border-gray-700 rounded block m-2 mx-auto p-2"
/>
<input
@@ -59,11 +83,14 @@ export default function Register() {
className="border border-gray-700 rounded block m-2 mx-auto p-2"
/>
<div
className="mx-auto bg-gray-700 w-min p-3 m-5 text-white rounded cursor-pointer"
className="mx-auto bg-black w-min p-3 m-5 text-white rounded cursor-pointer"
onClick={registerUser}
>
Register
</div>
<Link href={"/auth/login"} className="block mx-auto w-min">
Login
</Link>
</div>
);
}
View File