Proyectos de Subversion LeadersLinked - SPA

Rev

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