Front-end: React with React-router + axios
Back-end: express with express-session, passport, passport-local, passport-local-mongoose
I want to use 24 hour login sessions and use is.Authenticated() method from passport-local to verify if user is loggedIN
I found 2 very similar questions in here, both of them are not answered:
my app.js:
const sessionConfig = {
store,
name: "session",
secret: secret,
resave: false,
saveUninitialized: true,
domain: 'localhost:3000',
cookie: {
httpOnly: true,
//secure:true, //enable when deployed
expires: Date.now() + 1000 * 60 * 60 * 24,
maxAge: 1000 * 60 * 60 * 24,
}
}
const corsOptions = {
origin: "http://localhost:3000",
credentials: true,
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
"Access-Control-Allow-Credentials": "true"
};
app.use(cors(corsOptions));
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session(sessionConfig));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(Gymbro.authenticate()));
passport.serializeUser(Gymbro.serializeUser());
passport.deserializeUser(Gymbro.deserializeUser());
here login route that seem to work correctly:
router.post("/login", passport.authenticate("local", {session: true}), catchAsync(async (req,res)=>{
console.log(req.isAuthenticated()) //returns true
console.log(req.user) // returns full user object
console.log(req.session) // returns Session with passport part ( passport:{user: 'jon'})
res.send("you logged in")
}))
Than a user goes to other screen in React router which will trigger get request
axios.get(`http://localhost:3001/gym/all`, {withCredentials: true}).then((res) => {
setGyms(res.data.gyms);
router.get("/all", catchAsync(async (req, res) => {
console.log(req.isAuthenticated()) // returns false ( i will need only authenticated people to get response)
console.log(req.session) // returns Session but without any passport bit
const gyms = await Gym.find({});
res.send({ gyms });
}));
store is connected properly, Can axios be stripping my get request? even i opt withCredentials?