JS-301-NodeServer
  • Introduction
  • js_library
    • Node Server
      • 00 - Intro
        • 01 - Purpose
        • 02 - Back-End Setup
        • 03 - Terms Cheat Sheet
      • 01 - Server Set up
        • 01 - npm packages
        • 02 - Express Intro
        • 03 - Express code
      • 02 - Development Tools
        • 01 - Nodemon Intro
        • 02 - Postman Intro
        • 03 - Postman set up
      • 03 - Routes Intro
        • 01 - Routes intro
        • 02 - Express Router() intro
        • 03 - Challenge 1
        • 04 - Challenge 2
      • 04 - Database Intro
        • 00 - DB Intro and Set up
          • 00 - DB Intro
          • 01 - PostgreSQL Intro
          • 02 - Install
        • 01 - Sequelize Intro
          • 01 - Sequelize intro
          • 02 - Initialize
      • 05 - Model View Controller
        • 01 - MVC
          • 00 - MVC Intro
        • 02 - Models
          • 01 - Intro to Models
          • 02 - Test Model
        • 03 - Controllers
          • 00 - Controllers Intro
          • 01 - Controller Set up
          • 02 - Create Method
          • 03 - req.body()
          • 04 - Crafting the Response
          • 05 - Sending the Response
          • 06 - JSON Response
          • 07 - Error Handling
        • 04 - Conclusion
      • 06 - Tokenization
        • 01 - JWT Intro
          • 01 - JWT intro
        • 02 - User Create
          • 01 - User Create
          • 02 - Refactor
        • 03 - User Token
          • 01 - JWT Package
          • 02 - Adding JWT
          • 03 - ENV
      • 07 - Encryption
        • 01 - bcrypt
        • 02 - bcrypt setup
      • 08 - Session
        • 00 - Session Intro
        • 01 - Sign In Method
        • 02 - Sign In Bcrypt
        • 03 - Sign In JWT
      • 09 - Middleware
        • 01 - Test Client HTML
        • 02 - Test Client JS
        • 03 - Middleware intro
        • 04 - Headers intro
        • 05 - Server Update
        • 06 - Test Post
        • 07 - Test Post Refactor
        • 08 - Post Data
        • 09 - Fetch From One
      • 10 - Authenticated Routes
        • 01 - Intro to Authenticated Routes
        • 02 - Validate Session
        • 03 - Changes to app.js
        • 04 - authtestcontroller.js
        • 05 - Delete an Item
        • 06 - Update an Item
        • 07 - Postman Testing
      • 11 - Authenticated Requests
        • 00 - Additions to index
        • 01 - Anatomy of a Request
        • 02 - Create User
        • 03 - Getting a Token
        • 04 - Get Items From One User
        • 05 - Creating an Item for a User
        • 06 - Get one item
        • 07 - Update an Item
        • 08 - Deleting an Item
        • 09 - Deleting with a Custom Event
      • 12 - Workout Log Server
        • 00 - Intro
      • 13 - More Sequelize Functions
        • Migrations
          • 00 - Intro
          • 01 - init and config
          • 02 - Creating the First Migration
          • 03 - Running Migrations
          • 04 - Reverting Migrations
          • 05 - Seeds
          • 06 - Reverting Seeds
        • Queries
          • 00 - Intro
          • 01 - Queries
Powered by GitBook
On this page
  • User Scripts
  • Script Tags
  • userSignUp
  • Analysis
  • Test
  • userSignIn
  • Testing
  1. js_library
  2. Node Server
  3. 11 - Authenticated Requests

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:

    └── 5-Express Server
            └── server
            └── client
                └── 01-scripts.js
                └── 02-user-scripts.js
                └── index.html

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:

    <script src="01-scripts.js"></script>
    <script src="02-user-scripts.js"></script>

</body>

</html>

userSignUp

At the top of this new script file,02-user-scripts.js, let's add the code for signing up a user:

/********************
 * POST - /createuser
*********************/
function userSignUp(){
    let userName = document.getElementById('userSignUp').value; //1
    let userPass = document.getElementById('passSignUp').value;
    console.log(userName, userPass);

    let newUserData = {user : { username: userName, password: userPass}}; //2
    fetch('http://localhost:3000/api/user/createuser', {
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(newUserData) //3
    })
    .then(response => response.json())
    .then(function (response) {
        console.log(response.sessionToken);
        let token = response.sessionToken; //4
        localStorage.setItem('SessionToken', token);  //5
    });
}

Analysis

  1. Here, we grab the value of the user/password data from the createuser input field in the index.html file.

  2. The variables used to store the sign up info from the DOM get passed into the values of the username and password properties. We package everything up in a user object.

  3. In the request object in our fetch() call, we pass in the newUserData variable to be sent off in the body of our request to the server.

  4. We get the sessionToken from the response and store it in a token variable.

  5. In our localStorage, we call the setItem function and store the token in localStorage. This will keep our token safely stored in our local window.

Test

  1. Make sure the client and server are running.

  2. Open up the client in the browser. Go to Step #6: POST Sign Up on the table.

  3. Sign up with a new user and press send. You should see the following:

  4. Notice that we have the username, password, and a token printing in the console window.

  5. 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:

function userSignIn(){
    let userName = document.getElementById('userSignin').value; 
    let userPass = document.getElementById('passSignin').value;
    console.log(userName, userPass);

    let userData = {user : { username: userName, password: userPass}};
    fetch('http://localhost:3000/api/user/signin', { //<---signin route used
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
    })
    .then(response => response.json())
    .then(function (response) {
        console.log(response.sessionToken);
        let token = response.sessionToken;
        localStorage.setItem('SessionToken', token);
    });
}

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.

Previous01 - Anatomy of a RequestNext03 - Getting a Token

Last updated 7 years ago

screenshot