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 ( +
+ ); +} 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'; ---