passport.js authenticate throwing unauthorized error?

Viewed 10

I am trying to use passport.js with mongoose. The data sent are correct but I get an error of code 401 saying unauthorized?

Here is the back end controller.

userController.login = (req, res) =>{
    console.log("recieved");
    console.log(req.body);
    const user = new Users({
        username: req.body.mail,
        password: req.body.password
    })

    req.login(user, (err) => {
        if (err){
            res.status(404).send(err);
        }else{
            console.log("user found");
            passport.authenticate("local", (err, user, info) => {
                if (err) {
                    return res.status(401).json(err);
                }
                if (user) {
                    return res.status(200).send(user);
                } else {
                    res.status(401).json(info);
                }
            })(req, res, () => {
                console.log("Authenticated!");
                res.status(200).send(user);
            });
        }
    })
}
1 Answers

While posting I needed to rename the req.body.mail to just req.body.username because auth and req.login looks for req body directly and search for a username object.

Related