无法将用户序列化为使用password.js和cookie-session的会话

时间:2018-08-07 23:54:00

标签: node.js express passport.js google-plus-signin cookie-session

我正在尝试通过Google+ OAuth进行身份验证。为此,我将带护照的js与Google策略结合使用(passport-google-oauth20模块),但是当护照尝试将用户序列化为会话(使用cookie-session)时,我陷入了错误。

登录Google网站后出现错误。

代码:

passport.serializeUser((user, done) => {
    console.log('serialize ' + (user.id == undefined ? null : user.id));
    console.log(user);
    return done(null, (user.id == undefined ? null : user.id));
});

passport.deserializeUser((id, done) => {
console.log('dserialize id ' + id);
   db.connect((err, client, don) => {
        if (err) throw err
        client.query('SELECT * FROM "AppUsers" WHERE "googleId" = $1', [id], (err, res) => {
            don();
            if (err) {
               console.log(err.stack);
            } else {
               console.log(res.rows[0]);
               if (res.rows[0]) {return done(null, res.rows[0]);}
               else {return done(null, null);}
            }
        });
    });
});

编辑:

async function checkGoogle(profile) {
    const client = await db.connect();
    try {
        const { rows } = await client.query('SELECT * FROM "AppUsers" WHERE "googleId" = $1', [profile.id]);
        let currentUser = rows[0];
        console.log(currentUser);
        if (currentUser) {
            console.log('in db ' + currentUser.id);
            console.log(currentUser);
            return currentUser;
        } else {
            const { rows } = await client.query('INSERT INTO "AppUsers" ("googleId") VALUES ($1) RETURNING *', [profile.id]);
            let newUser = rows[0];
            console.log('not in db ' + newUser.id);
            console.log(newUser);
            return newUser;
        }
    } catch (error) {
        alert(error);
    } finally {
        client.release();
    }
}

passport.use(
    new GoogleStrategy({
        // options for google strategy
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret,
        callbackURL: '/auth/google/redirect'
    }, (accessToken, refreshToken, profile, done) => {
        // check if user already exists in our own db
        return done(null, checkGoogle(profile));
    })
);

输出: The error screen

请告诉我您是否需要更多信息。

1 个答案:

答案 0 :(得分:0)

您需要等待 checkGoogle 函数通过使用async / await返回数据。

passport.use(
    new GoogleStrategy({
        // options for google strategy
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret,
        callbackURL: '/auth/google/redirect'
    }, async (accessToken, refreshToken, profile, done) => {
        const user = await checkGoogle(profile);
        // check if user already exists in our own db
        return done(null, user);
    })
);