首页 文章

Express Passport Session无法正常工作

提问于
浏览
1

我正在构建一个Node应用程序,用户必须在其中注册或登录,然后当他们拖放一些元素(前端全部工作)时,我将数据存储在数据库中,并使用相应的userId .

我的理解是,一旦注册/登录,我就可以使用req.user来访问他们的id并正确存储他们的动作,但是它无法正常工作 .

这是我的server.js文件中处理Passport的部分 . 另外,我使用Sequelize作为ORM,但是在没有req.user部分的情况下处理数据库的一切都很完美 .

app.use(cookieParser());
app.use(bodyParser.json());

app.use(passport.initialize());
app.use(passport.session());

/****** Passport functions ******/
passport.serializeUser(function (user, done) {
    console.log('serialized');
    done(null, user.idUser);
});

passport.deserializeUser(function (id, done) {
    console.log("start of deserialize");
    db.user.findOne( { where : { idUser : id } } ).success(function (user) {
        console.log("deserialize");
        console.log(user);
        done(null, user);
    }).error(function (err) {
        done(err, null);
    });
});

//Facebook
passport.use(new FacebookStrategy({
    //Information stored on config/auth.js
    clientID: configAuth.facebookAuth.clientID,
    clientSecret: configAuth.facebookAuth.clientSecret,
    callbackURL: configAuth.facebookAuth.callbackURL,
    profileFields: ['id', 'emails', 'displayName', 'name', 'gender'] 

}, function (accessToken, refreshToken, profile, done) {
    //Using next tick to take advantage of async properties
    process.nextTick(function () {
        db.user.findOne( { where : { idUser : profile.id } }).then(function (user, err) {
            if(err) {
                return done(err);
            } 
            if(user) {
                return done(null, user);
            } else {
                //Create the user
                db.user.create({
                    idUser : profile.id,
                    token : accessToken,
                    nameUser : profile.displayName,
                    email : profile.emails[0].value,
                    sex : profile.gender
                });

                //Find the user (therefore checking if it was indeed created) and return it
                db.user.findOne( { where : { idUser : profile.id } }).then(function (user, err) {
                    if(user) {
                        return done(null, user);
                    } else {
                        return done(err);
                    }
                });
            }
        });
    });
}));

/* FACEBOOK STRATEGY */
// Redirect the user to Facebook for authentication.  When complete,
// Facebook will redirect the user back to the application at
//     /auth/facebook/callback//
app.get('/auth/facebook', passport.authenticate('facebook', { scope : ['email']}));
/* FACEBOOK STRATEGY */
// Facebook will redirect the user to this URL after approval.  Finish the
// authentication process by attempting to obtain an access token.  If
// access was granted, the user will be logged in.  Otherwise,
// authentication has failed.

    app.get('/auth/facebook/callback',
        passport.authenticate('facebook', { failureRedirect: '/' }),
        function (req, res) {
            // Successful authentication, redirect home.
            res.redirect('../../app.html');
        });


app.get('/', function (req, res) {
    res.redirect('/');
});

app.get('/app', isLoggedIn, function (req, res) {
    res.redirect('app.html');
});

app.post('/meal', function (req, res) {
    //Testing Logs
        /*console.log(req.body.foodId);
        console.log(req.body.quantity);
        console.log(req.body.period);
        console.log(req.body);
        */

    //Check whether or not this is the first food a user drops on the diet
    var dietId = -1;

    db.diet.findOne( { where : { userIdUser : req.user.idUser } } ).then(function (diet, err) {
        if(err) {
            return done(err);
        }
        if(diet) {
            dietId = diet.idDiet;
        } else {
            db.diet.create( { userIdUser : req.user.idUser }).then(function (diet) {
                dietId = diet.idDiet;
            });
        }
    });

    db.meal.create({
        foodId : req.body.foodId,
        quantity : req.body.quantity,
        period : req.body.period
    }).then(function (meal) {
        console.log(meal.mealId);
        res.json({ mealId : meal.mealId});
    });
});

从我在Passport的文档中看到的,每当我使用req.user时都应该调用我实现的deserializeUser函数,但是,使用我的console.logs(),我发现在登录后调用了serializeUser,因此它是存储我的会话,但从不调用deserializeUser!永远 .

有关如何绕过这个的任何想法?任何帮助表示赞赏,谢谢!

1 回答

相关问题