I'm trying to authenticate users using passportjs for the first time but I've been having trouble getting it to work. So this is the relevant code I'm working with
Index.js route file
var express = require('express');
var router = express.Router();
var passport = require('passport');
var bcrypt = require('bcryptjs');
router.post('/', passport.authenticate('local', {
successRedirect: 'home',
failureRedirect: '/'
}));
app.js
// Authentication packages
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var MySQLStore = require('express-mysql-session')(session);
var bcrypt = require('bcryptjs');
passport.use(new LocalStrategy(function(email, password, done) {
console.log(email);
console.log(password);
res.locals.connection.query('SELECT id, password FROM users WHERE email = ?', [email], function(err, user) {
console.log(user);
if (err) {return done(err)};
if (user.length === 0) {
done(null, false);
};
const hash = user[0].password.toString();
console.log(hash);
bcrypt.compare(password, hash, function(err, res) {
if (res === true) {
return done(null, {user_id: user[0].id});
} else {
return done(null, false);
}
});
});
}
));
When i input a valid email address and password, I don't get redirected to the home like i want. Instead I'm redirected back to the login page. Same thing happens when i use an invalid email address. I also don't see the email and password even though I'm trying to console log it when i submit the login form.
Can anyone help me out here please.
I noticed you have email
as the username. I had a similar problem and found that the solution was just to add usernameField
to the strategy options:
new LocalStrategy({usernameField: 'email'}, function(email, password, done){...})
I think you may either need to place your passport.use
in your route index.js file, or somehow pass the passport
instance created in app.js as a parameter to index.js
Could you try that? It's possible that a new instance is created everytime you do require('passport')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.