Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 6510 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
6509 stevensc 1
import React, { useRef, useState, useEffect } from 'react'
2
import { axios } from '../../../utils'
3
import { Link } from 'react-router-dom'
4
import { useForm } from 'react-hook-form'
5
import { useSelector } from 'react-redux'
6
import { addNotification } from '../../../redux/notification/notification.actions'
7
import styled from 'styled-components'
8
import Recaptcha from 'react-recaptcha'
9
import CryptoJSAesJson from '../../../utils/crypto-js/cryptojs-aes-format'
10
 
11
import Spinner from '../../UI/Spinner'
12
import FormErrorFeedback from '../../UI/FormErrorFeedback'
13
 
14
const StyledCheck = styled.div`
15
  display: flex;
16
  flex-direction: column;
17
  justify-content: center;
18
  align-items: center;
19
  img {
20
    width: 100px;
21
    margin-bottom: 1rem;
22
  }
23
  p {
24
    text-align: center;
25
  }
26
`
27
const StyledSpinnerContainer = styled.div`
28
  position: absolute;
29
  left: 0;
30
  top: 0;
31
  width: 100%;
32
  height: 100%;
33
  background: rgba(255, 255, 255, 0.4);
34
  display: flex;
35
  justify-content: center;
36
  align-items: center;
37
  z-index: 300;
38
`
39
const ForgotPassword = () => {
40
  const { site_key, aes } = useSelector(({ auth }) => auth)
41
  const [forgotSent, setForgotSent] = useState(false)
42
  const [isLoading, setIsLoading] = useState(false)
43
  const [isVerified, setIsVerified] = useState(false)
44
 
45
  const reCaptchaInstance = useRef()
46
  const reCaptchaToken = useRef('')
47
 
48
  const { register, handleSubmit, setError, errors } = useForm({ mode: 'all' })
49
 
50
  const forgotPasswordVerifyCallbackHandler = (response) => {
51
    if (response) {
52
      reCaptchaToken.current = response
53
      setIsVerified(true)
54
    }
55
  }
56
 
57
  const forgotPasswordExpiredCallbackHandler = () => {
58
    reCaptchaToken.current = ''
59
    setIsVerified(false)
60
  }
61
 
62
  const onSubmitHandler = async (data) => {
63
    setIsLoading(true)
64
 
65
    const formData = new FormData()
66
    Object.entries(data).map(([key, value]) => {
67
      if (key === 'email' && value) {
68
        formData.append(key, CryptoJSAesJson.encrypt(value, aes))
69
        return
70
      }
71
 
72
      formData.append(key, value)
73
    })
74
    formData.append('captcha', reCaptchaToken.current)
75
 
76
    await axios
77
      .post('/forgot-password', formData)
78
      .then(({ data: response }) => {
79
        const { success, data } = response
80
        if (!success) {
81
          const resError = data
82
 
83
          if (typeof resError === 'object') {
84
            Object.entries(resError).map(([key, value]) => {
85
              setError(key, {
86
                message: Array.isArray(value) ? value[0] : value,
87
              })
88
            })
89
            return
90
          }
91
 
92
          addNotification({ style: 'danger', msg: resError })
93
        }
94
        reCaptchaInstance.current.reset()
95
        forgotPasswordExpiredCallbackHandler()
96
        setForgotSent(true)
97
 
98
        reCaptchaInstance.current.reset()
99
        loginExpiredCallbackHandler()
100
      })
101
      .finally(() => setIsLoading(false))
102
  }
103
 
104
  const handleOnRecaptchaLoad = () => {
105
    reCaptchaToken.current = ''
106
  }
107
 
108
  const loginExpiredCallbackHandler = () => {
109
    reCaptchaToken.current = ''
110
    setIsVerified(false)
111
  }
112
 
113
  useEffect(() => {
114
    reCaptchaInstance.current?.reset()
115
  }, [])
116
 
117
  if (forgotSent) {
118
    return (
119
      <StyledCheck>
120
        <img src="/images/check.png" alt="check" />
121
        <p>El enlace de recuperación fue enviado a su correo electrónico</p>
122
        <Link to="/signin">
123
          <button id="btn-submit" className="sign_in_sec_button">
124
            Entrar
125
          </button>
126
        </Link>
127
      </StyledCheck>
128
    )
129
  }
130
 
131
  return (
132
    <React.Fragment>
133
      <h3>Olvide mi Clave</h3>
134
      <form onSubmit={handleSubmit(onSubmitHandler)}>
135
        <div className="row">
136
          <div className="col-lg-12 no-pdd">
137
            <div className="inputContainer">
138
              <div className="sn-field">
139
                <input
140
                  type="email"
141
                  name="email"
142
                  placeholder="Correo electrónico"
143
                  ref={register({
144
                    required: 'Este campo es requerido',
145
                    pattern: {
146
                      value: /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/i,
147
                      message:
148
                        'Debe ser una dirección de correo electrónico valida',
149
                    },
150
                  })}
151
                />
152
                <i className="la la-envelope" />
153
              </div>
154
              {errors.email && (
155
                <FormErrorFeedback>{errors.email.message}</FormErrorFeedback>
156
              )}
157
            </div>
158
          </div>
159
          <div className="col-lg-12 no-pdd">
160
            <div className="inputContainer">
161
              <div className="sn-field">
162
                <Recaptcha
163
                  sitekey={site_key}
164
                  verifyCallback={forgotPasswordVerifyCallbackHandler}
165
                  verifyCallbackName="forgotPasswordVerifyCallbackHandler"
166
                  expiredCallback={forgotPasswordExpiredCallbackHandler}
167
                  expiredCallbackName="forgotPasswordExpiredCallbackHandler"
168
                  ref={reCaptchaInstance}
169
                  render="explicit"
170
                  onloadCallback={handleOnRecaptchaLoad}
171
                  hl="es"
172
                />
173
              </div>
174
            </div>
175
          </div>
176
          <div className="col-lg-12 no-pdd">
177
            <button type="submit" value="submit" disabled={!isVerified}>
178
              Nueva Clave
179
            </button>
180
          </div>
181
        </div>
182
      </form>
183
      {isLoading && (
184
        <StyledSpinnerContainer>
185
          <Spinner />
186
        </StyledSpinnerContainer>
187
      )}
188
    </React.Fragment>
189
  )
190
}
191
 
192
export default ForgotPassword