Week 10 - Sessions and Cookies

Tools and modules to track user sessions. Basic authentication discussed.


Sessions and Cookies

It is common to collect user information that persists for the duration of the user's visit on the web page.

Temporary user information can be stored in sessions (server side) and cookies client side.

Sessions

Sessions are hold temporary user information on the server in memory. ExpressJS offers session utility to easily configure, write and access session information for a specific user.

Cookies

Cookies will hold user information in the browser and are associated by the domain on which it was created. A web site can only access cookies from its own domain. Cookies have a shelf life, a time that can be defined by the developer.

Cookies can be created by the server or by Javascript on the browser.

A cookie might hold information such as your username, your shopping cart or a tracking number.

Demo

Set a username and a favorite color on our Astronaut demo app

http://itpdwdexpresstemplates.herokuapp.com/

Configuring Express

It is common to use both cookies and sessions together.

In app.js, inside the app.configure function

app.configure(function(){
  ...
  // COOKIES COOKIES COOKIES
  // INSERT CODE ABOVE app.use(app.router);

  // pass a secret to cookieParser() for signed cookies
  app.use(express.cookieParser('SECRET_COOKIE_HASH_HERE'));
  app.use(express.cookieSession()); // add req.session cookie support

  // make sesssion information available to all templates
  app.use(function(req, res, next){
    res.locals.sessionUserName = req.session.userName;
    res.locals.sessionUserColor = req.session.userColor;
    next();
  });

  app.use(app.router);
  ...

});

Passport Authentication

Passport is an amazing authentication system.

Demo includes Passport Local Strategy with Blog post and User example.

Demo: http://dwd-nodejs-passport.herokuapp.com/
Github : https://github.com/johnschimmel/DWD-NodeJS-Passport-Demo




Assignment

Continue to work on your project ideas. Be prepared to show progress in class next week.

Review the Passport Authentication example code.

comments powered by Disqus