Ошибка с электронной почтой, используя nodejs и passportjs - PullRequest
0 голосов
/ 29 марта 2020

У меня ошибка при попытке подключиться к фейсбуку с использованием паспорта js. Это ошибка:

ValidationError: Account validation failed: email: Path `email` is required.
at new ValidationError (/api/node_modules/mongoose/lib/error/validation.js:31:11)
at model.Document.invalidate (/api/node_modules/mongoose/lib/document.js:2413:32)
at p.doValidate.skipSchemaValidators (/api/node_modules/mongoose/lib/document.js:2262:17)
at /api/node_modules/mongoose/lib/schematype.js:1058:9
at processTicksAndRejections (internal/process/task_queues.js:79:11)

А это мой код:

/*******************FACEBOOK AUTH*************************/
passport.use(
    new FacebookStrategy({
        // options for facebook strategy
        clientID: XXXXXXXXXXXXXXXXXX,
        clientSecret: "XXXXXXXXXXXXXXXXXXXXX",
        callbackURL: "http://localhost:3001/auth/facebook/callback",
        profileFields : ['id', 'displayName', 'email']
    }, (accessToken, refreshToken, profile, done) => {
        // passport callback function
        console.log('passport callback function fired:');
        console.log(profile);
        if(profile!==null){
            var id = profile.id;
            var email = profile.email;

            console.log(id);
            console.log(email);
            var strfullname = profile.displayName;
            var fullname = strfullname.split(/(\s+)/);
            var nom = fullname[2];
            var prenom = fullname[0];
            console.log("nom "+ nom);
            console.log("prenom "+ prenom);
            Account.findOne({'email' : email},function (err, account){
                if(err){
                    console.log(err);
                    done(err);
                }
                if(account){//exist
                    if(err){
                        console.log(err);
                        done(err);
                    }  
                    else {//get account
                        console.log('currentAccount');
                        //check if enable = true
                        if(account.enable===true){
                            //send token
                            try{
                                jwt.sign({
                                    account
                                },config.secretKey,
                                (err,token)=>{
                                    if(err){
                                        done(err)
                                    }
                                    else{
                                        done(null,token);
                                    }
                                });
                            }
                            catch(e){
                                done(err);
                            }
                        }else{
                            done("This account is disabled, please contact support for more information",null);
                        }
                    }
                }
                else{//new account
                    if(err)
                    {
                        console.log(err);    
                        done(err);
                    }

                    const account = new Account({
                        email : email,
                        nom : nom,
                        acceptCGU : true,
                        prenom : prenom,
                        facebook : {
                            id : id,
                            email : email,
                            name : strfullname
                        }
                    });
                    //save data
                    account.save((err => {
                        if(err){
                            console.log(err);
                            done(err);
                        } 
                        else{
                            console.log('newaccount');
                            //send email
                            var smtpTransport = nodemailer.createTransport({
                                service : 'gmail',
                                auth : {
                                    user : "xxxxx.xxxxx@gmail.com",
                                    pass : "xxxxxxxxx"
                                }
                            });
                            var mailOptions = {
                                to : email,
                                from : "xxxxx.xxxxx@gmail.com",
                                subject : "Bienvenue chez XXXXX !",
                                text : "Bienvenue chez xxxxxx ! \n \n Votre compte : "+email+" a bien été créé. \n \n Nos dernières offres exclusives n'attendent plus que vous sur notre site xxxxx.\n A bientôt ! \n \n L'équipe XXXX"
                            }
                            smtpTransport.sendMail(mailOptions,function(err){
                                if(err){
                                    res.status(400);
                                    resultats = {
                                        "success": false,
                                        "message": 'Error : '+ err,
                                        "result": ''
                                    }
                                    res.json(resultats);
                                }
                                else{
                                   //send token
                                    try{
                                        jwt.sign({
                                            account
                                        },config.secretKey,
                                        (err,token)=>{
                                            if(err){
                                                done(err)
                                            }
                                            else{
                                                done(null,token);
                                            }
                                        });
                                    }
                                    catch(e){
                                        done(err);
                                    }
                                }
                            });
                        }
                    }));
                }
            });
        }

    })
);

Маршруты:

/*******************FACEBOOK AUTH ROUTES********************* */
// auth with faceboook
router.get('/auth/facebook', passport.authenticate('facebook'));
// callback route for facebook to redirect to
// hand control to passport to use code to grab profile info
router.get('/auth/facebook/callback*', passport.authenticate('facebook'), (req, res) => {
    if(req.user){
        res.cookie('token', req.user);
        return res.redirect("http://localhost:3000");
    }
    else{
        console.log('error');
        return res.redirect("http://localhost:3000");
    }
});

1 Ответ

0 голосов
/ 30 марта 2020

Я решил это, изменив эту строку:

var email = profile.email;

на

var email = profile._json.email;
...