Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 2802 | | Comparar con el anterior | Ultima modificación | Ver Log |

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