password reset functionality [WIP]
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import { prisma } from "@/lib/api/db";
|
||||
import sendPasswordResetRequest from "@/lib/api/sendPasswordResetRequest";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
export default async function forgotPassword(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
if (req.method === "POST") {
|
||||
const email = req.body.email;
|
||||
|
||||
if (!email) {
|
||||
return res.status(400).json({
|
||||
response: "Invalid email.",
|
||||
});
|
||||
}
|
||||
|
||||
const recentPasswordRequestsCount = await prisma.passwordResetToken.count({
|
||||
where: {
|
||||
identifier: email,
|
||||
createdAt: {
|
||||
gt: new Date(new Date().getTime() - 1000 * 60 * 5), // 5 minutes
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Rate limit password reset requests
|
||||
if (recentPasswordRequestsCount >= 3) {
|
||||
return res.status(400).json({
|
||||
response: "Too many requests. Please try again later.",
|
||||
});
|
||||
}
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: {
|
||||
email,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user || !user.email) {
|
||||
return res.status(400).json({
|
||||
response: "Invalid email.",
|
||||
});
|
||||
}
|
||||
|
||||
sendPasswordResetRequest(user.email, user.name);
|
||||
|
||||
return res.status(200).json({
|
||||
response: "Password reset email sent.",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { prisma } from "@/lib/api/db";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import bcrypt from "bcrypt";
|
||||
|
||||
export default async function resetPassword(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
if (req.method === "POST") {
|
||||
const token = req.body.token;
|
||||
const password = req.body.password;
|
||||
|
||||
if (!password || password.length < 8) {
|
||||
return res.status(400).json({
|
||||
response: "Password must be at least 8 characters.",
|
||||
});
|
||||
}
|
||||
|
||||
if (!token || typeof token !== "string") {
|
||||
return res.status(400).json({
|
||||
response: "Invalid token.",
|
||||
});
|
||||
}
|
||||
|
||||
// Hashed password
|
||||
const saltRounds = 10;
|
||||
const hashedPassword = await bcrypt.hash(password, saltRounds);
|
||||
|
||||
// Check token in db
|
||||
const verifyToken = await prisma.passwordResetToken.findFirst({
|
||||
where: {
|
||||
token,
|
||||
expires: {
|
||||
gt: new Date(),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!verifyToken) {
|
||||
return res.status(400).json({
|
||||
response: "Invalid token.",
|
||||
});
|
||||
}
|
||||
|
||||
const email = verifyToken.identifier;
|
||||
|
||||
// Update password
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
email,
|
||||
},
|
||||
data: {
|
||||
password: hashedPassword,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.passwordResetToken.update({
|
||||
where: {
|
||||
token,
|
||||
},
|
||||
data: {
|
||||
expires: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
// Delete tokens older than 5 minutes
|
||||
await prisma.passwordResetToken.deleteMany({
|
||||
where: {
|
||||
identifier: email,
|
||||
createdAt: {
|
||||
lt: new Date(new Date().getTime() - 1000 * 60 * 5), // 5 minutes
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return res.status(200).json({
|
||||
response: "Password reset successfully.",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import AccentSubmitButton from "@/components/AccentSubmitButton";
|
||||
import TextInput from "@/components/TextInput";
|
||||
import CenteredForm from "@/layouts/CenteredForm";
|
||||
import Link from "next/link";
|
||||
import { FormEvent, useState } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
|
||||
interface FormData {
|
||||
password: string;
|
||||
passwordConfirmation: string;
|
||||
}
|
||||
|
||||
export default function ResetPassword() {
|
||||
const [submitLoader, setSubmitLoader] = useState(false);
|
||||
|
||||
const [form, setForm] = useState<FormData>({
|
||||
password: "",
|
||||
passwordConfirmation: "",
|
||||
});
|
||||
|
||||
const [isEmailSent, setIsEmailSent] = useState(false);
|
||||
|
||||
async function submitRequest() {
|
||||
const response = await fetch("/api/v1/auth/forgot-password", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
toast.success(data.response);
|
||||
setIsEmailSent(true);
|
||||
} else {
|
||||
toast.error(data.response);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendConfirmation(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
|
||||
if (form.password !== "") {
|
||||
setSubmitLoader(true);
|
||||
|
||||
const load = toast.loading("Sending password recovery link...");
|
||||
|
||||
await submitRequest();
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
setSubmitLoader(false);
|
||||
} else {
|
||||
toast.error("Please fill out all the fields.");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<CenteredForm>
|
||||
<form onSubmit={sendConfirmation}>
|
||||
<div className="p-4 mx-auto flex flex-col gap-3 justify-between max-w-[30rem] min-w-80 w-full bg-base-200 rounded-2xl shadow-md border border-neutral-content">
|
||||
<p className="text-3xl text-center font-extralight">
|
||||
{isEmailSent ? "Email Sent!" : "Forgot Password?"}
|
||||
</p>
|
||||
|
||||
<div className="divider my-0"></div>
|
||||
|
||||
{!isEmailSent ? (
|
||||
<>
|
||||
<div>
|
||||
<p>
|
||||
Enter your email so we can send you a link to create a new
|
||||
password.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm w-fit font-semibold mb-1">Email</p>
|
||||
|
||||
<TextInput
|
||||
autoFocus
|
||||
type="password"
|
||||
placeholder="johnny@example.com"
|
||||
value={form.password}
|
||||
className="bg-base-100"
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, password: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AccentSubmitButton
|
||||
type="submit"
|
||||
label="Send Login Link"
|
||||
className="mt-2 w-full"
|
||||
loading={submitLoader}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-center">
|
||||
Check your email for a link to reset your password. If it doesn’t
|
||||
appear within a few minutes, check your spam folder.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex items-baseline gap-1 justify-center">
|
||||
<Link href={"/login"} className="block font-bold">
|
||||
Go back
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</CenteredForm>
|
||||
);
|
||||
}
|
||||
+57
-36
@@ -1,7 +1,6 @@
|
||||
import AccentSubmitButton from "@/components/AccentSubmitButton";
|
||||
import TextInput from "@/components/TextInput";
|
||||
import CenteredForm from "@/layouts/CenteredForm";
|
||||
import { signIn } from "next-auth/react";
|
||||
import Link from "next/link";
|
||||
import { FormEvent, useState } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
@@ -17,24 +16,40 @@ export default function Forgot() {
|
||||
email: "",
|
||||
});
|
||||
|
||||
const [isEmailSent, setIsEmailSent] = useState(false);
|
||||
|
||||
async function submitRequest() {
|
||||
const response = await fetch("/api/v1/auth/forgot-password", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
toast.success(data.response);
|
||||
setIsEmailSent(true);
|
||||
} else {
|
||||
toast.error(data.response);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendConfirmation(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
|
||||
if (form.email !== "") {
|
||||
setSubmitLoader(true);
|
||||
|
||||
const load = toast.loading("Sending login link...");
|
||||
const load = toast.loading("Sending password recovery link...");
|
||||
|
||||
await signIn("email", {
|
||||
email: form.email,
|
||||
callbackUrl: "/",
|
||||
});
|
||||
await submitRequest();
|
||||
|
||||
toast.dismiss(load);
|
||||
|
||||
setSubmitLoader(false);
|
||||
|
||||
toast.success("Login link sent.");
|
||||
} else {
|
||||
toast.error("Please fill out all the fields.");
|
||||
}
|
||||
@@ -45,40 +60,46 @@ export default function Forgot() {
|
||||
<form onSubmit={sendConfirmation}>
|
||||
<div className="p-4 mx-auto flex flex-col gap-3 justify-between max-w-[30rem] min-w-80 w-full bg-base-200 rounded-2xl shadow-md border border-neutral-content">
|
||||
<p className="text-3xl text-center font-extralight">
|
||||
Password Recovery
|
||||
{isEmailSent ? "Email Sent!" : "Forgot Password?"}
|
||||
</p>
|
||||
|
||||
<div className="divider my-0"></div>
|
||||
|
||||
<div>
|
||||
<p>
|
||||
Enter your email so we can send you a link to recover your
|
||||
account. Make sure to change your password in the profile settings
|
||||
afterwards.
|
||||
</p>
|
||||
<p className="text-sm text-neutral">
|
||||
You wont get logged in if you haven't created an account yet.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm w-fit font-semibold mb-1">Email</p>
|
||||
{!isEmailSent ? (
|
||||
<>
|
||||
<div>
|
||||
<p>
|
||||
Enter your email so we can send you a link to create a new
|
||||
password.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm w-fit font-semibold mb-1">Email</p>
|
||||
|
||||
<TextInput
|
||||
autoFocus
|
||||
type="email"
|
||||
placeholder="johnny@example.com"
|
||||
value={form.email}
|
||||
className="bg-base-100"
|
||||
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<TextInput
|
||||
autoFocus
|
||||
type="email"
|
||||
placeholder="johnny@example.com"
|
||||
value={form.email}
|
||||
className="bg-base-100"
|
||||
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AccentSubmitButton
|
||||
type="submit"
|
||||
label="Send Login Link"
|
||||
className="mt-2 w-full"
|
||||
loading={submitLoader}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-center">
|
||||
Check your email for a link to reset your password. If it doesn’t
|
||||
appear within a few minutes, check your spam folder.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<AccentSubmitButton
|
||||
type="submit"
|
||||
label="Send Login Link"
|
||||
className="mt-2 w-full"
|
||||
loading={submitLoader}
|
||||
/>
|
||||
<div className="flex items-baseline gap-1 justify-center">
|
||||
<Link href={"/login"} className="block font-bold">
|
||||
Go back
|
||||
|
||||
Reference in New Issue
Block a user