From 486da66d84a166b143f9556c465987070399a46e Mon Sep 17 00:00:00 2001 From: fadhlaouir Date: Fri, 15 Mar 2024 12:42:56 +0100 Subject: [PATCH] fix: Fix login as an admin --- src/controllers/AuthController.js | 38 ++++++++++++++----------------- src/models/UserModel.js | 2 +- 2 files changed, 18 insertions(+), 22 deletions(-) diff --git a/src/controllers/AuthController.js b/src/controllers/AuthController.js index ba1af3e..10cac7d 100644 --- a/src/controllers/AuthController.js +++ b/src/controllers/AuthController.js @@ -156,23 +156,17 @@ const signIn = async (req, res) => { */ const adminSignIn = async (req, res) => { try { - // Find the user by email - const foundUser = await User.findOne({ email: req.body.email }); + const { email, password } = req.body; - // If user not found, return error - if (!foundUser) { - return res.status(403).json({ - success: false, - message: "Échec de l'authentification, utilisateur introuvable", - }); - } + // Find the user by email + const foundUser = await User.findOne({ email }); - // Check if password matches - const passwordMatches = await foundUser.comparePassword(req.body.password); - if (!passwordMatches) { + // If user not found or password doesn't match, return error + if (!foundUser || !(await foundUser.comparePassword(password))) { return res.status(403).json({ success: false, - message: "Échec de l'authentification, Mot de passe erroné", + message: + "Échec de l'authentification, utilisateur introuvable ou mot de passe erroné", }); } @@ -185,12 +179,9 @@ const adminSignIn = async (req, res) => { }); } - // Check user - const userRole = ['is_admin', 'is_manager', 'is_doctor', 'is_nurse']; - - const userCanAccess = userRole.includes(foundUser.role); - - if (!userCanAccess) { + // Check user role + const allowedRoles = ['is_admin', 'is_manager']; + if (!allowedRoles.includes(foundUser.role)) { return res.status(403).json({ success: false, message: "Vous n'êtes pas autorisé à vous connecter", @@ -206,11 +197,16 @@ const adminSignIn = async (req, res) => { }, ); - // Return success response with token and user information return res.json({ success: true, token, - user: foundUser, + // return user information without password field + user: { + _id: foundUser._id, + email: foundUser.email, + fullName: foundUser.fullName, + role: foundUser.role, + }, }); } catch (error) { return res.status(500).json({ diff --git a/src/models/UserModel.js b/src/models/UserModel.js index c76ad4b..d09416a 100644 --- a/src/models/UserModel.js +++ b/src/models/UserModel.js @@ -14,7 +14,7 @@ const UserSchema = new Schema({ fullName: String, photo: String, is_active: Boolean, - role: { type: String, require: true }, // is_manager, is_admin, is_doctor, is_nurse, is_patient, is_employee + role: { type: String, require: true }, // is_manager, is_admin, is_user confirmationCode: String, resetPasswordToken: String, resetPasswordExpires: String,