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

redone e write permissions to routes #6

Merged
merged 7 commits into from
Jan 30, 2025
Merged
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
10 changes: 10 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# CHANGE ALL VARIABLES ON DEPLOY

NODE_ENV=development
MONGO_URI=mongodb://root:password@financedb:27017/
MONGO_INITDB_ROOT_USERNAME=root
MONGO_INITDB_ROOT_PASSWORD=password
DB_HOST=financedb
PORT=3002
BACK_USERS_URL=http://127.0.0.1:3001/
SECRET = S3T1N3L3L4
2 changes: 0 additions & 2 deletions src/Controllers/bankAccountController.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
const createBankAccount = async (req, res) => {
try {
// Log dos dados recebidos para depuração
console.log("Dados recebidos:", req.body);

Check warning on line 8 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement

// Acessando dados diretamente
const formData = req.body.formData || {}; // Fallback para objeto vazio se formData estiver ausente
Expand All @@ -30,11 +30,11 @@
// Criação de uma nova conta bancária
const bankAccount = new BankAccount(formData);
await bankAccount.save(); // Salvando a conta bancária no banco de dados
console.log("Conta bancária criada com sucesso:", bankAccount);

Check warning on line 33 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(201).send(bankAccount); // Enviando resposta de sucesso
} catch (error) {
// Log do erro para depuração
console.error("Erro ao criar conta bancária:", error.message);

Check warning on line 37 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(400).send({ error: error.message }); // Enviando erro caso ocorra
}
};
Expand All @@ -60,15 +60,13 @@
}
res.status(200).json(bankAccount); // Enviando conta bancária encontrada
} catch (error) {
console.error("Erro ao buscar conta bancária:", error.message);

Check warning on line 63 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(500).send({ error: error.message || "Erro interno" }); // Garantindo que a resposta tenha a chave 'error'
}
};


const deleteBankAccount = async (req, res) => {
try {

const { id } = req.params;

if (!id || !mongoose.Types.ObjectId.isValid(id)) {
Expand All @@ -81,7 +79,7 @@
res.status(200).send({ message: "Conta deletada com sucesso" });
} catch (error) {
// Log do erro para depuração
console.error("Erro ao deletar conta bancária:", error.message);

Check warning on line 82 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(500).send({ error: error.message }); // Enviando mensagem de erro
}
};
Expand All @@ -94,7 +92,7 @@
}

// Log dos dados recebidos
console.log("Dados recebidos para atualização:", req.body);

Check warning on line 95 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement

// Atualizar apenas os campos fornecidos
const bankAccount = await BankAccount.findByIdAndUpdate(id, req.body, {
Expand All @@ -107,7 +105,7 @@

res.status(200).send(bankAccount);
} catch (error) {
console.error("Erro ao atualizar conta bancária:", error.message);

Check warning on line 108 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(500).send({ error: error.message });
}
};
Expand Down
1 change: 0 additions & 1 deletion src/Controllers/financialMovementsController.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
const FinancialMovements = require("../Models/financialMovementsSchema");

const validateCPF = (cpf) => {

Check failure on line 3 in src/Controllers/financialMovementsController.js

View workflow job for this annotation

GitHub Actions / lint

'validateCPF' is assigned a value but never used
return /\d{3}\.\d{3}\.\d{3}-\d{2}/.test(cpf);
};


