Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 2633 | Rev 2636 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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