2

I have a website that runs on a CentOS 7 server, and I use pm2 for production, when I run pm2 logs this appears:

"Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak memory, and will not scale past a single process."

This worked well and authenticated, but after 5 days, this only authenticates in my PC, if I try on another PC, my login doesn't authenticate (work) and redirects me to the login page. Why does this happen?

I've found something about cookie-sessions, is cookie-sessions what I need? If yes how can I use it?

Here is my current code:

      const express = require('express')
      const bodyParser = require('body-parser')
      const mongoose = require('mongoose')
      const session = require('express-session')
      const passport =  require('passport')
      const passportLocalMongoose =  require('passport-local-mongoose')
      const _ = require('lodash')
      const app = express()
      app.use(express.static('public'))
      app.set('view engine', 'ejs')
      app.use(bodyParser.urlencoded({
          extended: true
      }))
      mongoose.connect("mongodb+srv://admin-Admin:password@cluster0-babnh.mongodb.net/collection", 
      {useNewUrlParser: true, useUnifiedTopology: true}).then(() => console.log('DB 
      Connected!')).catch(err => {
          console.log(err.message)
      })
      mongoose.set('useCreateIndex', true)

      app.use(session({
          secret: restricted.expressSession.secret,
          resave: false,
         saveUninitialized: false
      }))

      app.use(passport.initialize())
      app.use(passport.session())

      const userSchema = new mongoose.Schema ({
          email: String,
          password: String
      })

     userSchema.plugin(passportLocalMongoose)

     const User = new mongoose.model('User', userSchema)

     module.exports = mongoose.model('User', userSchema)

      passport.use(User.createStrategy())
      passport.serializeUser(User.serializeUser())
      passport.deserializeUser(User.deserializeUser()) 

     app.get('/', (req, res) => {
          res.render('login')
      })

     app.post('/', (req, res) =>{
          const user = new User({
              username: req.body.username,
              password: req.body.password
          })
          req.login(user, function(errLogin){
              if(errLogin) {
                  console.log(errLogin)
              } else{
                  passport.authenticate('local')(req, res, function(){
                      res.redirect('/home')
                  })
              }
         })
      })
Jack
  • 2,891
  • 11
  • 48
  • 65

1 Answers1

1
var mongoUri = 'mongodb://username:password@foo.mongohq.com/port/db'

app.use(session({
      secret: restricted.expressSession.secret,
      resave: false,
      saveUninitialized: false
      store   : new MongoStore({url  : mongoUri})
}))

use connect-mongo module to store express session in mongoDb.