const BasicAuth = require('passport-http').BasicStrategy const bCrypt = require('bcrypt-nodejs') const users = require('../models').Users /** * Compare bcrypt password * @param {Object} user * @param {String} password * @returns {Boolean} */ let isValidPassword = function (user, password) { return bCrypt.compareSync(password, user.password) } module.exports = function (passport) { passport.serializeUser( function (user, done) { done(null, user.id) } ) passport.deserializeUser( function (id, done) { users.findById(id) .then(user => { if (!user) { done(new Error('No user found'), user) return false } done(null, user) }) .catch(e => { done(e, null) }) } ) passport.use( 'basic-auth', new BasicAuth({ usernameField: 'email', passwordField: 'password', passReqToCallback: true }, function (req, email, password, done) { users.find({ where: { email: email } }) .then(user => { if (!user) { done(new Error('No user found')) return false } if (!isValidPassword(user, password)) { return done(null, false, { message: 'Invalid password' }) } return done(null, user) }) .catch(e => { done(e, null) }) }) ) }