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 comment to files #774

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
12 changes: 3 additions & 9 deletions config/database.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
//import mongoose
const mongoose = require("mongoose");

//mongoose connection
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.DB_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});

console.log(`MongoDB Connected: ${conn.connection.host}`);
await mongoose.connect(process.env.DB_STRING)
} catch (err) {
console.error(err);
process.exit(1);
}
};

Expand Down
51 changes: 31 additions & 20 deletions config/passport.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,52 @@
//import authentication mongoose and user model
const LocalStrategy = require("passport-local").Strategy;
const mongoose = require("mongoose");
const User = require("../models/User");


//export hash and salt
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);
}
//validating email and password
new LocalStrategy({ usernameField: "email" }, async (email, password, done) => {
try {
const user = await User.findOne({ email: email.toLowerCase() });

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

if (!user.password) {
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);
}

const isMatch = await user.comparePassword(password);
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { msg: "Invalid email or password." });
});
});
}
} catch (err) {
return done(err);
}
})
);

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

passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => done(err, user));
});
//hash and salt
passport.serializeUser((user, done) => {
done(null, user.id);
});

passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (err) {
done(err, null);
}
});
};
72 changes: 39 additions & 33 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//import for validation user properties
const passport = require("passport");
const validator = require("validator");
const User = require("../models/User");

//login page
exports.getLogin = (req, res) => {
if (req.user) {
return res.redirect("/profile");
Expand All @@ -11,7 +13,8 @@ exports.getLogin = (req, res) => {
});
};

exports.postLogin = (req, res, next) => {
//login action
exports.postLogin = async (req, res, next) => {
const validationErrors = [];
if (!validator.isEmail(req.body.email))
validationErrors.push({ msg: "Please enter a valid email address." });
Expand Down Expand Up @@ -44,18 +47,20 @@ exports.postLogin = (req, res, next) => {
})(req, res, next);
};

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

//signup page
exports.getSignup = (req, res) => {
if (req.user) {
return res.redirect("/profile");
Expand All @@ -65,7 +70,8 @@ exports.getSignup = (req, res) => {
});
};

exports.postSignup = (req, res, next) => {
//signup action
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 @@ -74,45 +80,45 @@ exports.postSignup = (req, res, next) => {
msg: "Password must be at least 8 characters long",
});
if (req.body.password !== req.body.confirmPassword)
validationErrors.push({ msg: "Passwords do not match" });
validationErrors.push({ msg: "Passwords do not match." });

if (validationErrors.length) {
req.flash("errors", validationErrors);
return res.redirect("../signup");
}

req.body.email = validator.normalizeEmail(req.body.email, {
gmail_remove_dots: false,
});

const user = new User({
userName: req.body.userName,
email: req.body.email,
password: req.body.password,
});
//checkk for exsisting user
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);
}
};
43 changes: 43 additions & 0 deletions controllers/comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const Comment = require("../models/Comment");

module.exports = {
createComment: async (req, res) => {
try {
await Comment.create({
commentText: req.body.comment,
likes: 0,
user: req.user.id,
post: req.params.id
});
console.log("Comment has been added!");
res.redirect("/post/"+req.params.id);
} catch (err) {
console.log(err);
}
},
likeComment: async (req, res) => {
console.log(req.params)
try {
await Comment.findOneAndUpdate(
{ _id: req.params.id },
{
$inc: { likes: 1 },
}
);
console.log("Likes +1");
res.redirect('back');
} catch (err) {
console.log(err);
}
},
deleteComment: async (req, res) => {
try {
console.log(req.params.id)
await Comment.findOneAndDelete({_id: req.params.id});
console.log("Deleted Comment");
res.redirect("/profile");
} catch (err) {
res.redirect("/profile");
}
},
};
1 change: 1 addition & 0 deletions controllers/home.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//export render for home page
module.exports = {
getIndex: (req, res) => {
res.render("index.ejs");
Expand Down
21 changes: 17 additions & 4 deletions controllers/posts.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
//import cloudinary model for post
const cloudinary = require("../middleware/cloudinary");
const Post = require("../models/Post");
const Post = require("../models/Post");
const Comment = require("../models/Comment");

//export post controllers
module.exports = {

//reads posts and render
getProfile: async (req, res) => {
try {
const posts = await Post.find({ user: req.user.id });
Expand All @@ -21,16 +26,20 @@ 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: -1}).lean()
res.render("post.ejs", { post: post, user: req.user, comments: comments });
} catch (err) {
console.log(err);
}
},

//create posts
createPost: async (req, res) => {
try {
// Upload image to cloudinary
const result = await cloudinary.uploader.upload(req.file.path);

//input to create post
await Post.create({
title: req.body.title,
image: result.secure_url,
Expand All @@ -45,6 +54,8 @@ module.exports = {
console.log(err);
}
},

//update posts
likePost: async (req, res) => {
try {
await Post.findOneAndUpdate(
Expand All @@ -59,14 +70,16 @@ module.exports = {
console.log(err);
}
},

//update posts
deletePost: async (req, res) => {
try {
// Find post by id
let post = await Post.findById({ _id: req.params.id });
let post = await Post.findById(req.params.id);
// Delete image from cloudinary
await cloudinary.uploader.destroy(post.cloudinaryId);
// Delete post from db
await Post.remove({ _id: req.params.id });
await Post.findOneAndDelete(req.params.id);
console.log("Deleted Post");
res.redirect("/profile");
} catch (err) {
Expand Down
2 changes: 2 additions & 0 deletions middleware/auth.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//export for logged in state
module.exports = {
ensureAuth: function (req, res, next) {
//user logged in direct home
if (req.isAuthenticated()) {
return next();
} else {
Expand Down
3 changes: 3 additions & 0 deletions middleware/cloudinary.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
const cloudinary = require("cloudinary").v2;

//giving access to loggin to cloudinary
require("dotenv").config({ path: "./config/.env" });

//access to cloudinary
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET,
});

//exports cloudinary
module.exports = cloudinary;
2 changes: 2 additions & 0 deletions middleware/multer.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//import for multer
const multer = require("multer");
const path = require("path");

/*stores image string not image*/
module.exports = multer({
storage: multer.diskStorage({}),
fileFilter: (req, file, cb) => {
Expand Down
26 changes: 26 additions & 0 deletions models/Comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const mongoose = require("mongoose");

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

module.exports = mongoose.model("Comment", CommentSchema);
Loading