Proyectos de Subversion LeadersLinked - SPA

Rev

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

Rev Autor Línea Nro. Línea
2781 stevensc 1
import React, { useEffect, useState } from 'react'
2
import { useForm } from 'react-hook-form'
3
import { connect } from 'react-redux'
4
import { styled } from '@mui/material'
5
 
6
import { axios } from 'utils'
7
import { addNotification } from '@app/redux/notification/notification.actions'
8
 
9
import Spinner from '@components/UI/Spinner'
10
import FormErrorFeedback from '@components/UI/form/FormErrorFeedback'
11
 
12
const StyledSpinnerContainer = styled('div')`
13
  position: absolute;
14
  left: 0;
15
  top: 0;
16
  width: 100%;
17
  height: 100%;
18
  background: rgba(255, 255, 255, 0.4);
19
  display: flex;
20
  justify-content: center;
21
  align-items: center;
22
  z-index: 300;
23
`
24
 
25
const ChangePassword = ({ addNotification }) => {
26
  const [loading, setLoading] = useState(false)
27
  const [isErrorPassword, setIsErrorPassword] = useState(false)
28
  const [isErrorConfirmation, setIsErrorConfirmation] = useState(false)
29
 
30
  const {
31
    register,
32
    handleSubmit,
33
    getValues,
34
    errors,
35
    reset,
36
    setError,
37
    formState: { isSubmitSuccessful }
38
  } = useForm()
39
 
40
  const handleOnSubmit = async (data) => {
41
    setLoading(true)
42
 
43
    let errorPassword = false
44
 
45
    const validPassword =
46
      /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$^x%x*-]).{6,16}$/
47
 
48
    if (!validPassword.test(data.password)) {
49
      setIsErrorPassword(true)
50
      setTimeout(() => {
51
        setIsErrorPassword(false)
52
      }, 10000)
53
      setLoading(false)
54
      errorPassword = true
55
    }
56
 
57
    if (data.password !== data.confirmation) {
58
      setIsErrorConfirmation(true)
59
      setTimeout(() => {
60
        setIsErrorConfirmation(false)
61
      }, 10000)
62
      setLoading(false)
63
      errorPassword = true
64
    }
65
 
66
    if (!errorPassword) {
67
      const formData = new FormData()
68
      Object.entries(data).forEach(([key, value]) => {
69
        formData.append(key, value)
70
      })
71
      await axios
72
        .post('/account-settings/password', formData)
73
        .then((response) => {
74
          const resData = response.data
75
          if (resData.success) {
76
            addNotification({
77
              style: 'success',
78
              msg: resData.data
79
            })
80
          } else {
81
            if (typeof resData.data === 'object') {
82
              Object.entries(resData.data).forEach(([key, value]) => {
83
                setError(key, { type: 'manual', message: value[0] })
84
              })
85
            } else {
86
              const errorMessage =
87
                typeof resData.data === 'string'
88
                  ? resData.data
89
                  : 'Ha ocurrido un error, Por favor intente mas tarde'
90
              addNotification({
91
                style: 'danger',
92
                msg: errorMessage
93
              })
94
            }
95
          }
96
        })
97
      setLoading(false)
98
    }
99
 
100
    errorPassword = false
101
  }
102
 
103
  useEffect(() => {
104
    reset({ ...getValues })
105
  }, [isSubmitSuccessful])
106
 
107
  return (
108
    <div className='settings-container'>
109
      <h2>Cambiar clave</h2>
110
      <div className='acc-setting_content'>
111
        <form onSubmit={handleSubmit(handleOnSubmit)}>
112
          <div className='d-flex flex-wrap' style={{ gap: '1rem' }}>
113
            <div className='cp-field'>
114
              <label htmlFor='password'>Clave</label>
115
              <div className='cpp-fiel'>
116
                <input
117
                  type='password'
118
                  name='password'
119
                  minLength='6'
120
                  maxLength='16'
121
                  id='password'
122
                  ref={register({
123
                    required: 'Por favor ingrese la contraseña'
124
                  })}
125
                  pattern='^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$^x%x*-]).{6,16}$'
126
                  title='La clave debe contener entre 6 y 16 caracteres, incluida una letra mayúscula, un número y un carácter especial #?!@$^%*-'
127
                />
128
                <i className='fa fa-lock'></i>
129
              </div>
130
              {isErrorPassword && (
131
                <p className='text-danger'>
132
                  Disculpe, La clave debe contener entre 6 y 16 caracteres,
133
                  incluida una letra mayúscula, un número y un carácter especial
134
                  #?!@$^%*-
135
                </p>
136
              )}
137
              {
138
                <FormErrorFeedback>
139
                  {errors?.password?.message}
140
                </FormErrorFeedback>
141
              }
142
            </div>
143
            <div className='cp-field'>
144
              <label htmlFor='confirmation'>Confirmación</label>
145
              <div className='cpp-fiel'>
146
                <input
147
                  type='password'
148
                  name='confirmation'
149
                  minLength='6'
150
                  maxLength='16'
151
                  id='confirmation'
152
                  ref={register({
153
                    required: 'Por favor ingrese la contraseña',
154
                    validate: (value) =>
155
                      value === getValues('password') ||
156
                      'La contraseña no coincide'
157
                  })}
158
                  pattern='^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$^x%x*-]).{6,16}$'
159
                  title='La clave debe contener entre 6 y 16 caracteres, incluida una letra mayúscula, un número y un carácter especial #?!@$^%*-'
160
                />
161
                <i className='fa fa-lock'></i>
162
              </div>
163
              {isErrorConfirmation && (
164
                <p className='text-danger'>
165
                  Disculpe, las claves tienen que coincidir
166
                </p>
167
              )}
168
              {
169
                <FormErrorFeedback>
170
                  {errors?.confirmation?.message}
171
                </FormErrorFeedback>
172
              }
173
            </div>
174
          </div>
175
          <div className='pt-4 d-flex align-items-center justify-content-center'>
176
            <button type='submit' className='btn btn-secondary'>
177
              Guardar
178
            </button>
179
          </div>
180
        </form>
181
      </div>
182
      {loading && (
183
        <StyledSpinnerContainer>
184
          <Spinner />
185
        </StyledSpinnerContainer>
186
      )}
187
    </div>
188
  )
189
}
190
 
191
const mapDispatchToProps = {
192
  addNotification: (notification) => addNotification(notification)
193
}
194
 
195
export default connect(null, mapDispatchToProps)(ChangePassword)