Skip to content

Instantly share code, notes, and snippets.

@mpragnarok
Created September 12, 2019 02:27
Show Gist options
  • Save mpragnarok/5fd38bf5abf48bafe8cf6309ba3a3b34 to your computer and use it in GitHub Desktop.
Save mpragnarok/5fd38bf5abf48bafe8cf6309ba3a3b34 to your computer and use it in GitHub Desktop.
Passport.js configuration in LocalStrategy
// config\passport.js
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcryptjs')
const User = require('../src/models/user')
module.exports = passport => {
// setup local passport
passport.use(
new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, async (email, password, done) => {
try {
const user = await User.findOne({ email })
if (!user) {
return done(null, false, { message: 'That email is not registered'})
}
const isMatch = await bcrypt.compare(password, user.password)
if (isMatch) {
return done(null, user)
} else {
return done(user.errors, null, { message: 'Email or password incorrect' })
}
} catch (e) {
throw e
}
})
)
// passport serializeUser & deserializeUser
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user)
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment