| 3736 |
stevensc |
1 |
import { useState } from 'react';
|
|
|
2 |
import { useApi, useAlert } from '@shared/hooks';
|
|
|
3 |
import { changePassword } from '@account-settings/services';
|
|
|
4 |
|
|
|
5 |
export function usePasswordChange() {
|
|
|
6 |
const { showSuccess, showError } = useAlert();
|
|
|
7 |
const [passwordErrors, setPasswordErrors] = useState({
|
|
|
8 |
isErrorPassword: false,
|
|
|
9 |
isErrorConfirmation: false
|
|
|
10 |
});
|
|
|
11 |
|
|
|
12 |
const { loading: isUpdating, execute: executeUpdate } = useApi(changePassword, {
|
|
|
13 |
onSuccess: (response) => {
|
|
|
14 |
if (response.success) {
|
|
|
15 |
showSuccess(response.data);
|
|
|
16 |
clearErrors();
|
|
|
17 |
} else {
|
|
|
18 |
if (typeof response.data === 'string') {
|
|
|
19 |
showError(response.data);
|
|
|
20 |
} else {
|
|
|
21 |
Object.entries(response.data).forEach(([key, value]) => {
|
|
|
22 |
showError(`${key}: ${value}`);
|
|
|
23 |
});
|
|
|
24 |
}
|
|
|
25 |
}
|
|
|
26 |
},
|
|
|
27 |
onError: (error) => {
|
|
|
28 |
showError(error.message || 'Error al cambiar la contraseña');
|
|
|
29 |
}
|
|
|
30 |
});
|
|
|
31 |
|
|
|
32 |
const clearErrors = () => {
|
|
|
33 |
setPasswordErrors({
|
|
|
34 |
isErrorPassword: false,
|
|
|
35 |
isErrorConfirmation: false
|
|
|
36 |
});
|
|
|
37 |
};
|
|
|
38 |
|
|
|
39 |
const setPasswordError = () => {
|
|
|
40 |
setPasswordErrors((prev) => ({ ...prev, isErrorPassword: true }));
|
|
|
41 |
setTimeout(() => {
|
|
|
42 |
setPasswordErrors((prev) => ({ ...prev, isErrorPassword: false }));
|
|
|
43 |
}, 10000);
|
|
|
44 |
};
|
|
|
45 |
|
|
|
46 |
const setConfirmationError = () => {
|
|
|
47 |
setPasswordErrors((prev) => ({ ...prev, isErrorConfirmation: true }));
|
|
|
48 |
setTimeout(() => {
|
|
|
49 |
setPasswordErrors((prev) => ({ ...prev, isErrorConfirmation: false }));
|
|
|
50 |
}, 10000);
|
|
|
51 |
};
|
|
|
52 |
|
|
|
53 |
const validateAndChangePassword = async (data) => {
|
|
|
54 |
clearErrors();
|
|
|
55 |
|
|
|
56 |
const validPassword = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$^x%x*-]).{6,16}$/;
|
|
|
57 |
|
|
|
58 |
if (!validPassword.test(data.password)) {
|
|
|
59 |
setPasswordError();
|
|
|
60 |
showError(
|
|
|
61 |
'La contraseña debe tener entre 6 y 16 caracteres, al menos una mayúscula, una minúscula, un número y un carácter especial'
|
|
|
62 |
);
|
|
|
63 |
return;
|
|
|
64 |
}
|
|
|
65 |
|
|
|
66 |
if (data.password !== data.confirm_password) {
|
|
|
67 |
setConfirmationError();
|
|
|
68 |
showError('Las contraseñas no coinciden');
|
|
|
69 |
return;
|
|
|
70 |
}
|
|
|
71 |
|
|
|
72 |
await executeUpdate(data);
|
|
|
73 |
};
|
|
|
74 |
|
|
|
75 |
return {
|
|
|
76 |
isUpdating,
|
|
|
77 |
passwordErrors,
|
|
|
78 |
validateAndChangePassword,
|
|
|
79 |
clearErrors
|
|
|
80 |
};
|
|
|
81 |
}
|