Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 6532 | Rev 6592 | Ir a la última revisión | | Comparar con el anterior | 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 { useForm } from 'react-hook-form'
6511 stevensc 4
import { useDispatch, useSelector } from 'react-redux'
6509 stevensc 5
import Recaptcha from 'react-recaptcha'
6
import cryptoJsAesJson from '../../../utils/crypto-js/cryptojs-aes-format'
7
 
6513 stevensc 8
import { login } from '../../../redux/auth/auth.actions'
9
import { addNotification } from '../../../redux/notification/notification.actions'
10
 
6509 stevensc 11
import Spinner from '../../../components/UI/Spinner'
12
import FormErrorFeedback from '../../../components/UI/FormErrorFeedback'
13
 
14
const Login = ({
15
  facebookOauth = '/signin/facebook',
16
  twitterOauth = '/signin/twitter',
17
  googleOauth = '/signin/google',
18
}) => {
19
  const { site_key, aes, defaultNetwork } = useSelector(({ auth }) => auth)
20
  const [rememberChecked, setRememberChecked] = useState(false)
21
  const [isLoading, setIsLoading] = useState(false)
22
  const [isVerified, setIsVerified] = useState(false)
23
 
24
  const reCaptchaToken = useRef('')
6511 stevensc 25
  const reCaptchaInstance = useRef(null)
6509 stevensc 26
 
6511 stevensc 27
  const dispatch = useDispatch()
28
 
6531 stevensc 29
  const {
30
    register,
31
    handleSubmit,
32
    errors,
33
    setError,
34
    getValues,
35
    setValue,
36
    reset,
37
  } = useForm({ mode: 'onBlur' })
6509 stevensc 38
 
39
  useEffect(() => {
40
    reCaptchaInstance.current?.reset()
41
  }, [])
42
 
43
  const onSubmitHandler = async (data, event) => {
44
    const formData = new FormData()
45
    Object.entries(data).map(([key, value]) => {
46
      if (key === 'email' && value)
47
        return formData.append(key, cryptoJsAesJson.encrypt(value, aes))
48
      if (key === 'password' && value)
49
        return formData.append(key, cryptoJsAesJson.encrypt(value, aes))
50
      if (value) formData.append(key, value)
51
    })
52
    formData.append('captcha', reCaptchaToken.current)
53
    await axios
54
      .post('/signin', formData)
55
      .then(({ data: response }) => {
56
        const { success, data } = response
57
        if (!success) {
58
          if (data.constructor.name === 'Object') {
59
            Object.entries(data).map(([key, value]) => {
60
              if (key in getValues()) {
61
                setError(key, {
62
                  type: 'manual',
63
                  message: Array.isArray(value) ? value[0] : value,
64
                })
65
              }
66
            })
67
            return
68
          }
6511 stevensc 69
          dispatch(addNotification({ style: 'danger', msg: data }))
6509 stevensc 70
          return
71
        }
72
 
6532 stevensc 73
        reCaptchaInstance.current.reset()
74
        loginExpiredCallbackHandler()
6531 stevensc 75
        reset()
6591 stevensc 76
        window.location.replace('/dashboard')
6509 stevensc 77
      })
6511 stevensc 78
      .catch((err) => {
6532 stevensc 79
        reCaptchaInstance.current.reset()
80
        loginExpiredCallbackHandler()
81
        setValue('password', '')
82
 
6511 stevensc 83
        dispatch(
84
          addNotification({
85
            style: 'danger',
86
            msg: 'Disculpe, ha ocurrido un error',
87
          })
88
        )
89
        console.log(`Error: ${err}`)
90
        throw new Error(err)
91
      })
6532 stevensc 92
      .finally(() => setIsLoading(false))
6509 stevensc 93
  }
94
 
95
  const loginVerifyCallbackHandler = (response) => {
96
    reCaptchaToken.current = response
97
    setIsVerified(true)
98
  }
99
 
100
  const loginExpiredCallbackHandler = () => {
101
    reCaptchaToken.current = ''
102
    setIsVerified(false)
103
  }
104
 
105
  const handleOnRecaptchaLoad = () => {
106
    reCaptchaToken.current = ''
107
  }
108
 
109
  const getRedirectUrl = async (endpoint) => {
110
    try {
111
      const res = await axios.get(endpoint)
112
      if (res.data && res.data.data) {
113
        window.location.href = res.data.data
114
      }
115
    } catch (error) {
116
      console.log('>>: error > ', error)
117
    }
118
  }
119
 
120
  return (
121
    <>
122
      <h3>Entrar</h3>
123
      <form onSubmit={handleSubmit(onSubmitHandler)}>
124
        <div className="inputContainer">
125
          <div className="sn-field">
126
            <input
127
              type="email"
128
              name="email"
129
              ref={register({
130
                required: 'Este campo es requerido',
131
                pattern: {
132
                  value: /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/i,
133
                  message:
134
                    'Debe ser una dirección de correo electrónico valida',
135
                },
136
              })}
137
              placeholder="Correo electrónico"
138
              maxLength="64"
139
            />
140
            <i className="la la-envelope" />
141
          </div>
142
          {errors.email && (
143
            <FormErrorFeedback>{errors.email.message}</FormErrorFeedback>
144
          )}
145
        </div>
146
        <div className="inputContainer">
147
          <div className="sn-field">
148
            <input
149
              type="password"
150
              name="password"
151
              ref={register({
152
                required: 'Este campo es requerido',
153
                pattern: {
154
                  value:
155
                    /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$^x%x*-]).{6,16}$/i,
156
                  message:
157
                    'Debe contener entre 6 y 16 caracteres, incluida una letra mayúscula, un número y un carácter especial #?!@$^%*-',
158
                },
159
              })}
