mirror of
https://github.com/documenso/documenso.git
synced 2025-11-13 00:03:33 +10:00
Merge pull request #196 from documenso/feat/password-reset
feat: reset password
This commit is contained in:
115
apps/web/components/forgot-password.tsx
Normal file
115
apps/web/components/forgot-password.tsx
Normal file
@ -0,0 +1,115 @@
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@documenso/ui";
|
||||
import Logo from "./logo";
|
||||
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { toast } from "react-hot-toast";
|
||||
|
||||
interface ForgotPasswordForm {
|
||||
email: string;
|
||||
}
|
||||
|
||||
export default function ForgotPassword() {
|
||||
const { register, formState, resetField, handleSubmit } = useForm<ForgotPasswordForm>();
|
||||
const [resetSuccessful, setResetSuccessful] = useState(false);
|
||||
|
||||
const onSubmit = async (values: ForgotPasswordForm) => {
|
||||
const response = await toast.promise(
|
||||
fetch(`/api/auth/forgot-password`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(values),
|
||||
}),
|
||||
{
|
||||
loading: "Sending...",
|
||||
success: "Reset link sent.",
|
||||
error: "Could not send reset link :/",
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
toast.dismiss();
|
||||
|
||||
if (response.status == 404) {
|
||||
toast.error("Email address not found.");
|
||||
}
|
||||
|
||||
if (response.status == 400) {
|
||||
toast.error("Password reset requested.");
|
||||
}
|
||||
|
||||
if (response.status == 500) {
|
||||
toast.error("Something went wrong.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.ok) {
|
||||
setResetSuccessful(true);
|
||||
}
|
||||
|
||||
resetField("email");
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex min-h-full items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="w-full max-w-md space-y-8">
|
||||
<div>
|
||||
<Logo className="mx-auto h-20 w-auto"></Logo>
|
||||
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">
|
||||
{resetSuccessful ? "Reset Password" : "Forgot Password?"}
|
||||
</h2>
|
||||
<p className="mt-2 text-center text-sm text-gray-600">
|
||||
{resetSuccessful
|
||||
? "Please check your email for reset instructions."
|
||||
: "No worries, we'll send you reset instructions."}
|
||||
</p>
|
||||
</div>
|
||||
{!resetSuccessful && (
|
||||
<form className="mt-8 space-y-6" onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="-space-y-px rounded-md shadow-sm">
|
||||
<div>
|
||||
<label htmlFor="email-address" className="sr-only">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
{...register("email")}
|
||||
id="email-address"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
className="focus:border-neon focus:ring-neon relative block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 text-gray-900 placeholder-gray-500 focus:z-10 focus:outline-none sm:text-sm"
|
||||
placeholder="Email"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={formState.isSubmitting}
|
||||
className="group relative flex w-full">
|
||||
Reset password
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
<div>
|
||||
<Link href="/login">
|
||||
<div className="relative mt-10 flex items-center justify-center gap-2 text-sm text-gray-500 hover:cursor-pointer hover:text-gray-900">
|
||||
<ArrowLeftIcon className="h-4 w-4" />
|
||||
Back to log in
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -111,9 +111,11 @@ export default function Login(props: any) {
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-sm">
|
||||
<a href="#" className="hover:text-neon-700 font-medium text-gray-500">
|
||||
<Link
|
||||
href="/forgot-password"
|
||||
className="hover:text-neon-700 font-medium text-gray-500">
|
||||
Forgot your password?
|
||||
</a>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
|
||||
143
apps/web/components/reset-password.tsx
Normal file
143
apps/web/components/reset-password.tsx
Normal file
@ -0,0 +1,143 @@
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { Button } from "@documenso/ui";
|
||||
import Logo from "./logo";
|
||||
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "react-hot-toast";
|
||||
import * as z from "zod";
|
||||
|
||||
const ZResetPasswordFormSchema = z
|
||||
.object({
|
||||
password: z.string().min(8, { message: "Password must be at least 8 characters" }),
|
||||
confirmPassword: z.string().min(8, { message: "Password must be at least 8 characters" }),
|
||||
})
|
||||
.refine((data) => data.password === data.confirmPassword, {
|
||||
path: ["confirmPassword"],
|
||||
message: "Password don't match",
|
||||
});
|
||||
|
||||
type TResetPasswordFormSchema = z.infer<typeof ZResetPasswordFormSchema>;
|
||||
|
||||
export default function ResetPassword() {
|
||||
const router = useRouter();
|
||||
const { token } = router.query;
|
||||
|
||||
const {
|
||||
register,
|
||||
formState: { errors, isSubmitting },
|
||||
handleSubmit,
|
||||
} = useForm<TResetPasswordFormSchema>({
|
||||
resolver: zodResolver(ZResetPasswordFormSchema),
|
||||
});
|
||||
|
||||
const [resetSuccessful, setResetSuccessful] = useState(false);
|
||||
|
||||
const onSubmit = async ({ password }: TResetPasswordFormSchema) => {
|
||||
const response = await toast.promise(
|
||||
fetch(`/api/auth/reset-password`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ password, token }),
|
||||
}),
|
||||
{
|
||||
loading: "Resetting...",
|
||||
success: `Reset password successful`,
|
||||
error: "Could not reset password :/",
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
toast.dismiss();
|
||||
const error = await response.json();
|
||||
toast.error(error.message);
|
||||
}
|
||||
|
||||
if (response.ok) {
|
||||
setResetSuccessful(true);
|
||||
setTimeout(() => {
|
||||
router.push("/login");
|
||||
}, 3000);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex min-h-full items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="w-full max-w-md space-y-8">
|
||||
<div>
|
||||
<Logo className="mx-auto h-20 w-auto"></Logo>
|
||||
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">
|
||||
Reset Password
|
||||
</h2>
|
||||
<p className="mt-2 text-center text-sm text-gray-600">
|
||||
{resetSuccessful ? "Your password has been reset." : "Please chose your new password"}
|
||||
</p>
|
||||
</div>
|
||||
{!resetSuccessful && (
|
||||
<form className="mt-8 space-y-6" onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="-space-y-px rounded-md shadow-sm">
|
||||
<div>
|
||||
<label htmlFor="password" className="sr-only">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
{...register("password", { required: "Password is required" })}
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
className="focus:border-neon focus:ring-neon relative block w-full appearance-none rounded-none rounded-t-md border border-gray-300 px-3 py-2 text-gray-900 placeholder-gray-500 focus:z-10 focus:outline-none sm:text-sm"
|
||||
placeholder="New password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="confirmPassword" className="sr-only">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
{...register("confirmPassword")}
|
||||
id="confirmPassword"
|
||||
name="confirmPassword"
|
||||
type="password"
|
||||
required
|
||||
className="focus:border-neon focus:ring-neon relative block w-full appearance-none rounded-none rounded-b-md border border-gray-300 px-3 py-2 text-gray-900 placeholder-gray-500 focus:z-10 focus:outline-none sm:text-sm"
|
||||
placeholder="Confirm new password"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{errors && (
|
||||
<span className="text-xs text-red-500">{errors.confirmPassword?.message}</span>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="group relative flex w-full">
|
||||
Reset password
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<Link href="/login">
|
||||
<div className="relative mt-10 flex items-center justify-center gap-2 text-sm text-gray-500 hover:cursor-pointer hover:text-gray-900">
|
||||
<ArrowLeftIcon className="h-4 w-4" />
|
||||
Back to log in
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
63
apps/web/pages/api/auth/forgot-password.ts
Normal file
63
apps/web/pages/api/auth/forgot-password.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { sendResetPassword } from "@documenso/lib/mail";
|
||||
import { defaultHandler, defaultResponder } from "@documenso/lib/server";
|
||||
import prisma from "@documenso/prisma";
|
||||
import crypto from "crypto";
|
||||
|
||||
async function postHandler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { email } = req.body;
|
||||
const cleanEmail = email.toLowerCase();
|
||||
|
||||
if (!cleanEmail || !/.+@.+/.test(cleanEmail)) {
|
||||
res.status(400).json({ message: "Invalid email" });
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: {
|
||||
email: cleanEmail,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return res.status(200).json({ message: "A password reset email has been sent." });
|
||||
}
|
||||
|
||||
const existingToken = await prisma.passwordResetToken.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
createdAt: {
|
||||
gte: new Date(Date.now() - 1000 * 60 * 60),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (existingToken) {
|
||||
return res.status(200).json({ message: "A password reset email has been sent." });
|
||||
}
|
||||
|
||||
const token = crypto.randomBytes(64).toString("hex");
|
||||
const expiry = new Date();
|
||||
expiry.setHours(expiry.getHours() + 24); // Set expiry to one hour from now
|
||||
|
||||
let passwordResetToken;
|
||||
try {
|
||||
passwordResetToken = await prisma.passwordResetToken.create({
|
||||
data: {
|
||||
token,
|
||||
expiry,
|
||||
userId: user.id,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return res.status(500).json({ message: "Something went wrong" });
|
||||
}
|
||||
|
||||
await sendResetPassword(user, passwordResetToken.token);
|
||||
|
||||
return res.status(200).json({ message: "A password reset email has been sent." });
|
||||
}
|
||||
|
||||
export default defaultHandler({
|
||||
POST: Promise.resolve({ default: defaultResponder(postHandler) }),
|
||||
});
|
||||
69
apps/web/pages/api/auth/reset-password.ts
Normal file
69
apps/web/pages/api/auth/reset-password.ts
Normal file
@ -0,0 +1,69 @@
|
||||
import { NextApiRequest, NextApiResponse } from "next";
|
||||
import { hashPassword, verifyPassword } from "@documenso/lib/auth";
|
||||
import { sendResetPasswordSuccessMail } from "@documenso/lib/mail";
|
||||
import { defaultHandler, defaultResponder } from "@documenso/lib/server";
|
||||
import prisma from "@documenso/prisma";
|
||||
|
||||
async function postHandler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { token, password } = req.body;
|
||||
|
||||
if (!token) {
|
||||
res.status(400).json({ message: "Invalid token" });
|
||||
return;
|
||||
}
|
||||
|
||||
const foundToken = await prisma.passwordResetToken.findUnique({
|
||||
where: {
|
||||
token,
|
||||
},
|
||||
include: {
|
||||
User: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!foundToken) {
|
||||
return res.status(404).json({ message: "Invalid token." });
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
|
||||
if (now > foundToken.expiry) {
|
||||
return res.status(400).json({ message: "Token has expired" });
|
||||
}
|
||||
|
||||
const isSamePassword = await verifyPassword(password, foundToken.User.password!);
|
||||
|
||||
if (isSamePassword) {
|
||||
return res.status(400).json({ message: "New password must be different" });
|
||||
}
|
||||
|
||||
const hashedPassword = await hashPassword(password);
|
||||
|
||||
const transaction = await prisma.$transaction([
|
||||
prisma.user.update({
|
||||
where: {
|
||||
id: foundToken.userId,
|
||||
},
|
||||
data: {
|
||||
password: hashedPassword,
|
||||
},
|
||||
}),
|
||||
prisma.passwordResetToken.deleteMany({
|
||||
where: {
|
||||
userId: foundToken.userId,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!transaction) {
|
||||
return res.status(500).json({ message: "Error resetting password." });
|
||||
}
|
||||
|
||||
await sendResetPasswordSuccessMail(foundToken.User);
|
||||
|
||||
res.status(200).json({ message: "Password reset successful." });
|
||||
}
|
||||
|
||||
export default defaultHandler({
|
||||
POST: Promise.resolve({ default: defaultResponder(postHandler) }),
|
||||
});
|
||||
@ -8,13 +8,13 @@ async function postHandler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const { email, password, source } = req.body;
|
||||
const cleanEmail = email.toLowerCase();
|
||||
|
||||
if (!cleanEmail || !cleanEmail.includes("@")) {
|
||||
res.status(422).json({ message: "Invalid email" });
|
||||
if (!cleanEmail || !/.+@.+/.test(cleanEmail)) {
|
||||
res.status(400).json({ message: "Invalid email" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!password || password.trim().length < 7) {
|
||||
return res.status(422).json({
|
||||
return res.status(400).json({
|
||||
message: "Password should be at least 7 characters long.",
|
||||
});
|
||||
}
|
||||
|
||||
30
apps/web/pages/auth/reset/[token].tsx
Normal file
30
apps/web/pages/auth/reset/[token].tsx
Normal file
@ -0,0 +1,30 @@
|
||||
import Head from "next/head";
|
||||
import { getUserFromToken } from "@documenso/lib/server";
|
||||
import ResetPassword from "../../../components/reset-password";
|
||||
|
||||
export default function ResetPasswordPage() {
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Reset Password | Documenso</title>
|
||||
</Head>
|
||||
<ResetPassword />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export async function getServerSideProps(context: any) {
|
||||
const user = await getUserFromToken(context.req, context.res);
|
||||
if (user)
|
||||
return {
|
||||
redirect: {
|
||||
source: "/login",
|
||||
destination: "/dashboard",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
props: {},
|
||||
};
|
||||
}
|
||||
20
apps/web/pages/auth/reset/index.tsx
Normal file
20
apps/web/pages/auth/reset/index.tsx
Normal file
@ -0,0 +1,20 @@
|
||||
import React from "react";
|
||||
import Logo from "../../../components/logo";
|
||||
|
||||
export default function ResetPage() {
|
||||
return (
|
||||
<div className="flex min-h-full items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="w-full max-w-md space-y-8">
|
||||
<div>
|
||||
<Logo className="mx-auto h-20 w-auto"></Logo>
|
||||
<h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">
|
||||
Reset Password
|
||||
</h2>
|
||||
<p className="mt-2 text-center text-sm text-gray-600">
|
||||
The token you provided is invalid. Please try again.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
32
apps/web/pages/forgot-password.tsx
Normal file
32
apps/web/pages/forgot-password.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
import { GetServerSideProps, GetServerSidePropsContext } from "next";
|
||||
import Head from "next/head";
|
||||
import { getUserFromToken } from "@documenso/lib/server";
|
||||
import ForgotPassword from "../components/forgot-password";
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Forgot Password | Documenso</title>
|
||||
</Head>
|
||||
<ForgotPassword />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export async function getServerSideProps({ req }: GetServerSidePropsContext) {
|
||||
const user = await getUserFromToken(req);
|
||||
|
||||
if (user)
|
||||
return {
|
||||
redirect: {
|
||||
source: "/login",
|
||||
destination: "/dashboard",
|
||||
permanent: false,
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
props: {},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user