Answer the question
In order to leave comments, you need to log in
How to use passport + ajax?
I'm a little confused on how to post a request and authenticate a user with error messages.
My current code is:
-route
router.post('/login', (req, res, next)=>{
passport.authenticate('local', {
successRedirect : '/admin',
failureRedirect : '/login',
failureFlash : true
})(req, res, next);
module.exports = passport => {
passport.use(new LocalStrategy({
usernameField : 'login'
},
(login, password, done) => {
//match user
User.findOne({
login : login
})
.then(user => {
if(!user){
return done(null, false, {message : 'no user found'});
}
//match passwords
bcrypt.compare(password, user.password, (err, isMatch)=>{
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, {message : 'password incorrect'});
}
})
})
.catch(err => console.log(err));
}
));
passport.serializeUser(//more code);
passport.deserializeUser(//more code);
});
$.ajax({
type: "POST",
url: "/login",
data: formData,
processData: false,
contentType: false,
success : function(data) {
console.log(data);
},
})
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(error, user, info) {
if(error) {
return res.status(500).json(error);
}
if(!user) {
return res.status(401).json(info.message);
}
res.json(user);
})(req, res, next);
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question