Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adiciona validações de senha e cpf às telas de edição de usuário. #11

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Sentinela 2024.1 - FRONTEND
# Sentinela 2024.2 - FRONTEND

## Comandos para rodar o projeto

Expand Down
16 changes: 12 additions & 4 deletions src/Pages/Protected/Users/ViewMembershipPage/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
// import { mascaraCPF, mascaraRg, mascaraTelefone, mascaraCEP, validateField } from "../../../../Utils/mask";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import SecondaryButton from "../../../../Components/SecondaryButton";
import { validarCPF } from "../../../../Utils/validators";

const ViewMembershipPage = () => {
const { state } = useLocation();
Expand Down Expand Up @@ -215,16 +216,22 @@ const ViewMembershipPage = () => {
throw new Error("missing fields");
}

const message = await updateMembership(membershipId, formData);
if (message) {
throw new Error(message);
const response = await updateMembership(membershipId, formData);
console.log("resposta: ", response);
if(response.status === 200){
alert("Usuário atualizado com sucesso!");
} else {
alert(response.data.mensagem);
}

setOpenSuccessDialog(false);
alert("usuário atualizado com sucesso!");
} catch (error) {
setOpenSuccessDialog(false);
alert("Erro ao atualizar usuário");
console.error(
"Erro ao atualizar usuário",
error
);
}
};

Expand Down Expand Up @@ -261,6 +268,7 @@ const ViewMembershipPage = () => {
if (!sex) missingFields.push("Sexo");
if (!rg) missingFields.push("RG");
if (!cpf) missingFields.push("CPF");
if (!validarCPF(cpf)) missingFields.push("CPF");
if (!email) missingFields.push("Email");
if (!phone) missingFields.push("Celular");
if (!ufAddress) missingFields.push("UF do Endereço");
Expand Down
63 changes: 49 additions & 14 deletions src/Pages/Protected/Users/userUpdate/index.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Button } from "@mui/material";
import FieldSelect from "../../../../Components/FieldSelect";
import FieldText from "../../../../Components/FieldText";
import Modal from "../../../../Components/Modal";
Expand All @@ -16,6 +17,7 @@ import {
isValidCelular,
isValidEmail,
mascaraTelefone,
validaSenha,
} from "../../../../Utils/validators";

