Skip to content

Instantly share code, notes, and snippets.

@neenjaw
Created February 25, 2018 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neenjaw/715884a0d3065adfe65feedec2c0d457 to your computer and use it in GitHub Desktop.
Save neenjaw/715884a0d3065adfe65feedec2c0d457 to your computer and use it in GitHub Desktop.
passport-local-mongoose authenticate example
//USER SCHEMA
const mongoose = require('mongoose');
const passportLocalMongoose = require('passport-local-mongoose');
module.exports = (function () {
const userSchema = mongoose.Schema({
username: String,
password: String,
displayName: { type: String, unique: true, required: true },
created: {
type: Date, default: Date.now
},
updated: Date,
isAdmin: { type: Boolean, default: false }
});
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model('User', userSchema);
return User;
}());
//THE AUTH LOGIC FOR INSIDE MIDDLEWARE OR ENDPOINTS
const authenticate = User.authenticate();
authenticate(req.user.username, update.newPassword, (err, result) => {
if (err) {
res.flash('danger', 'There was a problem updating your password.');
res.redirect(`/users/${req.user._id}`);
} else {
if (!result) {
res.flash('danger', 'Incorrect old password.');
res.redirect(`/users/${req.user._id}`);
} else {
res.send('Authenticated');
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment