I build a simple web application where the user has notes. I want the user to be able to sign in with a google account as well, but the user didn't save into the database. The local login works but the social login doesn't. Wherever I searched I only found a solution in which mongodb was used. What is the correct way with mysql? Here is my passport.js file:
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((req, user, done) => {
conn.query("SELECT * FROM user WHERE id = ? OR facebook_id = ? OR google_id", [user.id,
user.facebook_id, user.google_id], (err, rows) => {
if (err) {
console.log(err);
return done(null, err);
}
done(null, user);
});
});
passport.use(new GoogleStrategy({
clientID: configAuth.googleAuth.clientID,
clientSecret: configAuth.googleAuth.clientSecret,
callbackURL: configAuth.googleAuth.callbackURL,
passReqToCallback: true,
profileFields: configAuth.googleAuth.profileFields
},
function (req, accessToken, refreshToken, profile, done) {
process.nextTick(function () {
conn.query("SELECT * FROM user WHERE google_id = ?", [profile.id], (err, user) => {
if (err) {
return done(err);
} else if (user) {
return done(null, user);
} else {
let newUser = {
google_id: profile.id,
google_token: accessToken,
google_email: profile.emails[0].value,
google_name: profle.name.givenName + ' ' + profile.name.familyName
};
conn.query("INSERT INTO user (google_id, google_token, google_email, google_name) VALUES (?, ?, ?, ?)",
[newUser.google_id, newUser.google_token, newUser.google_email, newUser.google_name], (err, rows) => {
if (err) {
console.log(err);
}
return done(null, newUser);
})
}
});
});
}
));
And here are the routes:
app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
app.get('/auth/google/callback', passport.authenticate('google', {
successRedirect: '/main',
failureRedirect: '/'
}));
I can log in, I didn't receive an error message, but if I want to assign a new note to the user it doesn't add it because it doesn't save the user to the database.