My PassportJS setup doing something weird, I can see req.user
after logged-in in the deserialize
function but after all req.isAuthenticated()
false
and no req.user
found. I have already referred a bunch of questions regarding this issue on StackOverflow, almost every question on StackOverflow. Nothing works for me, not sure what is the case here. I'm posing my code, can someone pls tell me what is wrong here and why it's happening. At least a fix! :(
I'm using passport-google-oauth as my strategy. Also, the client is an Angular app.
I also tried with passport-google-oauth20 by accessing directly.
What I found is, in
social_logins.google_callback
thereq.user
can be found and alsoreq.isAuthenticated()
returnstrue
. After the redirect happens it won't work.
Thanks in advance!
// app.js
const pgSession = require('connect-pg-simple')(session);
app.set('trust proxy', 1);
/** @type {session.CookieOptions} */
const cookieOptions = {
path: '/',
secure: false,
httpOnly: false,
maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days
};
app.use(session({
secret: require('./config').session.secret, // session secret
cookie: cookieOptions,
proxy: true,
name: config.session.name,
resave: false,
saveUninitialized: true,
store: new pgSession({
pool: db.pool,
tableName: 'sess'
}),
}));
require('./config/passport')(passport);
app.use(passport.initialize());
app.use(passport.session());
// passport.js
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser(async (user, done) => {
done(null, user);
});
// passport login.js
app.get('/social-logins/connect/google', passport.authenticate('google-login', {
successRedirect: '/social-logins/google',
failureRedirect: '/social-logins/google',
scope: ['profile', 'email'],
failureFlash: true,
}));
// routes/index.js
router.get('/social-logins/google', social_logins.google_callback);
// callback funtion
social_logins.google_callback = async (req, res) => {
try {
const { user } = req;
if (!user) return res.redirect('https://localhost:3000/auth/login?message=Login Failed');
const url = `https://localhost:3000/auth/dashboard`;
req.session.save(() => {
return res.redirect(url);
});
} catch (error) {
log_error(error);
res.redirect(`https://localhost:3000/auth/login?error=true`);
}
};
// passport strategy
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
module.exports = new GoogleStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: 'https://localhost:3000/social-logins/connect/google',
passReqToCallback: true
}, async (req, accessToken, refreshToken, profile, done) => {
try {
const acc = {}; // find from db and assign db.query('select * from users where id = $1', [profile.id]);
return done(false, acc, { message: 'User successfully logged in' });
} catch (error) {
return done(error);
}
});
I resolved this by setting
domain
tocookieOptions
.