Skip to content

Commit

Permalink
Merge pull request #3 from fga-eps-mds/14-recover-password
Browse files Browse the repository at this point in the history
[feat/14] - recover password.
  • Loading branch information
yukioz authored Jul 12, 2024
2 parents d2115f5 + bbd6020 commit 3e3b527
Show file tree
Hide file tree
Showing 10 changed files with 308 additions and 20 deletions.
2 changes: 1 addition & 1 deletion .github/PULL_REQUEST_TEMPLATE.md.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Issue: closes: #X
# Issue: closes: #

## descrição

Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ yarn-error.log

# Arquivos de configuração de IDEs
.idea
.vscode
.vscode
.env
2 changes: 1 addition & 1 deletion Template-Colection/SENTINELA-COLETION.json

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions .env → env
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
Copie esse conteúdo para um .env

NODE_ENV=development
MONGO_URI=mongodb://root:password@mongodb:27017/
MONGO_INITDB_ROOT_USERNAME=root
MONGO_INITDB_ROOT_PASSWORD=password
DB_HOST=mongodb
PORT=3001
# host=
# email=
# pass =
EMAIL= [email protected]
EMAIL_USER = (usuário ou email do email)
PASSWORD = (senha do email)
SECRET = S3T1N3L3L4
111 changes: 110 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.19.2",
"mongoose": "^8.3.5"
"generate-password": "^1.7.1",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.3.5",
"nodemailer": "^6.9.14"
},
"devDependencies": {
"nodemon": "^3.1.0"
Expand Down
101 changes: 92 additions & 9 deletions src/Controllers/userController.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const express = require('express');
const router = express.Router();
const User = require('../Models/userSchema');
const bcrypt = require('bcrypt');
const { generateToken } = require('../Utils/token');
const { sendEmail } = require('../Utils/email');
const generator = require('generate-password');

const salt = bcrypt.genSaltSync();

Expand All @@ -23,13 +24,17 @@ const login = async (req, res) => {
const user = await User.findOne({ email: email });

if (!user) {
return res.status(400).send({ error: 'Invalid email or password' });
} else if(!bcrypt.compareSync(password, user.password)){
return res.status(400).send({ error: 'Invalid email or password' });
return res.status(400).send({ error: 'Email ou senha inválidos.' });
} else if (!bcrypt.compareSync(password, user.password)) {
return res.status(400).send({ error: 'Email ou senha inválidos.' });
}

return res.status(200).send(user);
// res.send({ user: user });

const token = generateToken(user._id)

return res.status(200).json({
token,
user
});
} catch (error) {
res.status(500).send(error);
}
Expand Down Expand Up @@ -57,12 +62,20 @@ const getUserById = async (req, res) => {
};

const patchUser = async (req, res) => {
const userId = req.params.id;

try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
if (!user) {
return res.status(404).send();
}

if(userId !== req.userId) {
return res.status(403).json({
mensagem: 'O token fornecido não tem permissão para finalizar a operação'
})
}

user.updatedAt = new Date();

await user.save();
Expand All @@ -85,11 +98,81 @@ const deleteUser = async (req, res) => {
}
};

const recoverPassword = async (req, res) => {
const { email } = req.body;

try {
const user = await User.findOne({ email });

if (!user) {
return res.status(404).json({ mensagem: 'Usuário não encontrado.' });
}

// // Gerar token com expiração curta (1 hora)
// const token = generateToken(user._id); // caso precise...

const temp_pass = generator.generate({
length: 6,
numbers: true
})

user.password = bcrypt.hashSync(temp_pass, salt)

await user.save()

const bodyEmail = `
Sua nova senha temporária é:
<br />
${temp_pass}
`;
const sended = await sendEmail(user.email, 'Redefinição de senha', bodyEmail);

if (!sended) {
return res.json({ mensagem: 'Falha ao enviar email.' });
}

return res.json({ mensagem: 'Email enviado com instruções para redefinir sua senha.' });
} catch (error) {
console.error('Erro ao solicitar redefinição de senha:', error);
return res.status(500).json({ mensagem: 'Erro interno ao processar solicitação.' });
}
};

const changePassword = async (req, res) => {
const { new_password } = req.body;
const userId = req.params.id;

try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).send();
}

if(userId !== req.userId) {
return res.status(403).json({
mensagem: 'O token fornecido não tem permissão para finalizar a operação'
})
}

user.password = bcrypt.hashSync(new_password, salt)
await user.save()

return res.status(200).json({
mensagem: "senha alterada com sucesso."
});
} catch (error) {
return res.status(500).send(error);
}
}


module.exports = {
signUp,
login,
getUsers,
getUserById,
deleteUser,
patchUser
patchUser,
recoverPassword,
changePassword
};
40 changes: 40 additions & 0 deletions src/Utils/email.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const nodemailer = require('nodemailer');

const {
EMAIL_USER,
EMAIL,
PASSWORD
} = process.env;

// Configuração do transporte de email
const transporter = nodemailer.createTransport({
host: 'sandbox.smtp.mailtrap.io',
port: 2525,
auth: {
user: EMAIL_USER,
pass: PASSWORD
},
debug: true, // Ativa o modo de depuração
logger: true // Ativa o modo de registro
});

const sendEmail = async (destiny, subject, bodyEmail) => {

try {
const info = await transporter.sendMail({
from: EMAIL,
to: destiny,
subject: subject,
html: bodyEmail
});
return 1
} catch (error) {
console.error('Erro ao enviar email:', error);
return 0;
}

};

module.exports = {
sendEmail
}
Loading

0 comments on commit 3e3b527

Please sign in to comment.