02 - Create User
In this module, we'll add client methods for creating and logging in as a user.
User Scripts
Please add a 02-user-scripts.js
file inside of the client folder:
We'll add some of our auth logic in this file.
Script Tags
Follow these steps to wire up the js
file:
1. Go to index.html
.
2. Go to the bottom of that same file, underneath the Bootstrap scripts and the 01-scripts.js
file, and add the 02-user-scripts.js
tag like this:
userSignUp
At the top of this new script file,02-user-scripts.js
, let's add the code for signing up a user:
Analysis
Here, we grab the value of the user/password data from the
createuser
input field in theindex.html
file.The variables used to store the sign up info from the DOM get passed into the values of the
username
andpassword
properties. We package everything up in a user object.In the request object in our
fetch()
call, we pass in thenewUserData
variable to be sent off in the body of our request to the server.We get the
sessionToken
from the response and store it in atoken
variable.In our
localStorage
, we call thesetItem
function and store the token inlocalStorage
. This will keep our token safely stored in our local window.
Test
Make sure the client and server are running.
Open up the client in the browser. Go to Step #6: POST Sign Up on the table.
Sign up with a new user and press send. You should see the following:
Notice that we have the username, password, and a token printing in the console window.
You should also crack open Postgres, refresh your database, and look at the User table. You should see the new user added there now.
userSignIn
The signin
function is exactly the same as signup
. We're just pulling from different fields and sending a request to a different endpoint. Put this code under userSignUp
:
Testing
Follow the signup
instructions to create a couple more users. Then use Step 7: POST SignIn
to sign in as each user. Notice that each one gets a different session token, which is reset in localStorage
each time.
Last updated