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

Mohammed fix authentication error #20

Merged
merged 3 commits into from
Dec 28, 2024
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
Binary file not shown.
Binary file not shown.
2 changes: 2 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ const cors = require('cors');
const favicon = require('express-favicon');
const logger = require('morgan');


const connectToDb = require('./db/connectToDb.js');

connectToDb();


const mainRouter = require('./routes/mainRouter.js');
const authRouter = require('./routes/authRouter.js');
const usersRoute = require('./routes/usersRouter.js');
Expand Down
46 changes: 23 additions & 23 deletions src/controllers/authController.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const asyncHandler = require("express-async-handler");
const bcrypt = require("bcryptjs");
const {User, validateRegisterUser, validateLoginUser} = require("../models/User");
const Group = require('../models/Group');
// const Group = require('../models/Group');


//Register
Expand All @@ -26,24 +26,24 @@ const Group = require('../models/Group');
}

// 3- If the user is not an admin, assign them to a group
let group = null;
if (req.body.role !== 'admin') {
// Check if the group exists by its name
group = await Group.findOne({ name: req.body.groupName });

if (!group) {
// If the group doesn't exist, create it
group = new Group({
name: req.body.groupName,
});
try {
// Save the new group
await group.save();
} catch (err) {
return res.status(500).json({ message: "Failed to create group: " + err.message });
}
}
}
// let group = null;
// if (req.body.role !== 'admin' && req.body.groupName) {
// // Only check for the group if the role is not admin and groupName is provided
// group = await Group.findOne({ name: req.body.groupName });

// if (!group) {
// // If the group doesn't exist, create it
// group = new Group({
// name: req.body.groupName,
// });
// try {
// // Save the new group
// await group.save();
// } catch (err) {
// return res.status(500).json({ message: "Failed to create group: " + err.message });
// }
// }
// }

// 4- Hash the password
const salt = await bcrypt.genSalt(10);
Expand All @@ -55,9 +55,9 @@ const Group = require('../models/Group');
last_name: req.body.last_name,
email: req.body.email,
password: hashedPassword,
role: req.body.role || 'student', // Default role is student
// role: req.body.role || 'student', // Default role is student
isAdmin: req.body.role === 'admin', // If role is 'admin', set isAdmin to true
groupId: group ? group._id : null, // Only assign a group if the user is not an admin
// groupId: group ? group._id : null, // Only assign a group if the user is not an admin
});

try {
Expand Down Expand Up @@ -117,8 +117,8 @@ const Group = require('../models/Group');
res.status(200).json({
_id: user._id,
isAdmin: user.isAdmin,
role: user.role, // Send role to the frontend
groupId: user.groupId, // Send groupId to the frontend
// role: user.role, // Send role to the frontend
// groupId: user.groupId, // Send groupId to the frontend
profilePhoto: user.profilePhoto,
token,
first_name: user.first_name, // Send the JWT token
Expand Down
45 changes: 23 additions & 22 deletions src/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,30 +50,31 @@ const UserSchema = new mongoose.Schema({
isAccountVerified: {
type:Boolean,
default: false,
},
role: {
type: String,
enum: ['student', 'mentor', 'admin'], // Roles allowed
default: 'student', // Default role is student
},
groupId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Group', // Reference to a Group collection
required: function() { return this.role !== 'admin'; },
},
// },
// role: {
// type: String,
// enum: ['student', 'mentor', 'admin'], // Roles allowed
// default: 'student', // Default role is student
// },
// groupId: {
// type: mongoose.Schema.Types.ObjectId,
// ref: 'Group', // Reference to a Group collection
// required: function() { return this.role !== 'admin'; },
// },

}, {
timestamps: true,
},
},
{ timestamps: true }

});
);

// Generate Auth Token
UserSchema.methods.generateAuthToken = function() {
return jwt.sign(
{
id: this._id,
role: this.role,
groupId: this.groupId || null, // Admin will have null groupId
// role: this.role,
// groupId: this.groupId || null, // Admin will have null groupId
isAdmin: this.isAdmin
},
process.env.JWT_SECRET,
Expand All @@ -91,12 +92,12 @@ function validateRegisterUser(obj) {
last_name: Joi.string().trim().min(2).max(100).required(),
email: Joi.string().trim().min(5).max(100).required().email(),
password: Joi.string().trim().min(8).required(),
role: Joi.string().valid('student', 'mentor', 'admin').optional(), // role can be passed
groupName: Joi.string().when('role', {
is: Joi.not('admin'), // Only require groupName if the role is not 'admin'
then: Joi.required(),
otherwise: Joi.optional()
}),
// role: Joi.string().valid('student', 'mentor', 'admin').optional(), // role can be passed
// groupName: Joi.string().when('role', {
// is: Joi.not('admin'), // Only require groupName if the role is not 'admin'
// then: Joi.optional(),
// otherwise: Joi.optional()
// }),
});
return schema.validate(obj);
}
Expand Down
1 change: 1 addition & 0 deletions src/routes/usersRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const photoUpload = require("../middlewares/photoUpload");
// api/users/photo-upload
router.route("/photo-upload")
.post(verifyToken, photoUpload.single("image"), PhotoUploadCtrl)
//router.post('/users/photo-upload', upload.single('profilePhoto'), PhotoUploadCtrl);



Expand Down