1

I'm using express-session, passport, connect-mongo and mongodb-atlas last versions, for create sessions and save them on the server, the problem is when app.use(passport.session()), this session is created even if the user is not logged in.

app.use(session({
    // key: "id",
    secret: process.env.SESSION_SECRET,
    cookie: {
        httpOnly: true,
        sameSite: true,

        // secure: process.env.IN_PROD,
        maxAge: 10800000,
    }, // three hours in miliseconds
    store: new MongoStore({
        mongooseConnection: mongoose.connection,
        autoReconnect: true,
        collection: "admin.mySessions",
        serialize: serialize

    }),
    resave: false,
    saveUninitialized: false,
    name: 'Id'
}));

this causes that when passport is initialized and the passport session the cookie is saved with session id and the session is saved in the mongodb mi question is how save session only for users logged in

1 Answers1

0

Hello mate I am not aware of mongo-session, but from your explanation I understand that you are creating token for users even if they don't login. I suggest you create a new token each time a user hits login API and expire the token once he logs out.By following this token is generated only for active users.

naveen ashok
  • 311
  • 1
  • 16
  • hello what happens is that when request to any route of my api, the session is generated and saved in mongodb, what I want is that it is only saved when it is logged in. i'm sorry if I have not explained myself well – Juan Manuel Apr 05 '19 at 08:55
  • Please do correct me If I am wrong so you have generated token only for logged in user's as you expected what's the actual issue @JuanManuel – naveen ashok Apr 05 '19 at 11:36
  • You're right, I thought that unauthenticated users did not have to generate a session. This causes me to have another questions: 1- users unauthenticated generate sessions and save in mongodb store, is standard if yes? 2- how to prevent malicious users or robots from saturating the mongodb database by generate sessions without users over and over again? thanks for answering @naveenashok – Juan Manuel Apr 05 '19 at 12:31
  • Thanks for the healthy question @JuanManuel I would recommend to use the username and password to be included during token generation from which you can verify only the user who has generated the token is using it. That's how I validate it using JWT token usually I will encrypt the token along with the username and password which will be validated on each API. [please refer](https://www.npmjs.com/package/jsonwebtoken)!. While signing the token I will pass user details as payload. – naveen ashok Apr 05 '19 at 12:45
  • You are welcome @JuanManuel. Let me know if you find an alternate – naveen ashok Apr 05 '19 at 14:40