Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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