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

added comments feature #748

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion config/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ const connectDB = async () => {
const conn = await mongoose.connect(process.env.DB_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});

console.log(`MongoDB Connected: ${conn.connection.host}`);

} catch (err) {
console.error(err);
process.exit(1);
Expand Down
45 changes: 29 additions & 16 deletions config/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,51 @@ const User = require("../models/User");

module.exports = function (passport) {
passport.use(
new LocalStrategy({ usernameField: "email" }, (email, password, done) => {
User.findOne({ email: email.toLowerCase() }, (err, user) => {
if (err) {
return done(err);
}
new LocalStrategy({ usernameField: "email" }, async (email, password, done) => {
try {
// Find the user based on the email
const user = await User.findOne({ email: email.toLowerCase() });

if (!user) {
// No user found with that email
return done(null, false, { msg: `Email ${email} not found.` });
}

if (!user.password) {
// User registered using a sign-in provider
return done(null, false, {
msg:
"Your account was registered using a sign-in provider. To enable password login, sign in using a provider, and then set a password under your user profile.",
});
}
user.comparePassword(password, (err, isMatch) => {
if (err) {
return done(err);
}
if (isMatch) {
return done(null, user);
}

// Compare passwords if the user is found
const isMatch = await user.comparePassword(password);

if (isMatch) {
// Successful login
return done(null, user);
} else {
// Password does not match
return done(null, false, { msg: "Invalid email or password." });
});
});
}
} catch (err) {
// Error occurred during user lookup or password comparison
return done(err);
}
})
);

passport.serializeUser((user, done) => {
done(null, user.id);
});

passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => done(err, user));
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (err) {
done(err);
}
});
};
110 changes: 58 additions & 52 deletions controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ exports.getLogin = (req, res) => {
});
};

exports.postLogin = (req, res, next) => {
exports.postLogin = async (req, res, next) => {
const validationErrors = [];
if (!validator.isEmail(req.body.email))
validationErrors.push({ msg: "Please enter a valid email address." });
Expand All @@ -26,34 +26,43 @@ exports.postLogin = (req, res, next) => {
gmail_remove_dots: false,
});

passport.authenticate("local", (err, user, info) => {
if (err) {
return next(err);
}
if (!user) {
req.flash("errors", info);
return res.redirect("/login");
}
req.logIn(user, (err) => {
try {
passport.authenticate("local", (err, user, info) => {
if (err) {
return next(err);
}
req.flash("success", { msg: "Success! You are logged in." });
res.redirect(req.session.returnTo || "/profile");
});
})(req, res, next);
if (!user) {
req.flash("errors", info);
return res.redirect("/login");
}
req.logIn(user, (err) => {
if (err) {
return next(err);
}
req.flash("success", { msg: "Success! You are logged in." });
res.redirect(req.session.returnTo || "/profile");
});
})(req, res, next);
} catch (err) {
return next(err);
}
};

exports.logout = (req, res) => {
req.logout(() => {
console.log('User has logged out.')
})
req.session.destroy((err) => {
if (err)
console.log("Error : Failed to destroy the session during logout.", err);
req.user = null;
res.redirect("/");
});
exports.logout = async (req, res) => {
try {
req.logout(() => {
console.log('User has logged out.')
});
req.session.destroy((err) => {
if (err) {
console.log("Error : Failed to destroy the session during logout.", err);
}
req.user = null;
res.redirect("/");
});
} catch (err) {
console.log(err);
}
};

exports.getSignup = (req, res) => {
Expand All @@ -65,7 +74,7 @@ exports.getSignup = (req, res) => {
});
};

exports.postSignup = (req, res, next) => {
exports.postSignup = async (req, res, next) => {
const validationErrors = [];
if (!validator.isEmail(req.body.email))
validationErrors.push({ msg: "Please enter a valid email address." });
Expand All @@ -84,35 +93,32 @@ exports.postSignup = (req, res, next) => {
gmail_remove_dots: false,
});

const user = new User({
userName: req.body.userName,
email: req.body.email,
password: req.body.password,
});
try {
const existingUser = await User.findOne({
$or: [{ email: req.body.email }, { userName: req.body.userName }],
});

if (existingUser) {
req.flash("errors", {
msg: "Account with that email address or username already exists.",
});
return res.redirect("../signup");
}

const user = new User({
userName: req.body.userName,
email: req.body.email,
password: req.body.password,
});

User.findOne(
{ $or: [{ email: req.body.email }, { userName: req.body.userName }] },
(err, existingUser) => {
await user.save();
req.logIn(user, (err) => {
if (err) {
return next(err);
}
if (existingUser) {
req.flash("errors", {
msg: "Account with that email address or username already exists.",
});
return res.redirect("../signup");
}
user.save((err) => {
if (err) {
return next(err);
}
req.logIn(user, (err) => {
if (err) {
return next(err);
}
res.redirect("/profile");
});
});
}
);
res.redirect("/profile");
});
} catch (err) {
return next(err);
}
};
17 changes: 17 additions & 0 deletions controllers/comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const Comment = require("../models/Comment")

module.exports = {
createComment: async (req, res) => {
try {
await Comment.create({
comment: req.body.comment,
likes: 0,
post: req.params.id,
});
console.log("Comment has been added!");
res.redirect("/post/"+req.params.id);
} catch (err) {
console.log(err);
}
},
};
5 changes: 4 additions & 1 deletion controllers/posts.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const cloudinary = require("../middleware/cloudinary");
const Post = require("../models/Post");
const Comment = require("../models/Comment")

module.exports = {
getProfile: async (req, res) => {
Expand All @@ -21,7 +22,9 @@ module.exports = {
getPost: async (req, res) => {
try {
const post = await Post.findById(req.params.id);
res.render("post.ejs", { post: post, user: req.user });
const comments = await Comment.find({post: req.params.id}).sort({ createdAt: "desc" }).lean();
console.log(comments)
res.render("post.ejs", { post: post, user: req.user, comments: comments });
} catch (err) {
console.log(err);
}
Expand Down
22 changes: 22 additions & 0 deletions models/Comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const mongoose = require("mongoose");

const CommentSchema = new mongoose.Schema({
comment: {
type: String,
required: true,
},
likes: {
type: Number,
required: true,
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
},
createdAt: {
type: Date,
default: Date.now,
},
});

module.exports = mongoose.model("Comment", CommentSchema);
14 changes: 7 additions & 7 deletions models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ UserSchema.pre("save", function save(next) {

// Helper method for validating user's password.

UserSchema.methods.comparePassword = function comparePassword(
candidatePassword,
cb
) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
cb(err, isMatch);
});
UserSchema.methods.comparePassword = async function(candidatePassword) {
try {
const isMatch = await bcrypt.compare(candidatePassword, this.password);
return isMatch;
} catch (error) {
throw error;
}
};

module.exports = mongoose.model("User", UserSchema);
Loading