I am trying to get session data, using passport js. When I use the /test or /test2 route, I get the session data. If I try to console.log in these routes, I get the whole session data. But when I try it with /user_data, I dont seem to get the expected response. Where am I going wrong here? I am using passport.js and express session. When going through the /user_data route, I get the following output:
Session {
cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }
}
Here is the code I am using, it is fairly dirty as of now as I am trying to tinker around.
const express = require('express')
const app = express()
const session = require('express-session');
const port = 3000
const passport =require("passport")
const GoogleStrategy = require('passport-google-oauth2').Strategy;
const bodyParser = require("body-parser");
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new GoogleStrategy({
clientID:"some.com",
clientSecret:"some_secret",
callbackURL: "http://localhost:3000/auth/google/callback",
passReqToCallback : true
},
function(request, accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));
app.use(session({
resave: false,
saveUninitialized: true,
secret: 'SECRET'
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get("/failed", (req, res) => {
res.send("Failed")
})
app.get("/success", (req, res) => {
res.send(`Welcome ${req.user.email}`)
})
app.get('/auth/google',
passport.authenticate('google', {
scope:
['email', 'profile']
}
));
app.get('/auth/google/callback',
passport.authenticate('google', {
failureRedirect: '/failed',
}),
function (req, res) {
res.redirect('/')
}
);
app.get("/test",(req,res)=>{
let sess = req.session;
console.log(sess);
var email=sess.passport.user.email;
var netid=email.split('@')[0];
req.session.netid=netid;
console.log(netid);
// console.log(sess.user.id);
res.send("test")
});
app.get("/test2",(req,res)=>{
let sess = req.session;
console.log(sess);
var netid=sess.netid;
console.log(netid);
res.send("test2")
});
app.get("/user_data",(req,res)=>{
var sess = req.session;
console.log(sess.passport);
res.send(sess.passport);
});
app.get('/logout', function(req, res){req.logOut();res.redirect('/');});
app.get('/', (req, res) => {res.sendFile(__dirname "/pages/index.html");})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
CodePudding user response:
In theory user_data is just another endpoint and on that basis it should work just like test and test2.
However, user_data could be a reserved name. Try changing that endpoint to something else.