Nodegeek
Nodegeek

Reputation: 280

User Session cookies process_Nodejs /passport

I'm trying to create session - cookies in order to maintain user login and then do some authorization to some content but the problem that this system is too complex , session , cookies , storage'memory'

cause I read in many sites that Session-only cookies, stores information in the browser memory, and is available for the duration of the browser session. In other words, the data stored inside a session cookie is available from the time of storage until the browser is closed. Moving from page to page during this time does not erase the data.

What I'm trying to use is create session for every user using passport using the configuration below but I didn"t succeed ,

the code sessions is below app.js

require('./models/db')
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const passport = require('passport');
const flash = require('connect-flash');
const session = require('express-session');
const bodyParser = require('body-parser')

const app = express();

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


// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
app.use('/public/uploads',express.static(__dirname + '/public/uploads'))
// Express body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// Express session
app.use(
  session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
  })
);

// Passport middleware
app.use(passport.initialize());
app.use(passport.session());

// Connect flash
app.use(flash());

// Global variables
app.use(function(req, res, next) {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  next();
});

// Routes
app.use('/', require('./routes/index.js'));
app.use('/gallery',require('./routes/gallery.js'));
app.use('/users', require('./routes/users.js'));
app.use('/me', require('./routes/publish.js'))
app.use('/api',require('./routes/ChangePassword'));
app.use('/post', require('./routes/home.js'))
const PORT = process.env.PORT || 5000;

app.listen(PORT, console.log(`Server started on port ${PORT}`));

and the routes for the user.js for the login is below

router.post('/login', (req, res, next) => {
passport.authenticate('local', {
    successRedirect: '/users/home',
    failureRedirect: '/users/login',
    failureFlash: true
  })(req, res, next);
});

Any recommandation on How achieving it using an efficient process ?

Best Regards,

Upvotes: 0

Views: 73

Answers (1)

Syed Mishar Newaz
Syed Mishar Newaz

Reputation: 567

Remember, when using express.js, the order of middleware matters. You are using EJS middleware before passport.js. That's why your pages are being rendered before session is initialized.

Upvotes: 1

Related Questions