首页 > 后端开发 > Golang > 正文

密码重置功能:前端

DDD
发布: 2024-10-02 12:07:01
原创
868 人浏览过

Password Reset Feature: Frontend

前端

与后端部分相比,前端部分非常简单。我需要做的就是创建一个模式,并使用它发送数据两次。

  • 首先发送电子邮件将OTP发送至
  • 然后发送OTP和新密码进行更改

为了创建模式,我从我早期项目 Chat-Nat 的 MessageModal 组件中复制了一些代码,即用于封装模式的类名。

规划

我将添加“忘记密码?”登录页面上的按钮,并设置 onClick 处理程序以打开模态

在请求之前,我需要使用布尔状态来表示 OTP 是否已发送到用户的电子邮件。我将状态命名为 OTPSent

  • 如果!isOTPSent ->只需询问电子邮件地址,发送 api 请求,然后如果成功 setOTPSent(true)
  • 如果是OTPS发送->现在还要求提供 OTP 和新密码,如果成功,则关闭模式

以下是我从该项目的现有前端重用的一些组件和挂钩:

  • 盒子->它将我的登录和注册页面整齐地包装到一张卡片中,位于页面中央,并在此处重用,标题为“密码重置”
  • 验证表单->只是一个表单,但我对其进行了编码以在我们等待服务器响应时禁用提交按钮并将按钮文本设置为“正在加载...”
  • 表单输入->具有自己的标签的输入字段,具有值设置器和 onChange 处理程序,可选地具有 isRequired 布尔值
  • 使用Axios->自定义挂钩来处理来自需要令牌刷新的服务器的响应。 apiReq 函数用于正常请求发送,一些自定义错误处理用于显示alert() 和刷新令牌,refreshReq 函数用于刷新身份验证令牌并再次尝试初始请求。

这是模态的完整代码:

// src/components/PasswordResetModal.tsx
import React, { useState } from "react"
import AuthForm from "./AuthForm";
import FormInput from "./FormInput";
import Box from "./Box";
import { useAxios } from "../hooks/useAxios";

interface FormData {
    email: string,
    new_password: string,
    otp: string,
}

interface Props {
    isVisible: boolean,
    onClose: () => void,
}

const PasswordResetModal: React.FC<Props> = ({ isVisible, onClose }) => {
    const [formData, setFormData] = useState<FormData>({
        email: "",
        new_password: "",
        otp: ""
    });
    const [isLoading, setLoading] = useState<boolean>(false);
    const [isOTPSent, setOTPSent] = useState<boolean>(false);
    const { apiReq } = useAxios();

    const handleClose = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
        if ((e.target as HTMLElement).id === "wrapper") {
            onClose();

            // could have setOTPSent(false), but avoiding it in case user misclicks outside
        }
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData({
            ...formData,
            [name]: value,
        });
    };

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setLoading(true);

        if (!isOTPSent) { // first request for sending otp,
            const response = await apiReq<unknown, FormData>("post", "/api/reset-password", formData)

            if (response) {
                alert("OTP has been sent to your email");
                setOTPSent(true);
            }
        } else { // then using otp to change password
            const response = await apiReq<unknown, FormData>("put", "/api/reset-password", formData)

            if (response) {
                alert("Password has been successfully reset\nPlease log in again");

                // clear the form
                setFormData({
                    email: "",
                    otp: "",
                    new_password: "",
                })

                // close modal
                onClose();
            }
        }

        setLoading(false);
    };

    if (!isVisible) return null;

    return (
        <div
            id="wrapper"
            className="fixed inset-0 bg-black bg-opacity-25 backdrop-blur-sm flex justify-center items-center"
            onClick={handleClose}>
            <Box title="Password Reset">
                <AuthForm
                    submitHandler={handleSubmit}
                    isLoading={isLoading}
                    buttonText={isOTPSent ? "Change Password" : "Send OTP"}>
                    <FormInput
                        id="email"
                        label="Your email"
                        type="email"
                        value={formData.email}
                        changeHandler={handleChange}
                        isRequired />

                    {isOTPSent && (<>
                        <FormInput
                            id="otp"
                            label="OTP"
                            type="text"
                            value={formData.otp}
                            changeHandler={handleChange}
                            isRequired />
                        <FormInput
                            id="new_password"
                            label="New Password"
                            type="password"
                            value={formData.new_password}
                            changeHandler={handleChange}
                            isRequired />
                    </>)}
                </AuthForm>
            </Box>
        </div>
    )
}

export default PasswordResetModal
登录后复制

这是在登录表单中处理模式的条件渲染的方式

// src/pages/auth/Login.tsx
import PasswordResetModal from "../../components/PasswordResetModal";

const Login: React.FC = () => {
    const [showModal, setShowModal] = useState<boolean>(false);

    return (
        <Section>
            <Box title="Login">
                <div className="grid grid-flow-col">
                    {/* link to the register page here */}
                    <button 
                    type="button"
                    onClick={() => setShowModal(true)}
                    className="text-blue-700 hover:text-white border border-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-3 py-2 text-center me-2 mb-2 dark:border-blue-500 dark:text-blue-500 dark:hover:text-white dark:hover:bg-blue-500 dark:focus:ring-blue-800">
                        Forgot Password?
                    </button>

                    <PasswordResetModal isVisible={showModal} onClose={() => setShowModal(false)} />
                </div>
            </Box>
        </Section>
    )
登录后复制

我们完成了!至少我是这么想的。

在我的开发环境中运行该应用程序时,我发现了一个错误,如果后端已经运行很长时间,则电子邮件将无法通过。

我们将在下一篇文章中修复此错误

以上是密码重置功能:前端的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!