Start learning with our library of video tutorials taught by experts. Get started

Node.js Essential Training
Illustration by Richard Downs

Logging in to Express applications using Passport


From:

Node.js Essential Training

with Joseph LeBlanc

Video: Logging in to Express applications using Passport

One of the oldest patterns in web applications is to have someone log in to your website. Then use a cookie to identify the user on subsequent requests. Fortunately, there's more express middleware available for handling logins with sessions. In this video, we''ll handle user logins, and then use middleware to store that information in a session. First, let's set up our project. Go to exercise files in chapter seven, and then in video five, copy the start folder to the desktop. Next, let's go to terminal and install all of the modules.
Expand all | Collapse all
  1. 3m 9s
    1. Welcome
      42s
    2. What you should know before watching this course
      57s
    3. Using the exercise files
      47s
    4. Using the challenges
      43s
  2. 18m 50s
    1. Why use Node.js?
      2m 1s
    2. Choosing a Node.js installation process
      4m 56s
    3. Installing Node.js on the Mac
      2m 5s
    4. Installing Node.js on Windows
      1m 43s
    5. Installing Node.js via Node Version Manager on Ubuntu Linux
      4m 45s
    6. Installing Node.js via Node Version Manager on a Mac
      3m 20s
  3. 13m 54s
    1. Exploring language additions to the V8 JavaScript engine
      3m 38s
    2. Understanding require() and modules
      6m 39s
    3. Understanding callback execution in the event loop
      3m 37s
  4. 12m 23s
    1. Initializing Node.js projects
      2m 37s
    2. Finding an NPM
      3m 30s
    3. Maintaining projects using the npm command
      6m 16s
  5. 21m 4s
    1. Creating modules with getters and setters
      6m 33s
    2. Understanding module caching and scopes
      6m 15s
    3. Implementing JavaScript creational patterns
      5m 8s
    4. Challenge: Leveraging module caching
      55s
    5. Solution: Leveraging module caching
      2m 13s
  6. 32m 27s
    1. Starting Express applications
      3m 42s
    2. Handling GET requests returning JSON
      3m 26s
    3. Navigating large datasets using request variables in routes
      5m 4s
    4. Modifying data through PUT requests
      4m 32s
    5. Supplying middleware to modify HTTP response headers
      4m 37s
    6. Generating HTML views in Jade
      8m 9s
    7. Challenge: List all records as JSON
      37s
    8. Solution: List all records as JSON
      2m 20s
  7. 25m 37s
    1. Evaluating unit testing methodologies
      3m 8s
    2. Isolating existing code for testing
      6m 47s
    3. Supplying helpers for test data
      2m 35s
    4. Writing unit tests with Mocha
      6m 5s
    5. Simulating HTTP requests with SuperTest
      7m 2s
  8. 28m 45s
    1. Connecting to MongoDB via Mongoose
      4m 16s
    2. Defining schemas for collections in Mongoose
      3m 47s
    3. Querying MongoDB collections
      5m 32s
    4. Persisting Express sessions through MongoDB and mongo-connect
      7m 6s
    5. Logging in to Express applications using Passport
      8m 4s
  9. 21m 47s
    1. Controlling the built-in REPL
      4m 18s
    2. Constructing a custom REPL
      5m 40s
    3. Receiving command-line arguments with Optimist
      6m 14s
    4. Building command-line tools
      3m 35s
    5. Challenge: Launch a custom REPL from a command
      41s
    6. Solution: Launch a custom REPL from a command
      1m 19s
  10. 15m 46s
    1. Emitting events and attaching listeners
      5m 32s
    2. Streaming chunked data through readable streams
      2m 33s
    3. Controlling readable streams
      1m 52s
    4. Piping readable data into writable streams
      2m 10s
    5. Handling duplex streams over TCP
      3m 39s
  11. 4m 6s
    1. Deploying projects to cloud hosting services
      2m 36s
    2. Finding Node.js resources
      1m 30s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
Node.js Essential Training
3h 17m Intermediate Oct 16, 2013

Viewers: in countries Watching now:

Node.js is a powerful tool for controlling web servers, building applications, and creating event-driven programming. And it brings JavaScript—a language familiar to all web developers—into an environment independent of web browsers. Learn all about Node.js and start creating JavaScript applications in this course with Joseph LeBlanc. He shows how to install Node.js on Mac, Windows, and Linux and dives deep into its modules and Express framework for app development. Learn how to unit test your code, start sessions on web servers, stream data, and create simple command-line tools.

Topics include:
  • Why use Node.js?
  • Installing Node.js
  • Understanding the event loop
  • Initializing Node.js projects
  • Creating modules with getters and setters
  • Starting Express applications
  • Testing your code
  • Working with sessions and databases
  • Building command-line tools
  • Emitting events and attaching listeners
  • Controlling readable streams
Subjects:
Developer Servers Cloud Computing Programming Languages
Software:
JavaScript Node.js
Author:
Joseph LeBlanc

Logging in to Express applications using Passport

One of the oldest patterns in web applications is to have someone log in to your website. Then use a cookie to identify the user on subsequent requests. Fortunately, there's more express middleware available for handling logins with sessions. In this video, we''ll handle user logins, and then use middleware to store that information in a session. First, let's set up our project. Go to exercise files in chapter seven, and then in video five, copy the start folder to the desktop. Next, let's go to terminal and install all of the modules.

