Skip to content

Commit

Permalink
Merge pull request #12 from fga-eps-mds/fix-beackend-tests
Browse files Browse the repository at this point in the history
Fix beackend tests
  • Loading branch information
guipeeix7 authored Dec 16, 2024
2 parents bb3083e + 61327b4 commit 698de8f
Show file tree
Hide file tree
Showing 8 changed files with 108 additions and 87 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ package-lock.json
.idea
.vscode
.env
.vs/
.vs/
8 changes: 4 additions & 4 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"dotenv": "^16.4.5",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.2.1",
"express": "^4.19.2",
Expand Down
8 changes: 6 additions & 2 deletions src/Controllers/membershipController.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,12 @@ const createMembershipForm = async (req, res) => {

const membership = new Membership(formData);

membership.password = await bcrypt.hash(formData.senha, saltRounds);
const temp_pass = generator.generate({
length: 8,
numbers: true,
});

membership.password = bcrypt.hashSync(temp_pass, saltRounds);

await membership.save();
return res.status(201).send(membership);
Expand All @@ -54,7 +59,6 @@ const createMembershipForm = async (req, res) => {
}
};


const getMembershipForm = async (req, res) => {
try {
const sindRole = await Role.findOne({ name: "sindicalizado" });
Expand Down
84 changes: 22 additions & 62 deletions src/Controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,45 +130,31 @@ const getLoggedUserId = async (req, res) => {
if (!token) {
return res.status(401).json({ message: "Token não fornecido" });
}

try {
const decoded = jwt.verify(token, SECRET);
const decoded = jwt.verify(token, SECRET ?? "S3T1N3L3L4");

userId = decoded.id;
} catch (err) {
console.log(err);
return res.status(401).json({ message: "Token inválido ou expirado" });
return -1;
}
return userId;
};

const getLoggedUser = async (req, res) => {
//let userId = await this.getLoggedUserId(req,res);

const token = req.headers.authorization?.split(" ")[1];

if (!token) {
return res.status(401).json({ message: "Token não fornecido" });
}

try {
const decoded = jwt.verify(token, SECRET);

userId = decoded.id;
} catch (err) {
console.log(err);

return res.status(401).json({ message: "Token inválido ou expirado" });
}
const userId = await getLoggedUserId(req, res);

try {
const user = await User.findById(userId).populate("role");
if (!user) {
return res.status(404).send();
}
res.status(200).send(user);
return res.status(200).send(user);
} catch (error) {
res.status(500).send(error);
// return res.status(500).send(error);
return res
.status(500)
.send({ message: error.message || "Erro interno no servidor" });
}
};

Expand All @@ -182,13 +168,6 @@ const patchUser = async (req, res) => {
return res.status(404).send();
}

// Verifique se o usuário tem permissão para atualizar os dados
// if (userId !== req.userId) {
// return res.status(457).json({
// mensagem: 'O token fornecido não tem permissão para finalizar a operação'
// });
// }

Object.assign(user, req.body.updatedUser);

user.updatedAt = new Date();
Expand Down Expand Up @@ -323,9 +302,9 @@ const changePassword = async (req, res) => {
try {
const user = await User.findById(userId);

if (!user) {
return res.status(404).send({ message: "usuário não encontrado" });
}
// if (!user) {
// return res.status(404).send({ message: "usuário não encontrado" });
// }

user.password = bcrypt.hashSync(newPassword, salt);

Expand All @@ -348,38 +327,20 @@ const changePasswordInProfile = async (req, res) => {

const userId = await getLoggedUserId(req, res);

try {
const user = await User.findById(userId);

if (!user) {
return res.status(404).send();
}
if (!bcrypt.compareSync(old_password, user.password)) {
return res.status(401).json({
mensagem: "Senha atual incorreta.",
});
}

user.password = bcrypt.hashSync(new_password, salt);
await user.save();
const user = await User.findById(userId);

return res.status(200).json({
mensagem: "senha alterada com sucesso.",
if (!bcrypt.compareSync(old_password, user.password)) {
return res.status(401).json({
mensagem: "Senha atual incorreta.",
});
} catch (error) {
return res.status(500).send({ myerror: error });
}
};
const teste = async (req, res) => {
try {
// eslint-disable-next-line no-unused-vars
const { status } = req.query;
const membership = await Membership.find({ religion: { $ne: null } });
return res.status(200).send(membership);
} catch (error) {
return res.status(400).send({ error });
}
return res.status(201).send("Xabl2");

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

return res.status(200).json({
mensagem: "senha alterada com sucesso.",
});
};

module.exports = {
Expand All @@ -394,5 +355,4 @@ module.exports = {
recoverPassword,
changePassword,
changePasswordInProfile,
teste,
};
31 changes: 14 additions & 17 deletions src/Utils/initDatabase.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
require("dotenv").config();

// ./utils/initRoles.js
const mongoose = require("mongoose");
const Role = require("../Models/roleSchema"); // Ajuste o caminho conforme necessário
const User = require("../Models/userSchema");
const bcrypt = require("bcryptjs");

const saltRounds = 13;
const salt = bcrypt.genSaltSync();

const initializeRoles = async () => {
const roles = [
Expand Down Expand Up @@ -55,6 +53,7 @@ const initializeRoles = async () => {
];

try {
// Verificar se a conexão está aberta antes de executar
if (mongoose.connection.readyState === 1) {
for (const roleData of roles) {
const existingRole = await Role.findOne({
Expand All @@ -76,7 +75,9 @@ const initializeRoles = async () => {
}

try {
// Verificar se a conexão está aberta antes de executar
if (mongoose.connection.readyState === 1) {
// Busca o user 'administrador'
const adminRole = await Role.findOne({ name: "administrador" });
if (!adminRole) {
console.error(
Expand All @@ -92,19 +93,18 @@ const initializeRoles = async () => {
return;
}

// Verifica se o usuário administrador já existe
const existingAdmin = await User.findOne({
email: process.env.Admin_email,
email: "admin@admin.com",
});
if (!existingAdmin) {
const hashedPassword = await bcrypt.hash(
process.env.Admin_senha,
saltRounds
);
const hashedPassword = await bcrypt.hash("senha", salt); // Altere a senha padrão conforme necessário

// Cria o usuário administrador
const adminUser = new User({
name: "Admin",
email: process.env.Admin_email,
phone: process.env.Admin_celular,
email: "admin@admin.com",
phone: "1234567890",
status: true,
password: hashedPassword,
role: adminRole._id,
Expand All @@ -118,19 +118,16 @@ const initializeRoles = async () => {
}

const ExistingSindicalizado = await User.findOne({
email: process.env.User_email,
email: "user@user.com",
});
if (!ExistingSindicalizado) {
const hashedPassword = await bcrypt.hash(
process.env.User_senha,
saltRounds
); // Altere a senha padrão conforme necessário
const hashedPassword = await bcrypt.hash("senha", salt); // Altere a senha padrão conforme necessário

// Cria o usuário administrador
const sindUser = new User({
name: "User",
email: process.env.User_email,
phone: process.env.User_celular,
email: "user@user.com",
phone: "61981818181",
status: true,
password: hashedPassword,
role: userRole,
Expand Down
1 change: 1 addition & 0 deletions src/__tests__/membershipController.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ describe("MembershipController Test Suite", () => {
describe("POST /membership/create", () => {
it("should create a new membership", async () => {
const newMembership = generateMembershipData("001");
// console.log("Chaaaama no grau", newMembership);
const response = await createMembership(newMembership);
expect(response.status).toBe(201);
expect(response.body).toHaveProperty("_id");
Expand Down
59 changes: 59 additions & 0 deletions src/__tests__/userController.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,63 @@ describe("User Controller Tests", () => {
expect(res.status).toBe(404);
expect(res.body).toHaveProperty("mensagem", "Usuário não encontrado.");
});

it("Deve retornar os dados do usuário logado (getLoggedUser)", async () => {
const res = await request(app)
.get("/user")
.set("Authorization", `Bearer ${authToken}`);

expect(res.status).toBe(200);
expect(res.body).toHaveProperty("_id");
});

it("should return 401 if token is not provided", async () => {
const res = await request(app).get("/user");

expect(res.status).toBe(401);
expect(res.body).toEqual({ mensagem: "Tokem não fornecido." });
});

it("should update a user", async () => {
const res = await request(app)
.patch(`/users/renew-password`)
.set("Authorization", `Bearer ${authToken}`)
.send({ old_password: "senha", new_password: "senha2" });

expect(res.status).toBe(200);
expect(res.body).toEqual({ mensagem: "senha alterada com sucesso." });
});

it("should not update a user", async () => {
const res = await request(app)
.patch(`/users/renew-password`)
.set("Authorization", `Bearer ${authToken}`)
.send({ old_password: "senha234", new_password: "senha2" });

expect(res.status).toBe(401);
expect(res.body).toEqual({ mensagem: "Senha atual incorreta." });
});

it("deve alterar a senha com sucesso", async () => {
const response = await request(app)
.patch(`/users/change-password/${userId}`)
.send({
newPassword: "senha",
});

expect(response.status).toBe(200);
expect(response.body).toEqual({
mensagem: "senha alterada com sucesso.",
});
});

it("deve alterar a senha sem sucesso", async () => {
const response = await request(app)
.patch("/users/change-password/invalido")
.send({
newPassword: "senha",
});

expect(response.status).toBe(500);
});
});

0 comments on commit 698de8f

Please sign in to comment.