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

Fixed mongoose v8.1 breaking errors #778

Open
wants to merge 2 commits 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
8 changes: 1 addition & 7 deletions config/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,7 @@ const mongoose = require("mongoose");

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

const conn = await mongoose.connect(process.env.DB_STRING);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (err) {
console.error(err);
Expand Down
50 changes: 25 additions & 25 deletions config/passport.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,41 @@
const LocalStrategy = require("passport-local").Strategy;
const mongoose = require("mongoose");
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);
}
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);
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 (isMatch) {
return done(null, user);
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.",
});
}
return done(null, false, { msg: "Invalid email or password." });
});
});
const isMatch = await user.comparePassword(password)
if (isMatch) {
return done(null, user);
}
return done(null, false, { msg: "Invalid email or password." });
} catch {
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)
}
});
};
56 changes: 26 additions & 30 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const passport = require("passport");
const validator = require("validator");
const User = require("../models/User");
const User = require("../models/User");

exports.getLogin = (req, res) => {
exports.getLogin = async (req, res) => {
if (req.user) {
return res.redirect("/profile");
}
Expand All @@ -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,15 +26,15 @@ exports.postLogin = (req, res, next) => {
gmail_remove_dots: false,
});

passport.authenticate("local", (err, user, info) => {
passport.authenticate("local", async (err, user, info) => {
if (err) {
return next(err);
}
if (!user) {
req.flash("errors", info);
return res.redirect("/login");
}
req.logIn(user, (err) => {
req.logIn(user, async (err) => {
if (err) {
return next(err);
}
Expand Down Expand Up @@ -65,7 +65,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 @@ -89,30 +89,26 @@ exports.postSignup = (req, res, next) => {
email: req.body.email,
password: req.body.password,
});

User.findOne(
{ $or: [{ email: req.body.email }, { userName: req.body.userName }] },
(err, existingUser) => {
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");
});
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");
}
);
await user.save();
await new Promise((resolve, reject)=> {
req.logIn(user, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
res.redirect("/profile");
} catch (err) {
next(err)
}
};
3 changes: 2 additions & 1 deletion controllers/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,11 @@ module.exports = {
// Delete image from cloudinary
await cloudinary.uploader.destroy(post.cloudinaryId);
// Delete post from db
await Post.remove({ _id: req.params.id });
await Post.deleteOne({ _id: req.params.id });
console.log("Deleted Post");
res.redirect("/profile");
} catch (err) {
console.log(err)
res.redirect("/profile");
}
},
Expand Down
40 changes: 15 additions & 25 deletions models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,24 @@ const UserSchema = new mongoose.Schema({

// Password hash middleware.

UserSchema.pre("save", function save(next) {
const user = this;
if (!user.isModified("password")) {
return next();
}
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
UserSchema.pre("save", async function (next) {
try {
if (this.isModified('password')) {
return next()
}
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
});
const salt = await bcrypt.genSalt(10)
this.password = await bcrypt.hash(this.password, salt)
next()
} catch {
next(err)
}
})


// 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) {
return bcrypt.compare(candidatePassword, this.password)
}

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