export default function UserUpdatePage() {
Expand All @@ -39,7 +41,8 @@ export default function UserUpdatePage() {
const [isEmailValid, setIsEmailValid] = useState(true);
const [isCelularValid, setIsCelularValid] = useState(true);
const [isUserVisible, setIsUserVisible] = useState(true);
const [isNewPasswordValid] = useState(true);
const [isNewPasswordValid, setNewPasswordValid] = useState(true);
const [passwordMessage, setPasswordMessage] = useState(" ");

const passwordsMatch = newPassword === confirmPassword;

Expand Down Expand Up @@ -74,8 +77,6 @@ export default function UserUpdatePage() {
fetchUser();
}, [userId]);

console.log(userId);

const handleSave = async () => {
const trimmedCelular = celular.replace(/\D/g, "");
const { isValid: isValidNumber, message: celularMessage } =
Expand Down Expand Up @@ -110,20 +111,27 @@ export default function UserUpdatePage() {
console.error(`Erro ao atualizar usuário com ID ${userId}:`, error);
}
};

const handleSavePassword = async () => {
if(!passwordsMatch || !isNewPasswordValid){
return;
}

const updatedUserPassword = {
old_password: oldPassword,
new_password: newPassword,
};

try {
await changePasswordInProfile(updatedUserPassword).then((data) => {
console.log("caraleo", data);
if (data && data.response.status != 200) {
if (data && data.status != 200) {
alert(data.response.data.mensagem);
}
}
else if(data && data.status == 200) {
handleSavePasswordModal();
}
});
handleSavePasswordModal();

} catch (error) {
console.error(
`Erro ao atualizar senha do usuário com ID ${userId}:`,
Expand All @@ -135,6 +143,7 @@ export default function UserUpdatePage() {
const handleChangeLogin = (event) => setLogin(event.target.value);

const handleSaveModal = () => setShowSaveModal(true);

const handleSavePasswordModal = () => setShowPasswordSaveModal(true);

const handleSaveCloseDialog = () => {
Expand All @@ -146,6 +155,19 @@ export default function UserUpdatePage() {
const showUserDiv = () => setIsUserVisible(true);
const showPasswordDiv = () => setIsUserVisible(false);

const handleNavigateToContributions = () => {
navigate(`/movimentacoes/contribuicoes/${nomeCompleto}`, {
state: {
userId,
nomeCompleto,
celular,
email,
login,
perfilSelecionado,
},
});
};

return (
<section className="container">
<div className="forms-container-user">
Expand Down Expand Up @@ -193,6 +215,13 @@ export default function UserUpdatePage() {
</label>
)}

<Button
className="contribution-btn"
onClick={handleNavigateToContributions}
>
Histórico de Contribuições
</Button>

<PrimaryButton text="Salvar" onClick={handleSave} />

<Modal alertTitle="Alterações Salvas" show={showSaveModal}>
Expand All @@ -219,20 +248,26 @@ export default function UserUpdatePage() {
label="Nova senha"
value={newPassword}
type={showPasswords ? "text" : "password"}
onChange={(e) => setNewPassword(e.target.value)}
onChange={(e) => { setNewPassword(e.target.value);
const isValidPassword = validaSenha(e.target.value);
setNewPasswordValid(isValidPassword.status);
setPasswordMessage(isValidPassword.message);
}
}
/>
{!isNewPasswordValid && (
<label className="isValid">*Insira uma senha válida</label>
)}

<FieldText
label="Repetir nova senha"
type={showPasswords ? "text" : "password"}
onChange={(e) => setConfirmNewPassword(e.target.value)}
/>

<br />
{!passwordsMatch && confirmPassword && (
{!isNewPasswordValid && (
<span style={{ color: "red" }}>{passwordMessage}</span>
)}

{isNewPasswordValid && !passwordsMatch && confirmPassword && (
<span style={{ color: "red" }}>As senhas não coincidem</span>
)}
<br />
Expand Down
12 changes: 8 additions & 4 deletions src/Pages/Public/MemberShip/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@ import SecondaryButton from "../../../Components/SecondaryButton";
import Modal from "../../../Components/Modal";
import { useNavigate } from "react-router-dom";
import { listOrgans } from "../../../Services/organService";
import { isValidEmail } from "../../../Utils/validators";
import { mascaraTelefone } from "../../../Utils/validators";
import { mascaraCEP } from "../../../Utils/validators";
import {
isValidEmail,
mascaraTelefone,
mascaraCEP,
validarCPF
} from "../../../Utils/validators";

const MemberShip = () => {
const [email, setEmail] = useState("");
Expand Down Expand Up @@ -336,7 +339,8 @@ const MemberShip = () => {

//VALIDAÇÕES
if (isValidEmail(email) === false) erros.email = 1;
if (cpf.length < 14) erros.cpf = 1;
//if (cpf.length < 14) erros.cpf = 1;
if (!validarCPF(cpf)) erros.cpf = 1;
if (rg.length < 7) erros.rg = 1;
//if (cep.length < 9) erros.cep = 1;
//if (telefone.length < 14) erros.telefone = 1;
Expand Down
7 changes: 3 additions & 4 deletions src/Services/memberShipService.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,12 @@ export const updateMemberStatus = async (memberId, formData) => {

export const updateMembership = async (memberId, formData) => {
try {
await APIUsers.patch(`membership/update/${memberId}`, {
const response = await APIUsers.patch(`/membership/update/${memberId}`, {
formData,
});

return false;
return response;
} catch (error) {
return error.response.data.erro;
return error.response;
}
};

Expand Down
3 changes: 2 additions & 1 deletion src/Services/userService.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ export const changePasswordById = async (newPassword, id) => {
// );
export const changePasswordInProfile = async (passwords) => {
try {
await APIUsers.patch(
const response = await APIUsers.patch(
`/users/renew-password`,
{ ...passwords },
{
Expand All @@ -235,6 +235,7 @@ export const changePasswordInProfile = async (passwords) => {
},
}
);
return response;
} catch (error) {
return error;
}
Expand Down
82 changes: 82 additions & 0 deletions src/Utils/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,48 @@ export const mascaraCEP = (cep) => {
return formattedCEP.replace(/(\d{5})(\d)/, "$1-$2");
};

export const validarCPF = (cpf) => {
cpf = cpf.replace(/[^\d]+/g, "");

if (cpf.length !== 11) {
console.error("Erro: CPF deve conter 11 d�gitos");
return false;
}

if (/^(\d)\1+$/.test(cpf)) {
console.error("Erro: CPF n�o pode conter todos d�gitos iguais");
return false;
}

let soma = 0;
for (let i = 0; i < 9; i++) {
soma += parseInt(cpf.charAt(i)) * (10 - i);
}
let resto = (soma * 10) % 11;
if (resto === 10 || resto === 11) {
resto = 0;
}
if (resto !== parseInt(cpf.charAt(9))) {
console.error("Erro: Primeiro d�gito verificador do CPF � inv�lido");
return false;
}

soma = 0;
for (let i = 0; i < 10; i++) {
soma += parseInt(cpf.charAt(i)) * (11 - i);
}
resto = (soma * 10) % 11;
if (resto === 10 || resto === 11) {
resto = 0;
}
if (resto !== parseInt(cpf.charAt(10))) {
console.error("Erro: Segundo d�gito verificador do CPF � inv�lido");
return false;
}

return true;
};

export const handleCpfCnpjInput = (value) => {
const numericValue = value.replace(/\D/g, "");
if (numericValue.length <= 11) {
Expand Down Expand Up @@ -122,3 +164,43 @@ export const mascaraCelular = (celular) => {
.replace(/^(\d{2})(\d)/g, "($1) $2")
.replace(/(\d{5})(\d{4})$/, "$1-$2");
};

export const validaSenha = (novaSenha) => {
const comprimentoMinimo = 8;
const temMaiuscula = /[A-Z]/.test(novaSenha);
const temMinuscula = /[a-z]/.test(novaSenha);
const temNumero = /\d/.test(novaSenha);

if (novaSenha.length < comprimentoMinimo) {
return {
status: false,
message: `A senha deve ter pelo menos ${comprimentoMinimo} caracteres`,
};
}

if (!temMaiuscula) {
return {
status: false,
message: "A senha deve ter pelo menos uma letra maiuscula",
};
}

if (!temMinuscula) {
return{
status: false,
message: "A senha deve ter pelo menos uma letra minuscula",
};
}

if (!temNumero) {
return{
status: false,
message: "A senha deve ter pelo menos um numero",
};
}

return{
status: true,
message: "Senha válida",
};
};