User authentication
In this section of the book we’re going to add some user authentication functionality to our application, so that only registered, logged-in users can create new snippets. Non-logged-in users will still be able to view the snippets, and will also be able to sign up for an account.
The workflow will look like this:
A user will register by visiting a form at
/user/signup
and entering their name, email address and password. We’ll store this information in a newusers
database table (which we’ll create in a moment).A user will log in by visiting a form at
/user/login
and entering their email address and password.We will then check the database to see if the email and password they entered match one of the users in the
users
table. If there’s a match, the user has authenticated successfully and we add the relevantid
value for the user to their session data, using the key"authenticatedUserID"
.When we receive any subsequent requests, we can check the user’s session data for a
"authenticatedUserID"
value. If it exists, we know that the user has already successfully logged in. We can keep checking this until the session expires, when the user will need to log in again. If there’s no"authenticatedUserID"
in the session, we know that the user is not logged in.
In many ways, a lot of the content in this section is just putting together the things that we’ve already learned in a different way. So it’s a good litmus test of your understanding and a reminder of some key concepts.
You’ll learn:
- How to implement basic signup, login and logout functionality for users.
- A secure approach to encrypting and storing user passwords in your database.
- A solid and straightforward approach to verifying that a user is logged in using middleware and sessions.
- How to prevent cross-site request forgery (CSRF) attacks.