V
V
Vladimir2019-10-19 08:53:34
Node.js
Vladimir, 2019-10-19 08:53:34

Why doesn't passport.js authentication work?

Good morning. I have a script that should check the user's data and authorize him, but for some reason, nothing happens when the request is sent..
Here is the code:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

const Sequelize = require('sequelize');

// Option 1: Passing parameters separately
const sequelize = new Sequelize('test', 'root', '', {
  host: 'localhost',
  dialect: 'mysql',
  operatorsAliases: false,
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }

  // dialectOptions: {
  //   socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock',
  //   supportBigNumbers: true,
  //   bigNumberStrings: true
  // },

});

sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

const User = sequelize.define('users', {
  // attributes
  email: {
    type: Sequelize.STRING,
    allowNull: false
  },
  password: {
    type: Sequelize.STRING
    // allowNull defaults to true
  }
}, {
  // options
});

let userDB = null;

sequelize
  .query('SELECT * FROM users', { raw: true })
  .then(users => {
  	const isIds = users[0].map(user => user.id);
  	const isEmails = users[0].map(user => user.email);
  	const isPasswords = users[0].map(user => user.password);

  	userDB = {
    id: isIds,
    email: isEmails,
    password: isPasswords
  }
  console.log(userDB);
});

passport.serializeUser(function(user, done) {
  console.log("Serialize: ", user);
  	done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  /*User.findById(id, function(err, user) {
    done(err, user);
  });*/

  	console.log("Deserialize: ", id);
  	user = (userDB.id === id) ? userDB : false;
  	done(null, user);

});

passport.use(new LocalStrategy(
  {usernameField: 'email'},
  function(email, password, done) {
  	if(email === userDB.email[0] && password === userDB.password[0]) {
  		return done(null,userDB)
  	}
  	else {
  		return done(null,false)
  	}
  })
);

Thank you^^

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-10-19
@hzzzzl

How is the passport connected to the project?
what do you mean it doesn't work, req.user is always empty?
see example with passport and express
https://github.com/passport/express-4.x-local-exam...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question