P
P
PlasterTom2018-07-12 17:58:32
Node.js
PlasterTom, 2018-07-12 17:58:32

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);


-strategy with flash messages
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
$.ajax({
    type: "POST",
    url: "/login",
    data: formData,
    processData: false,
    contentType: false,
    success : function(data) {
        console.log(data);
    },
})


Rummaged through the entire stackoverflow, something like this is often found as an answer, but I still can't show errors in the form.

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 question

Ask a Question

731 491 924 answers to any question