快速护照会议不工作 [英] Express Passport Session not working

查看:137
本文介绍了快速护照会议不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我的理解是,一旦他们注册/登录,我可以使用req.user访问他们的id并正确存储他们的操作,但它不工作。



这是处理护照的server.js文件的一部分。另外,我使用Sequelize作为一个ORM,但是处理数据库的所有内容都没有req.user部分是完美的。

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

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

/ ******护照功能****** /
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(新的FacebookStrategy({
//存储在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){
//使用下一个tick来利用异步属性
process.nextTick(function(){
db.user.findOne({where:{idUser:profile.id}})然后(function(user,err){
if(err){
return done(err);
}
if(user){
return done(null,user);
} else {
//创建用户
db.user.create ({
idUser:profile.id,
token:accessToken ,
nameUser:profile.displayName,
email:profile.emails [0] .value,
sex:profile.gender
});

//找到用户(因此检查是否确实创建)并返回
db.user.findOne({where:{idUser:profile.id}})然后( function(user,err){
if(user){
return done(null,user);
} else {
return done(err);
}
});
}
});
});
}));

/ * FACEBOOK STRATEGY * /
//将用户重定向到Facebook进行身份验证。完成后,
// Facebook将把用户重定向到
// / auth / facebook / callback //
app.get('/ auth / facebook',护照)。认证('facebook',{scope:['email']}));
/ * FACEBOOK STRATEGY * /
// Facebook将批准后将用户重定向到此URL。尝试获取访问令牌来完成
//身份验证过程。如果
//访问被授予,用户将被登录,否则
//身份验证失败。

app.get('/ auth / facebook / callback',
passport.authenticate('facebook',{failureRedirect:'/'}),
function(req, res){
//成功验证,重定向到家。
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){
//测试日志
/*console.log(req.body.foodId);
console.log(req.body.quantity);
console.log(req.body.period);
console.log(req.body);
* /

//检查这是否是用户降低饮食的第一个食物
var dietId = -1;

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

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

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



有关如何解决这个问题的任何想法?任何帮助,谢谢!

解决方案

您需要 express会话中间件,然后调用 passport.session()。请阅读有关更多信息的 passportjs配置部分文档。


I'm building a Node application in which the users must register or login, then when they drag and drop some elements (the front end is all working) I store on the database their action with their corresponding userId.

My understanding is that once they are registered/logged in, I can use the req.user to access their id and correctly store their actions, however it isn't working.

Here is the section of my server.js file that deals with Passport. Also, I'm using Sequelize as an ORM, but everything dealing with the database works perfect without the req.user part.

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

From what I read on the documentation for Passport, the deserializeUser function that I implemented should be called whenever I use req.user, however, with my console.logs(), I found out that serializeUser is called after logging in, therefore it is storing my session, but deserializeUser is never called! Ever.

Any idea on how to get around this? Any help is appreciated, thank you!

解决方案

You need the express session middleware before calling passport.session(). Read the passportjs configuration section on documentation for more info.

这篇关于快速护照会议不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