Created
February 25, 2018 22:03
-
-
Save neenjaw/715884a0d3065adfe65feedec2c0d457 to your computer and use it in GitHub Desktop.
passport-local-mongoose authenticate example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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