Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 6510 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useRef, useState, useEffect } from 'react'
import { axios } from '../../../utils'
import { Link } from 'react-router-dom'
import { useForm } from 'react-hook-form'
import { useDispatch, useSelector } from 'react-redux'
import { addNotification } from '../../../redux/notification/notification.actions'
import styled from 'styled-components'
import Recaptcha from 'react-recaptcha'
import CryptoJSAesJson from '../../../utils/crypto-js/cryptojs-aes-format'

import Spinner from '../../UI/Spinner'
import FormErrorFeedback from '../../UI/FormErrorFeedback'

const StyledCheck = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  img {
    width: 100px;
    margin-bottom: 1rem;
  }
  p {
    text-align: center;
  }
`
const StyledSpinnerContainer = styled.div`
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 300;
`
const ForgotPassword = () => {
  const { site_key, aes } = useSelector(({ auth }) => auth)
  const [forgotSent, setForgotSent] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [isVerified, setIsVerified] = useState(false)

  const reCaptchaToken = useRef('')
  const reCaptchaInstance = useRef(null)

  const dispatch = useDispatch()

  const { register, handleSubmit, setError, errors } = useForm({ mode: 'all' })

  const forgotPasswordVerifyCallbackHandler = (response) => {
    if (response) {
      reCaptchaToken.current = response
      setIsVerified(true)
    }
  }

  const forgotPasswordExpiredCallbackHandler = () => {
    reCaptchaToken.current = ''
    setIsVerified(false)
  }

  const onSubmitHandler = async (data) => {
    setIsLoading(true)

    const formData = new FormData()
    Object.entries(data).map(([key, value]) => {
      if (key === 'email' && value) {
        formData.append(key, CryptoJSAesJson.encrypt(value, aes))
        return
      }

      formData.append(key, value)
    })
    formData.append('captcha', reCaptchaToken.current)

    await axios
      .post('/forgot-password', formData)
      .then(({ data: response }) => {
        const { success, data } = response
        if (!success) {
          const resError = data

          if (typeof resError === 'object') {
            Object.entries(resError).map(([key, value]) => {
              setError(key, {
                message: Array.isArray(value) ? value[0] : value,
              })
            })
            return
          }

          dispatch(addNotification({ style: 'danger', msg: resError }))
        }

        reCaptchaInstance.current.reset()
        forgotPasswordExpiredCallbackHandler()
        setForgotSent(true)
        reCaptchaInstance.current.reset()
        loginExpiredCallbackHandler()
      })
      .catch((err) => {
        dispatch(
          addNotification({
            style: 'danger',
            msg: 'Disculpe, ha ocurrido un error',
          })
        )
        console.log(`Error: ${err}`)
        throw new Error(err)
      })
      .finally(() => setIsLoading(false))
  }

  const handleOnRecaptchaLoad = () => {
    reCaptchaToken.current = ''
  }

  const loginExpiredCallbackHandler = () => {
    reCaptchaToken.current = ''
    setIsVerified(false)
  }

  useEffect(() => {
    reCaptchaInstance.current?.reset()
  }, [])

  if (forgotSent) {
    return (
      <StyledCheck>
        <img src="/images/check.png" alt="check" />
        <p>El enlace de recuperación fue enviado a su correo electrónico</p>
        <Link to="/signin">
          <button id="btn-submit" className="sign_in_sec_button">
            Entrar
          </button>
        </Link>
      </StyledCheck>
    )
  }

  return (
    <>
      <h3>Olvide mi Clave</h3>
      <form onSubmit={handleSubmit(onSubmitHandler)}>
        <div className="inputContainer">
          <div className="sn-field">
            <input
              type="email"
              name="email"
              placeholder="Correo electrónico"
              ref={register({
                required: 'Este campo es requerido',
                pattern: {
                  value: /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/i,
                  message:
                    'Debe ser una dirección de correo electrónico valida',
                },
              })}
            />
            <i className="la la-envelope" />
          </div>
          {errors.email && (
            <FormErrorFeedback>{errors.email.message}</FormErrorFeedback>
          )}
        </div>
        <div className="inputContainer">
          <div className="sn-field">
            <Recaptcha
              sitekey={site_key}
              verifyCallback={forgotPasswordVerifyCallbackHandler}
              verifyCallbackName="forgotPasswordVerifyCallbackHandler"
              expiredCallback={forgotPasswordExpiredCallbackHandler}
              expiredCallbackName="forgotPasswordExpiredCallbackHandler"
              ref={reCaptchaInstance}
              render="explicit"
              onloadCallback={handleOnRecaptchaLoad}
              hl="es"
            />
          </div>
        </div>
        <button type="submit" value="submit" disabled={!isVerified}>
          Nueva Clave
        </button>
      </form>
      {isLoading && (
        <StyledSpinnerContainer>
          <Spinner />
        </StyledSpinnerContainer>
      )}
    </>
  )
}

export default ForgotPassword