const createFinancialMovements = async (req, res) => {
try {
console.log("Dados recebidos:", req.body);

Check warning on line 9 in src/Controllers/financialMovementsController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
const financialMovementsData = req.body.financialMovementsData || {};
if (!financialMovementsData) {
return res.status(400).send({ error: "No data provided" });
Expand All @@ -15,8 +14,8 @@
/* if (!validateCPF(financialMovementsData.cpFCnpj)) {
return res.status(400).send({ error: "Invalid CPF" });
} */
if (!financialMovementsData.contaOrigem) {

Check failure on line 17 in src/Controllers/financialMovementsController.js

View workflow job for this annotation

GitHub Actions / lint

Delete `··`
throw new Error("Database error");

Check failure on line 18 in src/Controllers/financialMovementsController.js

View workflow job for this annotation

GitHub Actions / lint

Delete `·`
}

// Criação da movimentação financeira
Expand All @@ -27,7 +26,7 @@

res.status(201).send(financialMovement);
} catch (error) {
console.error("Error creating financial movement:", error.message);

Check warning on line 29 in src/Controllers/financialMovementsController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
return res.status(400).send({ error: error.message });
}
};
Expand Down
10 changes: 5 additions & 5 deletions src/Controllers/financialReportController.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
);
res.sendFile(filePath, (err) => {
if (err) {
console.error("Erro ao enviar o arquivo:", err);

Check warning on line 22 in src/Controllers/financialReportController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(500).send("Erro ao enviar o arquivo.");
} else {
fs.unlinkSync(filePath); // Remover arquivo após envio
Expand Down Expand Up @@ -64,9 +64,9 @@
const query = {
sitPagamento: sanitizedSitPagamento,
datadeVencimento: {
$gte: new Date(dataInicio),
$lte: new Date(dataFinal),
}
$gte: new Date(dataInicio),
$lte: new Date(dataFinal),
},
};
if (sanitizedNomeOrigem) query.nomeOrigem = sanitizedNomeOrigem;
if (sanitizedContaOrigem) query.contaOrigem = sanitizedContaOrigem;
Expand All @@ -80,7 +80,7 @@
if (req.body.contaOrigem) {
query.contaOrigem = req.body.contaOrigem;
}

if (sanitizedSitPagamento) {
const today = new Date(); // Data atual

Expand All @@ -93,7 +93,7 @@
{ datadePagamento: { $eq: null } },
{ datadePagamento: { $gt: today } },
];
}else {
} else {
delete query.datadePagamento;
}
}
Expand Down
30 changes: 30 additions & 0 deletions src/Middlewares/accessControlMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const jwt = require("jsonwebtoken");

const checkPermissions = (permissionName) => {
return async (req, res, next) => {
try {
const decoded = jwt.decode(
req.headers.authorization?.split(" ")[1]
);
if (!decoded) {
return res
.status(401)
.json({ mensagem: "Tokem não fornecido." });
}
const permission = decoded.permissions.find(
(perm) => perm === permissionName
);

if (!permission) {
return res
.status(400)
.send("user has no permission to access resource");
}
next();
} catch (error) {
next(error);
}
};
};

module.exports = { checkPermissions };
32 changes: 22 additions & 10 deletions src/Models/csvGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ const formatNumericDate = (date) => {
return `${day}/${month}/${year}`;
};

const generateFinancialReportCSV = (financialMovements, filePath, includeFields) => {
const generateFinancialReportCSV = (
financialMovements,
filePath,
includeFields
) => {
return new Promise((resolve, reject) => {
try {
if (financialMovements.length === 0) {
Expand All @@ -22,7 +26,10 @@ const generateFinancialReportCSV = (financialMovements, filePath, includeFields)
}

const allFields = {
tipoDocumento: { label: "Tipo Documento", value: "tipoDocumento" },
tipoDocumento: {
label: "Tipo Documento",
value: "tipoDocumento",
},
valorBruto: { label: "Valor Bruto", value: "valorBruto" },
valorLiquido: { label: "Valor Líquido", value: "valorLiquido" },
contaOrigem: { label: "Conta Origem", value: "contaOrigem" },
Expand All @@ -37,37 +44,42 @@ const generateFinancialReportCSV = (financialMovements, filePath, includeFields)
label: "Data de Pagamento",
value: (row) => formatNumericDate(row.datadePagamento),
},
formaPagamento: { label: "Forma de Pagamento", value: "formaPagamento" },
formaPagamento: {
label: "Forma de Pagamento",
value: "formaPagamento",
},
sitPagamento: {
label: "Situação de Pagamento",
value: (row) => {
// Verificar se a linha ou o campo de data está ausente ou inválido
if (!row || row.datadePagamento == null) {
console.log("Linha sem data de pagamento:", row); // Log para debugar
return "Não pago"; // Retorna 'Não pago' se não houver data
return "Não pago"; // Retorna 'Não pago' se não houver data
}

// Verificar se a data é válida
const paymentDate = new Date(row.datadePagamento);
if (isNaN(paymentDate.getTime())) {
console.log("Data inválida:", row.datadePagamento); // Log para debugar
return "Não pago"; // Retorna 'Não pago' se a data for inválida
return "Não pago"; // Retorna 'Não pago' se a data for inválida
}

const today = new Date();
return paymentDate <= today ? "Pago" : "Não pago";
},
},

descricao: { label: "Descrição", value: "descricao" },
};

if (!includeFields || includeFields.length === 0) {
fs.writeFileSync(filePath, "");
return resolve();
}

const fields = includeFields.map((field) => allFields[field]).filter(Boolean);
const fields = includeFields
.map((field) => allFields[field])
.filter(Boolean);

if (fields.length === 0) {
fs.writeFileSync(filePath, "");
Expand Down
Loading
Loading