Skip to content

Commit

Permalink
fix some bugs in code
Browse files Browse the repository at this point in the history
  • Loading branch information
amitamrutiya committed Oct 21, 2023
1 parent 3526873 commit 7d82991
Show file tree
Hide file tree
Showing 16 changed files with 299 additions and 276 deletions.
66 changes: 38 additions & 28 deletions controller/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const mailSender = require("../utils/mailSender");
require("dotenv").config();
const { passwordUpdated } = require("../mail/templates/passwordUpdate");

//Send Otp
// Send Otp
exports.sendOTP = async (req, res) => {
try {
//fetch email from request body
Expand Down Expand Up @@ -69,7 +70,7 @@ exports.sendOTP = async (req, res) => {
}
};

//Singup
// Singup
exports.signUp = async (req, res) => {
try {
//data fetch from request body
Expand Down Expand Up @@ -162,7 +163,7 @@ exports.signUp = async (req, res) => {
}
};

//Login
// Login
exports.login = async (req, res) => {
try {
//fetch data from request body
Expand All @@ -176,7 +177,7 @@ exports.login = async (req, res) => {
}

//check if user exist
const user = await User.findOne({ email });
const user = await User.findOne({ email }).populate("additionalDetails");
if (!user) {
return res.status(401).json({
success: false,
Expand All @@ -194,7 +195,7 @@ exports.login = async (req, res) => {
accountType: user.accountType,
};
const token = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: "2h",
expiresIn: "20h",
});
user.token = token;
user.password = undefined;
Expand Down Expand Up @@ -230,30 +231,25 @@ exports.login = async (req, res) => {
}
};

//ChangePassowrd
// ChangePassowrd
exports.changePassowrd = async (req, res) => {
try {
//fetch data from request body
const { email, oldPassword, newPassword, confirmNewPassword } = req.body;
// Fetch data from request body
const { oldPassword, newPassword, confirmNewPassword } = req.body;
const userDetails = await User.findById(req.user.id);

//validate data
if (!email || !oldPassword || !newPassword || !confirmNewPassword) {
// Validate data
if (!userDetails || !oldPassword || !newPassword || !confirmNewPassword) {
return res
.status(403)
.json({ success: false, message: "Please fill all the fields" });
}

//check if user exist
const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({
success: false,
message: "User does not exist, please signup first",
});
}

//check if password is correct
const isPasswordCorrect = await bcrypt.compare(oldPassword, user.password);
// Check if password is correct
const isPasswordCorrect = await bcrypt.compare(
oldPassword,
userDetails.password
);
if (isPasswordCorrect) {
//match 2 password
if (newPassword !== confirmNewPassword) {
Expand All @@ -266,14 +262,29 @@ exports.changePassowrd = async (req, res) => {
const hashedPawword = await bcrypt.hash(newPassword, 10);

//update password
await User.findByIdAndUpdate(user._id, { password: hashedPawword });
const updatedUserDetails = await User.findByIdAndUpdate(
req.user.id,
{ password: hashedPawword },
{ new: true }
);

//Send mail to user
await mailSender(
email,
"Password Changed Successfully",
"Your password has been changed successfully"
);
try {
const emailResponse = await mailSender(
updatedUserDetails.email,
passwordUpdated(
updatedUserDetails.email,
`Password updated successfully for ${updatedUserDetails.firstName} ${updatedUserDetails.lastName}`
)
);
console.log("Email sent successfully:", emailResponse.response);
} catch (error) {
return res.status(500).json({
success: false,
message: "Error occurred while sending email",
error: error.message,
});
}

//return response
res.status(200).json({
Expand All @@ -290,4 +301,3 @@ exports.changePassowrd = async (req, res) => {
return res.status(500).json({ success: false, message: error.message });
}
};

12 changes: 7 additions & 5 deletions controller/Course.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ exports.createCourse = async (req, res) => {
!whatYouWillLearn ||
!price ||
!category ||
!duration ||
!totalDuration ||
!language ||
!thumbnail ||
!tags
Expand All @@ -40,7 +40,9 @@ exports.createCourse = async (req, res) => {
}

// Check for instructor
const instructorDetails = await User.findById(req.user._id);
const instructorDetails = await User.findById(req.user.id, {
accountType: "Instructor",
});
if (!instructorDetails) {
return res.status(400).json({
success: false,
Expand Down Expand Up @@ -101,10 +103,10 @@ exports.createCourse = async (req, res) => {
};

//getAllCourse handler function
exports.showAllCourses = async (req, res) => {
exports.getAllCourses = async (req, res) => {
try {
const allCourses = await Course.find(
{},
{ status: "Published" },
{
courseName: true,
price: true,
Expand All @@ -115,7 +117,7 @@ exports.showAllCourses = async (req, res) => {
studentsEnrolled: true,
}
)
.populate("instructor")
.populate("Instructor")
.exec();

return res.status(200).json({
Expand Down
Empty file added controller/Payments.js
Empty file.
29 changes: 21 additions & 8 deletions controller/Profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,14 @@ const User = require("../models/User");
exports.updateProfile = async (req, res) => {
try {
// Get user id and data
const { dateOfBirth = "", about = "", contactNumber, gender } = req.body;
const {
firstName = "",
lastName = "",
dateOfBirth = "",
about = "",
contactNumber = "",
gender = "",
} = req.body;
const { id } = req.user;

// validation
Expand All @@ -14,12 +21,10 @@ exports.updateProfile = async (req, res) => {
success: false,
message: "User id is required",
});
} else if (!contactNumber || !gender) {
return res.status(400).json({
success: false,
message: "Contact number and gender is required",
});
} else if (contactNumber.length < 10 || contactNumber.length > 10) {
} else if (
contactNumber &&
(contactNumber.length < 10 || contactNumber.length > 10)
) {
return res.status(400).json({
success: false,
message: "Contact number should be 10 digits",
Expand All @@ -31,6 +36,10 @@ exports.updateProfile = async (req, res) => {
const profileId = userDetails.additionalDetails;
const profileDetails = await Profile.findById(profileId);

// update user
const user = await User.findByIdAndUpdate(id, { firstName, lastName });
await user.save();

// update profile
profileDetails.dateOfBirth = dateOfBirth;
profileDetails.about = about;
Expand All @@ -40,6 +49,11 @@ exports.updateProfile = async (req, res) => {
// save profile
await profileDetails.save();

// Find the updated user details
const updatedUserDetails = await User.findById(id)
.populate("additionalDetails")
.exec();

// return response
return res.status(201).json({
success: true,
Expand All @@ -55,4 +69,3 @@ exports.updateProfile = async (req, res) => {
});
}
};

10 changes: 5 additions & 5 deletions controller/ResetPassword.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const User = require("../models/User");
const mailSender = require("../utils/mailSender");
const bcrypt = require("bcryptjs");
const crypto = require("crypto");

// ResetPasswordToken
exports.resetPasswordToken = async (req, res) => {
Expand All @@ -23,7 +24,7 @@ exports.resetPasswordToken = async (req, res) => {
}

//generate token
const token = crypto.randomUUID();
const token = crypto.randomBytes(20).toString("hex");

//update user by adding token and expiration time
await User.findOneAndUpdate(
Expand All @@ -41,8 +42,8 @@ exports.resetPasswordToken = async (req, res) => {
//send email to user
await mailSender(
email,
"Reset Password Email from StudyNotion",
`Password reset link: ${url}`
"Password Reset Link",
`Your Link for email verification is ${url}. Please click this url to reset your password.`
);

//return response successful
Expand Down Expand Up @@ -93,7 +94,7 @@ exports.resetPassword = async (req, res) => {
if (userDetails.resetPasswordExpires < Date.now()) {
return res.status(400).json({
success: false,
message: "Token expired",
message: "Token is expired, please regenerate your token'",
});
}

Expand All @@ -120,4 +121,3 @@ exports.resetPassword = async (req, res) => {
});
}
};

42 changes: 28 additions & 14 deletions controller/Section.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
const Section = require("../models/Section");
const Course = require("../models/Course");
const SubSection = require("../models/SubSection");

// Create Section
exports.createSection = async (req, res) => {
try {
//data fetch
// data fetch
const { sectionName, courseId } = req.body;

//data validation
// data validation
if (!sectionName || !courseId) {
return res
.status(400)
.json({ success: false, error: "All fields are required" });
}

//check if course exist
const course = await Course.findById(courseId);
// check if course exist
const course = await Course.findById({ _id: courseId });
if (!course) {
return res
.status(404)
.json({ success: false, error: "Course not found" });
}
//create Section

// create Section
const newSection = await Section.create({ courseId, sectionName });

//update course with newSection
Expand All @@ -30,7 +32,7 @@ exports.createSection = async (req, res) => {
{ $push: { courseContent: newSection._id } },
{ new: true }
)
.populate("courseContent")
.populate({ path: "courseContent", populate: { path: "subSection" } })
.exec();

//send response
Expand Down Expand Up @@ -77,6 +79,11 @@ exports.updateSection = async (req, res) => {
{ new: true }
);

//update course with new updatedSection
const course = await Course.findById(courseId)
.populate({ path: "courseContent", populate: { path: "subSection" } })
.exec();

//send response
res.status(201).json({
success: true,
Expand Down Expand Up @@ -114,17 +121,24 @@ exports.deleteSection = async (req, res) => {
.json({ success: false, error: "Section not found" });
}

await Course.findByIdAndUpdate(section.courseId, {
$pull: { courseContent: sectionId },
});

//delete sub section
await SubSection.deleteMany({ _id: { $in: section.subSection } });

//delete Section
const deletedSection = await Section.findByIdAndDelete(sectionId);

//TODO: maybe it can give you error
//update course with new deleted Section
const updatedCourseDetails = await Course.findByIdAndUpdate(
section.courseId,
{ $pull: { courseContent: deletedSection._id } },
{ new: true }
)
.populate("courseContent")
//find the updated course and return
await Course.findById(section.courseId)
.populate({
path: "courseContent",
populate: {
path: "subSection",
},
})
.exec();

//send response
Expand Down
Loading

0 comments on commit 7d82991

Please sign in to comment.