Sessions And Cookies

Sessions and Cookies are the basics of managing user state. Let's dig deep into that with Nodejs.

These two are used to Storing data in the memory or client-side
More Briefly

1.Cookies

stored in the client side

user--------------------------------------->Server
                    request

when user logged in we kept their login data in a cookie and
        send back to client via response header


user<-------------------------------------- Server
                response + cookie


This cookie can be used again for auto login
Cookie is a great tool for tracking users
Sensitive data not store in the client side -> so cookies should not store them

2.Sessions

Stored data in the server-side (backend)


user----------------------------------------------->Server
                        request


                   server stores session
             in the database => session Storage


user<----------------------------------------------- Server
                    response + cookie
                (Stored the session Id )
        (hashed id-> nobody can read-only server))

Ok enough theory. Let’s go to Coding..!!

Cookies


Setting up a cookie

exports.postLogin = (req, res, next) => {
 
 /*
    here execute the login logics, validations etc
    and set the cookie

    setting a Cookie -> setting a header
    'Set-Cookie' - reserved
*/ 

  res.setHeader("Set-Cookie", "loggedIn = true");
  console.log("cookie setts..!!!");
  res.redirect("/");
 
};

Accessing a cookie

exports.getLogin = (req, res, next) => {
  //console.log(req.get("Cookie")); <-accessing the cookie

  let loggedIn;
  if (req.get("Cookie")) {
    loggedIn = req.get("Cookie").split("=")[1];
            //extract the value and set for validity
    console.log("logging in------>>" + loggedIn);
  } else {
    loggedIn = false;
  }

  res.render("auth/login", {
    pageTitle: "Login Page",
    active: "login",
    isAuthenticated: loggedIn,
  });
};

Now with this res.render method we can pass the header value
in the login.ejs page.
we can write the logic to show content according to the cookie value.

<%if (isAuthenticated) {%>
      <li >
        //show the content here
      </li>

  <%}%>
But drawback -> we can change the cookie value easily
(Firefox) inspect element -> storage-> cookies <-in here


Configuring Cookies -> more methods

res.setHeader("Set-Cookie", "loggedIn = true ;Max-Age=10");
 //look about Expires also-> need to set specific date
 //this cookie will last for 10 seconds

 res.setHeader("Set-Cookie", "loggedIn = true ;Secure");
 //this cookie will only be set if the page is served via https

 res.setHeader("Set-Cookie", "loggedIn = true ;HttpOnly");
 //now we cant access the cookie value through client side java script
 //this will protect from cross site scripting attacks


Sessions


1. Install the express session module.
npm install --save express-session

2. Initialize session middleware

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

Secret is used for signing the hash -> secretly store the id and the cookie

in production this should be long string value
 

resave :false - the session will not be saved on every request that is done / save only if change is done -> improve performance

saveUninitialized :false -> ensures no session get saved for a request that doesn’t need to be saved
 

also we can configure the cookie in here -> cookie:{maxAge:10}

·       

3. Auth.js controller

exports.postLogin = (req, res, next) => {
    //req.session. <= setting a value to session object
(add any key=> req.session.yourId="sdfsdf")
  req.session.isLoggedIn = true;
  res.redirect("/");
};


It still needs a cookie to identify the user
but sensitive info store on the server => client cant modify it

4. Store the sessions in the DB

In the github page -> expressjs/session there are docs to connect to different dbs..
let’s connect with mongo. for that
               npm install --save connect-mongodb-session

5. Configure Store

const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);

const MONGOCONNECT = "mongodb://localhost:27017/nodefirst";

const store = new MongoDBStore({
  uri: MONGOCONNECT,
  collection: "sessions",
  //can set expires also to clean up automatically
});

//also add the store to the middleware
app.use(
  session({
    secret: "my secret",
    saveUninitialized: false,
    resave: false,
    store: store,
  })
);

6. In Auth Controller

exports.postLogin = (req, res, next) => {
  req.session.isLoggedIn = true;
  // we can add any data to the session (as previous)

  res.redirect("/");
};

exports.getLogin = (req, res, next) => {
  console.log(req.session.isLoggedIn);
  // now we accessing the session data through the db

  res.render("auth/login", {
    pageTitle: "Login Page",
    active: "login",
    isAuthenticated: req.session.isLoggedIn, 
  // use it for verify the session
  });
};


Destroying the Session

view       -> logout button -> post request to action='/logout'
router.js  -> router.post("/logout", authController.postLogout);

exports.postLogout = (req, res, next) => {
  req.session.destroy(() => {
    res.redirect("/");
  });
};

Post a Comment

0 Comments