Skip to content

Commit

Permalink
Merge pull request #51 from ICEI-PUC-Minas-PPLCC-TI/develop
Browse files Browse the repository at this point in the history
Adicionando edição de usuário
  • Loading branch information
andreeluis authored Dec 2, 2023
2 parents 0365716 + de3c81b commit 701fb81
Show file tree
Hide file tree
Showing 4 changed files with 282 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/assets/css/profile.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.edit-profile {
display: flex;
flex-direction: row;
justify-content: space-around;
flex-wrap: wrap;
}

.profile-form,
.change-password {
min-width: 300px;
}

#delete-account button{
background-color: var(--red);
}
14 changes: 14 additions & 0 deletions src/assets/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,20 @@ function logout(event) {
location.reload();
}

function usernameExists(username) {
return fetch(`${apiURL}/users?username=${username}`)
.then(response => response.json())
.then(data => data.length > 0 ? true : false)
.catch(error => console.error('Falha ao verificar se o usuário existe:', error));
}

function emailExists(email) {
return fetch(`${apiURL}/users?email=${email}`)
.then(response => response.json())
.then(data => data.length > 0 ? true : false)
.catch(error => console.error('Falha ao verificar se o email existe:', error));
}

function generateUUID(qtde) {
uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
Expand Down
142 changes: 142 additions & 0 deletions src/assets/js/profile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
let actualUser;
const editForm = document.querySelector('#profile-form');
const editPassword = document.querySelector('#change-password');
const deleteAccount = document.querySelector('#delete-account');

window.addEventListener('load', loadContent, false);
editForm.addEventListener('submit', editProfile, false);
editPassword.addEventListener('submit', changePassword, false);
deleteAccount.addEventListener('submit', deleteUser, false);


async function loadUser() {
try { actualUser = await (await fetch(`${apiURL}/users/${user.id}`)).json()}
catch (error) { console.error('Falha ao carregar usuário:', error)}
}


async function loadContent() {
if (!user) {
window.location.href = '/login';
return;
}

await loadUser();

document.querySelector('#username').value = actualUser.username;
document.querySelector('#email').value = actualUser.email;
}

async function editProfile(event) {
event.preventDefault();

const username = document.querySelector('#username').value;
const email = document.querySelector('#email').value;

if (username.length < 3) {
alert('O nome de usuário deve conter no mínimo 3 caracteres!');
return;
}

if (await usernameExists(username) && username !== actualUser.username) {
alert('O nome de usuário já está em uso!');
return;
}

if (await emailExists(email) && email !== actualUser.email) {
alert('O email já está em uso!');
return;
}


try {
const response = await fetch(`${apiURL}/users/${user.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, email }),
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

sessionStorage.setItem('user', JSON.stringify({ "id":user.id, "name":username }));

window.location.href = 'index.html';
}
catch (error) {
console.error('Falha ao editar o perfil:', error);
}

}

async function changePassword(event) {
event.preventDefault();

const oldPassword = document.querySelector('#old-password').value;
const newPassword = document.querySelector('#password').value;
const confirmPassword = document.querySelector('#password-confirm').value;

if (oldPassword !== actualUser.password) {
alert('Senha atual incorreta!');
return;
}

if (newPassword.length < 6) {
alert('A senha deve conter no mínimo 6 caracteres!');
return;
}

if (newPassword !== confirmPassword) {
alert('As senhas não coincidem!');
return;
}

try {
const response = await fetch(`${apiURL}/users/${user.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ password: newPassword }),
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

sessionStorage.removeItem('user');

window.location.href = 'login.html';
}
catch (error) {
console.error('Falha ao alterar a senha:', error);
}
}


async function deleteUser(event) {
event.preventDefault();

const confirmDelete = window.confirm(`Você realmente quer excluir sua conta?`);
if (user && confirmDelete) {
try {
const response = await fetch(`${apiURL}/users/${user.id}`, {
method: 'DELETE'
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

sessionStorage.removeItem('user');

window.location.href = 'login.html';
}
catch (error) {
console.error('Falha ao deletar o usuário:', error);
}
}
}
111 changes: 111 additions & 0 deletions src/profile.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<!DOCTYPE html>
<html lang="pt-br">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous" />
<link rel="stylesheet" href="assets/css/style.css">
<link rel="stylesheet" href="assets/css/profile.css">

<title>Arduino HUB</title>
</head>

<body>
<header>
<a href="index.html" class="logo"> Arduino HUB </a>

<!-- Hamburger icon -->
<input class="side-menu" type="checkbox" id="side-menu" />
<label class="hamb" for="side-menu"><span class="hamb-line"></span></label>

<!-- Menu -->
<nav>
<ul class="menu">
<li><a href="#">Projetos</a></li>
<li><a href="#">Ferramentas</a></li>
<li><a href="#">Fórum</a></li>
<li class="login"><a href="login.html">Login</a></li>
<li class="my-account dropdown-menu">
<a><i class="fas fa-user"></i></a>

<ul class="dropdown-content">
<li><a href="profile.html">Minha Conta</a></li>
<li><a href="" id="logout">Sair</a></li>
</ul>
</li>
</ul>
</nav>
</header>

<main>
<h2>Edição de Perfil</h2>

<section class="edit-profile">
<section class="profile-form">
<h3>Informações Pessoais</h3>

<form id="profile-form">
<div class="input-field">
<label for="username">Usuário</label>
<input min="3" type="text" name="username" id="username">
</div>

<div class="input-field">
<label for="email">E-mail</label>
<input type="email" name="email" id="email">
</div>

<button>Editar</button>
</form>

<form id="delete-account">
<button>Excluir conta</button>
</form>

</section>

<section class="change-password">
<h3>Alterar senha</h3>

<form id="change-password">
<div class="input-field">
<label for="old-password">Senha atual</label>
<input minlength="6" type="password" name="old-password" id="old-password">
</div>

<div class="input-field">
<label for="password">Nova senha</label>
<input minlength="6" type="password" name="password" id="password">
</div>

<div class="input-field">
<label for="password-confirm">Confirme a nova senha</label>
<input type="password" name="password-confirm" id="password-confirm">
</div>

<button>Alterar senha</button>
</form>
</section>
</section>
</main>

<footer>
<section class="about">
<h3>Sobre</h3>

<p>Projeto realizado pelos alunos de Ciência da Computação da PUC Minas, para a disciplina de Trabalho Interdisciplinar: Aplicações WEB.</p>
<p>Desenvolvemos um site educacional onde o usuário pode navegar e encontrar diversas informações relacionadas ao Arduino. Dentro dessas informações temos abas como projetos, fórum, ferramentas etc.</p>
</section>

<section>
<h3>Links</h3>
<li>Documentação do Projeto: <a href="docs/index.html">TI DOCS</a></li>
</section>
</footer>
</body>
<script src="assets/js/index.js"></script>
<script src="assets/js/profile.js"></script>

</html>

0 comments on commit 701fb81

Please sign in to comment.