160
              placeholder="Clave"
161
            />
162
            <i className="la la-lock"></i>
163
          </div>
164
          {errors.password && (
165
            <FormErrorFeedback>{errors.password.message}</FormErrorFeedback>
166
          )}
167
        </div>
168
        <div className="checky-sec">
169
          <div className="fgt-sec">
170
            <input
171
              type="checkbox"
172
              name="remember"
173
              id="remember"
174
              checked={rememberChecked}
175
              ref={register}
176
              value="1"
177
              readOnly
178
            />
179
            <label onClick={() => setRememberChecked(!rememberChecked)}>
180
              <span></span>
181
            </label>
182
            <small onClick={() => setRememberChecked(!rememberChecked)}>
183
              Recuerdame
184
            </small>
185
          </div>
186
        </div>
187
        <div className="sn-field">
188
          <Recaptcha
189
            sitekey={site_key}
190
            verifyCallback={loginVerifyCallbackHandler}
191
            verifyCallbackName="loginVerifyCallbackHandler"
192
            expiredCallback={loginExpiredCallbackHandler}
193
            expiredCallbackName="loginExpiredCallbackHandler"
194
            ref={reCaptchaInstance}
195
            render="explicit"
196
            onloadCallback={handleOnRecaptchaLoad}
197
            hl="es"
198
          />
199
        </div>
200
        <button
201
          type="submit"
202
          value="submit"
203
          id="btn-submit"
204
          disabled={!isVerified}
205
        >
206
          Entrar
207
        </button>
208
      </form>
209
      {defaultNetwork && (
210
        <div className="login-resources">
211
          <h4>Entrar usando su red social</h4>
212
          <ul>
213
            <li>
214
              <a
215
                onClick={() => getRedirectUrl(facebookOauth)}
216
                className="cursor-pointer fb text-white"
217
                title=""
218
              >
219
                <i className="fa fa-facebook"></i> FACEBOOK
220
              </a>
221
            </li>
222
            <li>
223
              <a
224
                onClick={() => getRedirectUrl(twitterOauth)}
225
                className="cursor-pointer tw btn-connect-social-media text-white"
226
                title=""
227
              >
228
                <i className="fa fa-twitter"></i> TWITTER
229
              </a>
230
            </li>
231
            <li className="bg-secondary">
232
              <a
233
                onClick={() => getRedirectUrl(googleOauth)}
234
                className="cursor-pointer go btn-connect-social-media text-white"
235
                title=""
236
              >
237
                <i className="fa fa-google"></i> GOOGLE
238
              </a>
239
            </li>
240
          </ul>
241
        </div>
242
      )}
243
      {isLoading && <Spinner />}
244
    </>
245
  )
246
}
247
 
248
export default Login