Skip to content

Commit

Permalink
fix: Fix login as an admin
Browse files Browse the repository at this point in the history
  • Loading branch information
fadhlaouir committed Mar 15, 2024
1 parent 6e70392 commit 486da66
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 22 deletions.
38 changes: 17 additions & 21 deletions src/controllers/AuthController.js
Original file line number Diff line number Diff line change
Expand Up @@ -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é",
});
}

Expand All @@ -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",
Expand All @@ -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({
Expand Down
2 changes: 1 addition & 1 deletion src/models/UserModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 486da66

Please sign in to comment.