« Previous Tutorial Next tutorial »

Now that we’re able to register users, it feels like we’re starting to build a real web app! Well, at least, it feels that way to me. We’re going to be able to use this newly created registration system to ensure that varying parts of our React app are only available to logged in users, and in some cases (for example a user’s settings page) only to one specific logged in user.

Speaking of logging in, let’s write that endpoint. Open /routes/api/authentication.js and head down toward the bottom of the file. We’re going to add a new route underneath our /register route, which ends on line21. This one’s simple, so here’s all of the code at once:

// POST to /login
router.post('/login', (req, res) => {
  passport.authenticate('local')(req, res, () => {
    // If logged in, we should have user info to send back
    if (req.user) {
      return res.send(JSON.stringify(req.user));
    }

    // Otherwise return an error
    return res.send(JSON.stringify({ error: 'There was an error logging in' }));
  });
});

Easy, right? Do the login and then send back the logged in user’s info, or if that fails, send an error. That error code’s unlikely to ever be called (but it’s still a good thing to have) because a bad login, say a mistyped password or nonexistent user, will throw an HTTP 401 unauthorized error, which ends the response. We’ll want to catch that, along with our JSON emergency error over on the React side of things when we write our Ajax code. But that, too, is another tutorial.

Let’s test our login. Save our file, make sure your Express server is running, and head over to Postman. The instructions are nearly the same as from the previous tutorial. In fact, Postman probably still has your data from the previous tutorial in it, but in case you get a brand new tab, here’s what to do:

  1. Set the dropdown from GET to POST
  2. For the URL, use http://localhost:3000/api/authentication/login
  3. Click “body” just below the URL
  4. Click the “raw” radio button
  5. Select “JSON (application/json)” from the dropdown

For your data, clear what’s already there (if there’s anything), and then just pass the username and password, like this:

{ "username": "administrator", "password": "correcthorsebatterystaple" }

Though, of course, you should use whatever the actual password was that you registered your user with.

Click the big, blue Send button and you’re good to go. Hopefully. If not, it’s not a catastrophe … leave a comment, and we’ll get it sorted out. You might be wondering why we’re having the API send back a user object instead of just some kind of “way to go!” success message. The reason is because we’ll update our App State, over on the React side, with the user object in order to make sure we’re keeping track of the latest info. We haven’t covered app state yet, of course, but that’s going to change when we get to wiring up the handy Log In form we already designed and having it actually contact the API.

OK, we can log a user in. Let’s log them out, too. This one’s even easier. Add it below your log in function in /routes/api/authentication.js:

// GET to /logout
router.get('/logout', (req, res) => {
  req.logout();
  return res.send(JSON.stringify(req.user));
});

Straightforward, right? Run a logout, and then send the user object, which should now be null, back. That makes it easy to check on the React side … if it’s NOT null, then something went wrong!

Save that file and switch back to Postman. Keep your Log In tab for right now, and open a new tab. You don’t have to do anything with this one except fill in the URI: http://localhost:3000/api/authentication/logout. That’s it. Click the Send button, and you should see it return null.

Of course, it might just be returning null because it’s broken. Since we have a little time, let’s prove that’s not the case by logging to our console for a second. Change your code to look like this:

router.get('/logout', (req, res) => {
  console.log(req.user);
  req.logout();
  console.log(req.user);
  return res.send(JSON.stringify(req.user));
});

Save the file, switch to Postman, and first switch back to your log in tab and run that, so that it creates a logged in user session again. It should, as expected, return a user object. Now switch back to your log out tab, and run that again. Once again, we just get null here … but we can go look in our node console, and see that it did indeed console log the user object first, and then console logged null after the log out was done. Cool.

Remember to delete those two console.logs from your code and re-save the file!

We’re all set here. In the next tutorial, we’ll switch back to React and wire up our log in form. After that, it’ll be time to dive into app state. That’s a big can of worms, but it’s an important step in creating a single-page React app. We’ll break it down into as many tutorials as it takes. See you there!

« Previous Tutorial Next tutorial »