Created
September 12, 2019 02:27
-
-
Save mpragnarok/5fd38bf5abf48bafe8cf6309ba3a3b34 to your computer and use it in GitHub Desktop.
Passport.js configuration in LocalStrategy
This file contains hidden or 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
| // 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