Cookies and Sessions in Node Express JS, Mongo DB APP

Sessions and cookies play a very important role in a web app. These are used to store information. Cookies are used to store information in the client-side system/browser. Sessions are stores both in client and server systems.

Node Packages Required for Sessions an Cookies

> passport

> passport-local

> passport-local-mongoose

> express-session

Installing these packages:

npm i passport passport-local passport-local-mongoose express-session

Full Code:

//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));

app.use(session({
  secret: "Our little secret",
  resave: false,
  saveUninitialized: false
}));

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

const uri = "mongodb://localhost:27017/usersDB"
mongoose.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.set('useCreateIndex', true);

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

userSchema.plugin(passportLocalMongoose)

const User = new mongoose.model("User", userSchema);


passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.get('/', function(req, res){
    res.render('home');
});

app.get('/login', function(req, res){
    res.render('login');
});

app.get('/register', function(req, res){
    res.render('register');
});

app.get("/secrets", function(req,res){
  if(req.isAuthenticated()){
    res.render("secrets");
  }else{
    res.redirect("/login");
  }
});

app.get("/logout", function(req,res){
  req.logout();
  res.redirect("/");
});


app.post("/register", function(req,res){
  User.register({username: req.body.username}, req.body.password, function(err, user){
    if(err){
      console.log(err);
      res.redirect("/register");
    }else{
      passport.authenticate("local")(req,res, function(){
        res.redirect("/secrets");
      });
    }
  });
});

app.post("/login", function(req,res){

  const user = new User({
    username: req.body.username,
    password: req.body.password
  });

  req.login(user, function(err){
    if(err){
      console.log(err);
    }else{
      passport.authenticate("local")(req,res, function(){
      res.redirect("/secrets");
      
      });
    }
  });

});

app.listen(3000, function() {
    console.log("Server started on port 3000");
  });

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *