Skip to content

Commit

Permalink
done testing part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
amitamrutiya committed Oct 27, 2023
1 parent 9ebb531 commit 7bf7384
Show file tree
Hide file tree
Showing 13 changed files with 202 additions and 64 deletions.
77 changes: 39 additions & 38 deletions controllers/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const User = require("../models/User");
const OTP = require("../models/OTP");
const Profile = require("../models/Profile");
const otpGenerator = require("otp-generator");
const bcrypt = require("bcryptjs");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const mailSender = require("../utils/mailSender");
require("dotenv").config();
Expand Down Expand Up @@ -33,9 +33,9 @@ exports.sendOTP = async (req, res) => {

//generate otp
var otp = otpGenerator.generate(6, {
upperCase: false,
specialChars: false,
alphabets: false,
lowerCaseAlphabets: false,
upperCaseAlphabets: false,
});
console.log("OTP generated: " + otp);

Expand Down Expand Up @@ -113,22 +113,26 @@ exports.signUp = async (req, res) => {
.status(400)
.json({ success: false, message: "User already exist" });
}

//find most recent OTP stored for the user
const recentOtp = await OTP.findOne({ email })
const recentOtp = await OTP.find({ email })
.sort({ createdAt: -1 })
.limit(1);

console.log("recentOtp " + recentOtp);
//check if OTP is valid
if (recentOtp.otp.length === 0) {
if (recentOtp.length === 0) {
return res.status(400).json({ success: false, message: "OTP not found" });
} else if (recentOtp.otp !== otp) {
} else if (recentOtp[0].otp !== otp) {
return res.status(400).json({ success: false, message: "Invalid OTP" });
}

//Hash Password
const hashedPawword = await bcrypt.hash(password, 10);

// Create the user
let approved = "";
approved === "Instructor" ? (approved = false) : (approved = true);

//save user to database
const profileDetails = await Profile.create({
gender: null,
Expand All @@ -141,10 +145,11 @@ exports.signUp = async (req, res) => {
firstName,
lastName,
email,
contactNumber: contactNumber,
password: hashedPawword,
accountType,
approved,
additionalDetails: profileDetails._id,
contactNumber: contactNumber ?? null,
image: `https://api.dicebear.com/5.x/initials/svg?seed=${firstName}+${lastName}`,
});

Expand All @@ -166,68 +171,64 @@ exports.signUp = async (req, res) => {
// Login
exports.login = async (req, res) => {
try {
//fetch data from request body
const { email, password } = req.body;
const { email, password } = req.body; //get data from req body

//validate data
if (!email || !password) {
return res
.status(403)
.json({ success: false, message: "Please fill all the fields" });
// validate krlo means all inbox are filled or not;
return res.status(403).json({
success: false,
message: "Please Fill up All the Required Fields",
});
}

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

//check if password is correct
const isPasswordCorrect = await bcrypt.compare(password, user.password);
if (isPasswordCorrect) {
//genreate JWT token
if (await bcrypt.compare(password, user.password)) {
//generate JWT, after password matching/comparing
const payload = {
// generate payload;
email: user.email,
id: user._id,
accountType: user.accountType,
};
const token = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: "20h",
// generate token (combination of header , payload , signature)
expiresIn: "20h", // set expiry time;
});
user.token = token;
user.password = undefined;

//create cookie and send response
const options = {
//create cookie and send response
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRE * 24 * 60 * 60 * 1000
),
httpOnly: true,
};
res.cookie("token", token, options).status(200).json({
token,
data: user,
success: true,
message: "User logged in successfully",
token,
user,
message: "Logged in successfully",
});
} else {
return res
.status(401)
.json({ success: false, message: "Invalid credentials" });
return res.status(401).json({
success: false,
message: "Password is incorrect",
});
}

//return response
res.status(200).json({
success: true,
message: "User logged in successfully",
data: user,
});
} catch (error) {
console.log("Error in logging in user: " + error);
return res.status(500).json({ success: false, message: error.message });
console.log(error);
return res.status(500).json({
success: false,
message: "Login Failure, please try again",
});
}
};

Expand Down
4 changes: 2 additions & 2 deletions controllers/Category.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ exports.createCategory = async (req, res) => {
}

// check if user is admin then only create category
if (req.user.accountType !== "admin") {
if (req.user.accountType !== "Admin") {
return res.status(403).json({
success: false,
message: "You are not authorized to create category",
});
}

//check if category already exist
const isExistingCategory = Category.findOne({ name });
const isExistingCategory = await Category.findOne({ name });
if (isExistingCategory) {
return res.status(400).json({
success: false,
Expand Down
42 changes: 28 additions & 14 deletions controllers/Course.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,30 @@
const Course = require("../models/Course");
const Category = require("../models/Category");
const User = require("../models/User");
const { uploadFileToCloudinary } = require("../utils/imageUploader");
const { uploadFileToCloudinary } = require("../utils/fileUploader");
require("dotenv").config();

//createCourse handler function
exports.createCourse = async (req, res) => {
try {
//fetch data
const {
let {
courseName,
courseDescription,
whatYouWillLearn,
price,
category,
tags,
tags: _tags,
totalDuration,
language,
status,
instructions: _instructions,
} = req.body;

//get thumbnail
const thumbnail = req.files.thumbnailImage;
const tags = JSON.parse(_tags); //Convert the tag and instructions from stringified Array to Array
const instructions = JSON.parse(_instructions);

//validate data
if (
Expand All @@ -29,18 +33,20 @@ exports.createCourse = async (req, res) => {
!whatYouWillLearn ||
!price ||
!category ||
!totalDuration ||
!language ||
!instructions.length ||
!thumbnail ||
!tags
!tags.length
) {
return res
.status(400)
.json({ success: false, message: "Please enter all the fields" });
}

if (!status || status === undefined) {
status = "Draft";
}
// Check for instructor
const instructorDetails = await User.findById(req.user.id, {
let instructorDetails = await User.findById(req.user.id, {
accountType: "Instructor",
});
if (!instructorDetails) {
Expand All @@ -51,7 +57,7 @@ exports.createCourse = async (req, res) => {
}

//check for category
const categoryDetails = await Category.findById(category);
let categoryDetails = await Category.findById(category);
if (!categoryDetails) {
return res.status(400).json({
success: false,
Expand All @@ -66,7 +72,7 @@ exports.createCourse = async (req, res) => {
);

//create an entry for new course
const newCourse = await Course.create({
let newCourse = await Course.create({
courseName,
courseDescription,
instructor: instructorDetails._id,
Expand All @@ -77,15 +83,23 @@ exports.createCourse = async (req, res) => {
tags,
language,
totalDuration,
status,
instructions,
});

//push course id to instructor's course array
instructorDetails.courses.push(newCourse._id);
await instructorDetails.save();
await User.findByIdAndUpdate(
instructorDetails._id,
{ $push: { courses: newCourse._id } },
{ new: true }
);

//update category schema
categoryDetails.courses.push(newCourse._id);
await categoryDetails.save();
await Category.findByIdAndUpdate(
category,
{ $push: { courses: newCourse._id } },
{ new: true }
);

//send response
return res.status(200).json({
Expand Down Expand Up @@ -158,7 +172,7 @@ exports.getCourseDetails = async (req, res) => {
.populate("ratingAndReviews")
.populate({
path: "courseContent",
populate: { path: "subSection" },
populate: { path: "subSections" },
})
.exec();

Expand Down
32 changes: 32 additions & 0 deletions controllers/Profile.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const Profile = require("../models/Profile");
const User = require("../models/User");
const { uploadFileToCloudinary } = require("../utils/fileUploader");
require("dotenv").config();

// Update Profile
exports.updateProfile = async (req, res) => {
Expand Down Expand Up @@ -69,3 +71,33 @@ exports.updateProfile = async (req, res) => {
});
}
};

exports.updateDisplayPicture = async (req, res) => {
try {
const displayPicture = req.files.displayPicture;
const userId = req.user.id;
const image = await uploadFileToCloudinary(
displayPicture,
process.env.FOLDER_NAME,
1000,
1000
);

const updatedProfile = await User.findByIdAndUpdate(
{ _id: userId },
{ image: image.secure_url },
{ new: true }
);

res.send({
success: true,
message: `Image Updated successfully`,
data: updatedProfile,
});
} catch (error) {
return res.status(500).json({
success: false,
message: error.message,
});
}
};
1 change: 1 addition & 0 deletions controllers/RatingAndReview.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const RatingAndReview = require("../models/RatingAndReview");
const Course = require("../models/Course");
const User = require("../models/User");
const mongoose = require("mongoose");

// create Rating and review
exports.createRating = async (req, res) => {
Expand Down
9 changes: 6 additions & 3 deletions controllers/Section.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,18 @@ exports.createSection = async (req, res) => {
}

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

//update course with newSection
const updatedCourseDetails = await Course.findByIdAndUpdate(
courseId,
{ $push: { courseContent: newSection._id } },
{ new: true }
)
.populate({ path: "courseContent", populate: { path: "subSection" } })
.populate({
path: "courseContent",
populate: { path: "subSections" },
})
.exec();

//send response
Expand Down Expand Up @@ -158,7 +161,7 @@ exports.deleteSection = async (req, res) => {
};

// Get All Sections
ecports.getAllSections = async (req, res) => {
exports.getAllSections = async (req, res) => {
try {
//data fetch
const { courseId } = req.body;
Expand Down
6 changes: 3 additions & 3 deletions controllers/SubSection.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ exports.createSubSection = async (req, res) => {
const { sectionId, title, timeDuration, description } = req.body;

//extract file/video
const video = req.file.videoFile;

const video = req.files.video;
//validation
if (!sectionId || !title || !timeDuration || !video || !description) {
return res.status(400).json({
Expand All @@ -38,7 +38,7 @@ exports.createSubSection = async (req, res) => {
//create a sub section
const subSection = await SubSection.create({
title,
timeDuration: `${uploadDetails.duration}`,
timeDuration: `${uploadVideo.duration}`,
description,
videoUrl: uploadVideo.secure_url,
});
Expand Down
Loading

0 comments on commit 7bf7384

Please sign in to comment.