From 9e71ce5cefb6c1c59008ba95575dfeb1d4f0e153 Mon Sep 17 00:00:00 2001 From: Arik Chakma Date: Sun, 2 Apr 2023 01:24:10 +0600 Subject: [PATCH] chore: forgot password functionality --- src/components/Profile/ForgotPasswordForm.tsx | 133 ++++++++++++++++++ src/pages/forgot-password.astro | 32 +---- 2 files changed, 135 insertions(+), 30 deletions(-) create mode 100644 src/components/Profile/ForgotPasswordForm.tsx diff --git a/src/components/Profile/ForgotPasswordForm.tsx b/src/components/Profile/ForgotPasswordForm.tsx new file mode 100644 index 000000000..c3ab3c254 --- /dev/null +++ b/src/components/Profile/ForgotPasswordForm.tsx @@ -0,0 +1,133 @@ +import { useState } from 'preact/hooks'; + +export default function ForgotPasswordForm() { + const [email, setEmail] = useState(''); + const [isLoading, setIsLoading] = useState(false); + const [message, setMessage] = useState<{ + type: 'error' | 'success' | 'info'; + message: string; + }>(); + + const handleSubmit = async (e: Event) => { + e.preventDefault(); + setIsLoading(true); + + const previousLocalStorageValue = localStorage.getItem( + 'forgot-password-send-at' + ); + + if (previousLocalStorageValue) { + if (new Date().getTime() < Number(previousLocalStorageValue)) { + setIsLoading(false); + return setMessage({ + type: 'error', + message: 'Please wait a few seconds before trying again.', + }); + } + } + + const res = await fetch('http://localhost:8080/v1-forgot-password', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ email }), + }); + + const data = await res.json(); + + if (!res.ok) { + setIsLoading(false); + return setMessage({ + type: 'error', + message: data.message, + }); + } + + setIsLoading(false); + setEmail(''); + setMessage({ + type: 'success', + message: 'Check your email for a link to reset your password.', + }); + + // TODO: Set a time in localStorage to prevent spamming the API (now + 5s) + const now = new Date(); + const time = now.getTime(); + const expireTime = time + 5 * 1000; + now.setTime(expireTime); + localStorage.setItem('forgot-password-send-at', now.getTime().toString()); + }; + + return ( +
+

+ Forgot password? +

+

+ Enter the email address associated with your account, and we'll email + you a link to reset your password. +

+ + + setEmail((e.target as HTMLInputElement).value)} + /> + + {message && ( +
+ {message.message} +
+ )} + + +
+ ); +} diff --git a/src/pages/forgot-password.astro b/src/pages/forgot-password.astro index 2e67a5f83..ab75f2dd5 100644 --- a/src/pages/forgot-password.astro +++ b/src/pages/forgot-password.astro @@ -1,39 +1,11 @@ --- +import ForgotPasswordForm from '../components/Profile/ForgotPasswordForm'; import SettingLayout from '../layouts/SettingLayout.astro'; ---
-
-

- Forgot password? -

-

- Enter the email address associated with your account, and we'll email - you a link to reset your password. -

- - - - - -
+
Don't have an account?