Change directory to that folder, I'm just going to drag it in, and then press return, and then type npm install. And then press return. Now that we've installed all the existing modules, let's add a couple more. There's one called Passport, Passport is a module that acts as middleware for Express and it handles logins. So let's install that now. Type in npm install --save, and passport. There's also a specific module I want to use with Passport called passport -local.

So I'm going to install that as well. Press Up on the keyboard and then just add -local to the end. Now let's start configuring passport. There's a snippet file in the exercise files, so go back to chapter seven in video five and go to the snippets folder. There's an auth.js file. Copy that directly in to the root of the start folder. Now, let's open the start folder in sublime text. Let's take a look at this auth.js file. On lines one and two, we're requiring the two modules that we just downloaded.

The first is passport, which is the main library, and then the second is passport-local. And we're extracting the strategy property from that module. Passport has a concept of strategies where you can use different strategies for logging into a website. So for instance, if you've been to website where you can create an account on the website or you can use your Facebook login, it's the same concept. Passport allows you to use multiple strategies on the same site, or you can use just one. In this case we're using local strategy.

Local strategy is the most flexible strategy if you want to implement your own custom login logic. And in this case that's exactly what we want to do. We're passing in a function to handle the logins and it's going to receive the username and password and a function named done. Done gets called as soon as we decide we've either authenticated the user or we've rejected it. In this case, we only have one user named admin. Typically you would have a database call here that we would check against, or some other place where usernames and passwords would be stored.

But in this case, we just have one username and the password is lynda. If the login is successful, we return done, along with an object with the user information. Otherwise, we pass false. There are two functions that must be defined so that the user information gets stored in the session. There are serializeUser and deserializeUser. You don't need to call either of these functions directly. Now that we have Passport configured for our uses, we can export it from this module.

Now let's add Passport as middleware to our application, so go to app.js. Just underneath where we're requiring connect-mongo, let's get Passport. Instead of requiring Passport directly, we're going to require our off module that we just defined. Next, let's use Passport as middleware in our application. Scroll down to the line just above body parser, and make some space. Next, we're going to call app.use we're going to call the initialize method on Passport right here.

This first line starts up Passport; duplicate that line. And then change initialize to session. On this line we're telling Passport to use the sessions in Express. It's possible to use Passport in such a way where you don't have a session. For instance, maybe you just need someone to log in once, and authenticate that request, but you don't really need to use sessions after that. However, in our case we want to maintain a session. So we're telling Passport to store the sessions. Now we need to add some routes.

We're going to have one route that displays a login form, and then we're going to have a second route that handles that login form. And then finally, we're going to have one more route that displays user information after someone's logged in. So let's create those three routes now. The first one is login. We'll define the handler function in a moment. Then the second route is going to be a post request to login. Instead of handling this in the routes file, we're going to handle it right here. We're going to call passport.authenticate. Authenticate takes two arguments.

The first argument is the strategy that we want to use. Then the second argument is an object. We're going to use this object to define two things, we're going to define two redirect routes. The first is going to be the failure redirect. If the login fails we want to redirect the user back to the login form. The second is a success redirect. In this case, we want to redirect the user to the user page. And now, finally, let's define the route for that user page. So now we have two route handlers that we need to define, login and user.

So now, let's go to index.js and routes. Towards the bottom of the page, let's define those two route handlers. The first handler is going to be very straightforward. We're just going to call the render method of the response object. The first argument we're passing in is login, and that's the name of the jade view that we're going to add in a moment. And then we're going to pass a title to that view. And that title is going to be Log in. The user route is going to be a little bit more sophisticated. First we want to check to make sure that the user is actually there.

We're going to test the value of the user property of Passport, which is stored in the session. So if the user is undefined, we're going to redirect the user back to the login page. However, if we do have a valid user, we want to render the user page. So to do that we're going to call the render method of the response object. We're going to call the user view and we're going to pass in a title as well as the user information. Now let's add our views.

Go back to the exercise files and open up the snippets folder. There are two jade files, one for login and one for user. Copy both of those into the views folder of the project. The log in page is a form. There are two inputs here, one for user name and one for password. By default, Passport is going to look for user name and password in the request. You can change this later but for now, I'm just going to leave it with these. And then there is a third input that's a submit button.

Next, lets have a quick look at user.jade. In this case we are just showing the title, and we're greeting the user by their username. So let's start up the server and watch this in action. Type in node server and then press return. Now go to localhost at port 3000 in the browser. I'm going to go to the /login route. I'm going to type in the username admin and the password lynda. And then I'm going to log in. And now it greets me by name. I'm going to open up a session free window, so I'm going to go to File and New Incognito Window.

And that way, we'll have a separate session for this window. So I'm going to paste in the same URL and go to user. And it redirects me. So this way, we know we have separate sessions for the separate windows. Passport provides the middleware necessary for handling website logins through HTML forms. While there are different strategies you could use, the local strategy is best for handling traditional login forms. In the next chapter, we'll have a look at command line interfaces in node.

There are currently no FAQs about Node.js Essential Training.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Node.js Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Notes cannot be added for locked videos.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.