ForgotPassword.js 9.14 KB
import axios from "axios";
import { Form, Formik } from "formik";
import { useRouter } from "next/router";
import React, { Fragment, useState } from "react";
import { Button } from "react-bootstrap";
import { toast } from "react-toastify";
import * as Yup from "yup";
import { finishVendorOtpVerification } from "../../redux/actions/vendorActions";
import OTPInput from "./OTPInput";

const ForgotPassword = () => {
  const loginValidationSchema = Yup.object().shape({
    email: Yup.string().required("Email Id is Required").email("Please Enter An Valid Email Id")
  });
  const [showOtpModal, setshowOtpModal] = useState(false);
  const [showPasswordPannel, setshowPasswordPannel] = useState(false);
  const [otp, setOtp] = useState(new Array(4).fill(""));
  const [passwordUpdatedSuccess, setpasswordUpdatedSuccess] = useState(false);
  const router = useRouter();
  return (
    <div>
      <Fragment>
        <div className="contaier-fluid login-banner-image">
          <div className="row">
            <div className="col-11 col-lg-4 login-div">
              <div className="">
                <h2>Password reset:</h2>
                <div className="form-container">
                  <div>
                    <Formik
                      initialValues={{
                        email: "",
                        password: "",
                        confirmPassword: ""
                      }}
                      validationSchema={loginValidationSchema}
                      onSubmit={async values => {
                        const config = {
                          headers: {
                            //   Authorization: `Bearer ${authUser.data.jwt}`,
                            "Content-Type": "application/json"
                          }
                        };

                        const data = {
                          data: {
                            email: values.email
                          }
                        };

                        const response = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/end-users`, data, config);
                        console.log("response", response);
                        if (response.data.otpSent) {
                          toast.success("OTP sent");
                          setshowOtpModal(true);
                        } else {
                        }
                      }}
                    >
                      {({ values, errors, touched, handleChange, handleBlur, handleSubmit, setErrors, setValues }) => (
                        <Form>
                          {!showOtpModal && !showPasswordPannel && (
                            <>
                              <div className="input-group">
                                <label>Email Id</label>
                                <input type="text" name="email" onChange={handleChange} onBlur={handleBlur} value={values.email} placeholder="yourname@example.com" />
                                {errors.email && touched.email && <span className="form-error">{errors.email}</span>}
                              </div>
                              <div className="input-group">
                                <Button type="submit" className="btn btn-primary btn-submit" disabled={!values.email || errors.email}>
                                  Send OTP
                                </Button>
                              </div>
                            </>
                          )}
                          {showOtpModal && (
                            <>
                              <div className="input-group mb-0 text-center">
                                <div className="otp-input">
                                  <OTPInput setOtp={setOtp} otp={otp} />
                                </div>
                                <div className="input-group mt-4">
                                  <Button
                                    type="submit"
                                    className="btn btn-primary btn-submit"
                                    onClick={async e => {
                                      e.preventDefault();
                                      console.log(otp);
                                      const oneTimePassword = otp.join("");
                                      // setLoading(false);
                                      const otpRes = await finishVendorOtpVerification({ email: values.email, oneTimePassword });
                                      console.log("otpRes", otpRes);
                                      if (!otpRes.data.ok) {
                                        toast.error("OTP is invalid, please enter the correct OTP!");
                                        return;
                                      }
                                      if (otpRes.data.ok) {
                                        setshowPasswordPannel(true);
                                        setshowOtpModal(false);
                                      }
                                    }}
                                  >
                                    Verify OTP
                                  </Button>
                                </div>
                              </div>
                            </>
                          )}
                          {showPasswordPannel && (
                            <>
                              <div className="input-group">
                                <label>Password</label>
                                <input type="password" name="password" onChange={handleChange} onBlur={handleBlur} value={values.password} placeholder="Enter new password" />
                                {errors.password && touched.password && <span className="form-error">{errors.password}</span>}
                                <label className="mt-3">Confirm Password</label>
                                <input
                                  type="password"
                                  name="confirmPassword"
                                  onChange={handleChange}
                                  onBlur={e => {
                                    handleBlur(e);
                                    if (values.password != values.confirmPassword) {
                                      setErrors({ confirmPassword: "Passwords do not match!" });
                                    }
                                  }}
                                  value={values.confirmPassword}
                                  placeholder="Confirm Password"
                                />
                                {errors.confirmPassword && touched.confirmPassword && <span className="form-error">{errors.confirmPassword}</span>}
                              </div>
                              <div className="input-group">
                                <Button
                                  //   type="submit"
                                  className="btn btn-primary btn-submit"
                                  disabled={!values.password || !values.confirmPassword || values.password != values.confirmPassword}
                                  onClick={async () => {
                                    const config = {
                                      headers: {
                                        //   Authorization: `Bearer ${authUser.data.jwt}`,
                                        "Content-Type": "application/json"
                                      }
                                    };
                                    const response = await axios.post(
                                      `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/end-user/reset-password`,
                                      { email: values.email, password: values.password },
                                      config
                                    );
                                    console.log("response", response);
                                    if (response.data.ok) {
                                      // setpasswordUpdatedSuccess(true)
                                      setshowPasswordPannel(false);
                                      setshowOtpModal(false);
                                      toast.success("Password updated! you can now log in.");
                                    //   setValues({ email: "", password: "", confirmPassword: "" });
                                    // setTimeout(() => {
                                    //     router.push("/")
                                    // }, 500);
                                    } else {
                                      toast.error("Error occured, please try again!");
                                    }
                                  }}
                                >
                                  Reset password
                                </Button>
                              </div>
                            </>
                          )}
                        </Form>
                      )}
                    </Formik>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Fragment>
    </div>
  );
};

export default ForgotPassword;