- Implement login and signup with a password
- Use
has_secure_passwordto hash and salt passwords
We're going to make a Rails app that covers a simple authentication flow: users can create accounts, log in, and log out.
There is some starter code in place for a Rails API backend and a React frontend. To get set up, run:
$ bundle install
$ npm install --prefix clientYou can work on this lab by running the tests with learn test. It will also be
helpful to see what's happening during the request/response cycle by running the
app in the browser. You can run the Rails server with:
$ rails sAnd you can run React in another terminal with:
$ npm start --prefix clientYou don't have to make any changes to the React code to get this lab working.
Our app has three pages:
- A signup page, where the user enters their username, password, and password confirmation.
- A login page, where the user submits their username and password and are then logged in.
- A user homepage, which says, "Welcome, ${username}!"
Users should not be able to log in if they enter an incorrect password.
Note: we're not covering password validations in this lab, so don't worry about those. Password validation is hard to get right anyway — it's surprisingly easy to produce rules that decrease password security rather than enhance it.
To complete the lab and get the tests passing, you will need to:
-
Create a User model, and migrations for a
userstable withusernameandpassword_digestcolumns. Make sure to usepassword_digest, notpassword, in your migration, and to include the has_secure_password macro in your model. -
Create a
UsersControllerwith acreatemethod that responds to aPOST /signuprequest. It should: create a new user; save their hashed password in the database; save the user's ID in the session hash; and return the user object in the JSON response. -
Add a
showmethod to yourUsersControllerthat responds to aGET /merequest. If the user is authenticated, return the user object in the JSON response. -
Create a Sessions controller with a
createaction for logging in that responds to aPOST /loginrequest, and adestroyaction for logging out that responds to aDELETE /logoutrequest.
Happy coding!