Essential CSS
JavaScript Roadmap
Learn JavaScript
Mastering Web Typography
Practical Astro
Understanding Async JS
Unorthodox Tailwind
API Masterclass
Build and Deploy
The Beginner Freelancer
Real World Node
Profile Billing Logout
Understanding Async JS
Lesson Plan
  1. Introduction
    1. What is Asynchronous JS?
    2. Callbacks are not automatically asynchronous
    3. What is an API?
    4. Evolution of HTTP APIs
    5. Ajax vs Asynchronous JavaScript
  2. Fundamental Concepts
    1. How to fetch resources
    2. Using XHR
    3. Using the Fetch API
    4. Using libraries
    5. Core JavaScript concepts
    6. Understanding Promises
    7. Understanding Async Functions
    8. Understanding the Event Loop
    9. Understanding JSON
    10. Async JS Best Practices
    11. Using Optimistic UI
  3. Understanding Rest API
    1. Diving into Rest APIs
    2. The Rest Architecture
    3. The Rest Structure
    4. Anatomy of a Request
    5. What's an endpoint
    6. Request methods
    7. Understanding request headers
    8. Understanding the request body
    9. Authentication
    10. Basic Authentication
    11. Bearer Authentication
    12. Authenticating with API keys and API Secrets
    13. Cross Origin Resource Sharing
    14. Anatomy of a response
    15. HTTP Statuses
    16. Response headers
    17. The response body
    18. Handling Errors
    19. Reading API documentations
    20. Understanding Curl
  4. Node Basics
    1. Why we are using Node
    2. Command Line Basics
    3. Installing Node
    4. Managing dependencies
    5. Using ES Modules in Node
    6. Using Node
    7. Restarting the server automatically
    8. Sending requests via Node
    9. Protecting API keys and secrets
  5. Building a server
    1. What's a server
    2. Building a simple server with Express
    3. Two kinds of servers
    4. API Server architecture
    5. Handling routes
    6. Understanding Middlewares
    7. Enabling CORS
    8. Receiving data
    9. Sending responses
    10. Handling errors in Express
    11. Using the server as a proxy
    12. Minimum viable server
  6. Open Authorization
    1. Open Authorisation (OAuth)
    2. Authenticating with Access Tokens
    3. Obtaining Access Tokens
    4. Public and Confidential Clients
    5. Authorisation Code Grant
    6. Understanding scope
    7. Proof Key for Code Exchange (PKCE)
    8. PKCE with Twitter
    9. Dynamic state and `code_verifier`
    10. Saving the access token in cookies
    11. Passing access tokens to the browser
    12. Saving the access token in local storage
    13. Refresh Token Grant
    14. Device Code Grant
    15. Client libraries vs REST
  7. Building Social Media Logins
    1. Introduction
    2. Starter Files
    3. Creating SSL certificates
    4. Login in with Github
    5. Github: Saving the token to local storage
    6. Github: Persisting the login status
    7. Login with Twitter
    8. Twitter: Saving the token to local storage
    9. Twitter: Persisting the login status
    10. Twitter: Refreshing the access token
    11. Login with Facebook
    12. Facebook: Saving the token to localStorage
    13. Facebook: Persisting the login status
    14. Facebook: Refreshing the access token
    15. Login with google
    16. Google: Saving the token to localStorage
    17. Google: Refreshing the access token

Github: Persisting the login status

There are three steps to ensure that a user is logged in with the identity provider:

  1. Grab the access token from local storage
  2. Verify the access token
  3. Update the access token (if necessary)

Step 1: Grab the access token

We can grab the access token by searching the github key in localStorage.

If you used localStore, you can use the get method.

const token = localStore.get('github')

If we can find the access token, we proceed on with step 2.

If we cannot find the access token, we stop operations here — we don’t have to do anything else since the page loads with the user with a “Logged Out” status.

Step 2: Verify the access token

There are two steps for verifying the access token:

  1. Simple Validation
  2. Robust Validation

Simple Validation

You can perform a simple validation with the following steps:

  1. Send the token a specific endpoint on the backend
  2. Search your database for the token
  3. If the token exist, allow the user to log in

This simple validation works if you only use the identity provider to login to your app.

If you want to use the access token to access the API, you will need to perform a robust validation.

Since we don’t have a database for this app, we cannot use a simple validation. We need to use the robust validation.

Robust Validation

You can perform a robust validation by sending the access token to the API. Typically we use an endpoint that returns the authenticated user.

For Github, it’s the /user request.

Now, most APIs need you to send your requests through a server. Github doesn’t require this, but Twitter, Facebook and Google needs it. So we will send the request through a server to keep things consistent.

We will:

  1. Send a request to /auth/github/verify
  2. Grab the access token in the endpoint and send a request to Github’s /user endpoint
  3. If the API returns a successful response, we know the access token works
  4. If the API returns an unsuccessful response, we know the access token doesn’t work

Here’s how to execute the steps:

We’ll start by sending a request to /auth/github/verify.

  • We’ll send a POST request since since authentication is typically uses a POST request.
  • We’ll also put the access_token in the body so we can get it in the backend.

Here’s what the request looks like:

import { zlFetch, localStore } from './lib.js'
const token = localStore.get('github')
if (token) {
// Sends request to server
const response = await zlFetch.post('/auth/github/verify', {
body: { accessToken: token.accessToken },
})
}

We’ll grab the access token in the backend:

// In routes/auth.js
router.post('/auth/github/verify', async (req, res) => {
const { accessToken } = req.body
})

We’ll send the access token to Github.

When we do this, we need to listen to both success and error messages. You’ll see why later.

zlFetch makes this easy by returning both success and error responses. You can activate this feature by setting returnError to true.

router.post('/auth/github/verify', async (req, res) => {
// ...
const { response, error } = await zlFetch('https://api.github.com/user', {
auth: accessToken,
returnError: true,
})
})

If the response is successful, we know the access token is valid, so we will send a success message to the frontend.

If the response is unsuccessful, we know the access token is invalid, so we will send an error message to the frontend.

router.post('/auth/github/verify', async (req, res) => {
// ...
if (response) {
res.json({ status: 'success' })
} else {
res.status(error.status).json({ message: error.body.message })
}
})

On the frontend, if we receive a success message, we know the access token is valid. So we update the login status.

If the receive an error message, we know the access token is invalid. In this case we don’t have to do anything since the login status is already so set to “Logged Out” by default.

if (token) {
// ...
const response = await zlFetch.post(/*...*/)
if (response) {
const element = document.querySelector(`.status[data-provider="github"]`)
element.textContent = 'Logged In'
}
}

Step 4: Update the access token

Github access token doesn’t expire so we don’t have to update the access token.

We’re done with Github at this point. Let’s make a quick refactor before moving into Twitter. We’ll do the refactor in the next lesson.