V
V
Valery Orlov2018-08-25 15:11:01
Node.js
Valery Orlov, 2018-08-25 15:11:01

How to record sessions of only authorized users?

The following code adds sessions to the database, all who visited the site. But I would like the sessions to be saved only for authorized users. Is it realistic to achieve this?

const express  = require('express');
const app      = express();
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const bodyParser = require("body-parser");
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
const port     = process.env.PORT || 8000;
const passport = require('passport');
const logger = require('morgan');
const flash    = require('connect-flash');

const configDB = require('./config/database.js');

mongoose.connect(configDB.url, { useNewUrlParser: true }); 

require('./config/passport')(passport); 

app.use('/views',express.static('views'));
app.use(logger('dev'));									
app.use(cookieParser()); 
app.use(bodyParser.urlencoded({ extended: false }));  
app.use(bodyParser.json());
app.set('view engine', 'ejs'); 
  app.use(session({
    key: 'FUSTSESSION',
    secret:'secret_mega_very_word',
    resave: true,
    saveUninitialized: true,
    cookie: { maxAge: 604800 },					
    store: new MongoStore({
      mongooseConnection:mongoose.connection,
      ttl :  604800
    }
    )
}));
  app.use(passport.initialize());
  app.use(passport.session()); 
  app.use(flash()); 

require('./app/routes.js')(app, passport); 

app.listen(port);
console.log('NodeJS слушает порт: ' + port);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question