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

Twitter: 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)

Here’s what we have written so far in persist-state.js

const token = localStore.get('github')
if (token) {
// Sends request to server
const response = await zlFetch.post('/auth/github/verify', {
body: { accessToken: token.accessToken },
})
if (response) {
setLoginStatus({ provider: 'github', loggedIn: true })
}
}

We can code the Twitter part up in two ways:

  1. We’ll code the Github and Twitter code separately.
  2. Or… we can handle Github and Twitter at once.

Here’s how to choose:

  • Choose method #1 if you’re unsure of how everything works.
  • Choose method #2 when you’re ready to refactor.

In this case, we’re going to go with the second method straight away because I know how everything works and I can walk you through the process quickly.

Step 1: Grab the access token

We can put the two providers into a single array since we’re going to handle Github and Twitter at once.

const providers = ['github', 'twitter']

We can loop through the array to check the validity of the token.

providers.forEach(provider => {
const token = localStore.get(provider)
)

If we cannot find the token we know the user has not logged in with that provider. So we can do an early return and stop the function from going on.

providers.forEach(provider => {
const token = localStore.get(provider)
if (!token) return
)

Step 2: Verify the access token

This gets a little tricky because we have two similar but different conditions.

  • Github tokens don’t expire
  • Twitter tokens expire

So we need to know whether the token is can expire. We also need to know whether the token has expired (if it can expire).

We can tell using the following conditions:

  1. If there is an expiresAt property, we know the token can expire.
  2. If Date.now() is larger than expiresAt, we know the token has expired

This brings us to the following conditional statement:

providers.forEach(provider => {
const { accessToken, refreshToken, expiresAt } = token
if (expiresAt && Date.now() > expiresAt) {
// Token has expired...
}
)

The next part is a bit complicated so follow along closely.

  • If the token has expired, we know the access token is invalid, so we don’t need to check the validity of the access token with the API anymore.
  • If the token has not expired, or if the token doesn’t have an expiry value, we need to check the validity of the access token with the API.

There are too many conditions here to make sense of in a single function. So let’s create a new function to check the validity of the token. We’ll call it isTokenValid.

First, we check whether the token has expired. If has expired, we will return false because the token is no longer valid.

async function isTokenValid({ provider, accessToken, expiresAt }) {
if (expiresAt && Date.now() >= expiresAt) return false
}

If the token has not expired, or if the token doesn’t have an expiry value, we check whether the token is valid with the API.

To do this, we will send the user to an endpoint in our backend like before:

async function isTokenValid({ provider, accessToken, expiresAt }) {
// ...
// Checks the validity of the token through an API
const { response } = await zlFetch.post(`/auth/${provider}/verify`, {
body: { accessToken },
returnError: true,
})
if (response) return true
return false
}

We can use isValidToken like this:

providers.forEach(async provider => {
// ...
const { accessToken, refreshToken, expiresAt } = token
const isValid = await isTokenValid({ provider, accessToken, expiresAt })
)

If the token is valid, we can set the login status to true and we’re done.

providers.forEach(async provider => {
// ...
const { accessToken, refreshToken, expiresAt } = token
const isValid = await isTokenValid({ provider, accessToken, expiresAt })
if (isValid) {
setLoginStatus({provider, loggedIn: true})
}
)

If the token is invalid, we need to use the refresh token to generate another access token…

We’ll talk about this process after we make our backend work.

providers.forEach(async provider => {
// ...
if (isValid) {
setLoginStatus({provider, loggedIn: true})
}
// Code to generate another access token goes here...
)

Making the backend work

In isTokenValid, we send a request to our server for each provider.

async function isTokenValid({ provider, accessToken, expiresAt }) {
// ...
const { response } = await zlFetch.post(`/auth/${provider}/verify`, {
body: { accessToken },
returnError: true,
})
// ...
}

Currently we don’t have an endpoint for /auth/twitter/verify, so we need to create it.

auth.js
router.post('/auth/twitter/verify', async (req, res) => {
// ...
})

We have to extract the access token from the body…

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

… and we have to check whether the access token is valid.

We can do this by sending a request to Twitter.

In this case, we can use the /user/me endpoint. (This API is buried pretty deep into the docs so don’t blame yourself if you can’t find it).

Here’s the request to send.

router.post('/auth/twitter/verify', async (req, res) => {
// ...
const { response, error } = await zlFetch(
'https://api.twitter.com/2/users/me',
{
auth: accessToken,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
returnError: true,
},
)
})

If the response is successful, we know the access token is valid. Otherwise we know it’s invalid.

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

The code we’ve written up to this point should work now — you should be able to see the Twitter Status set to Logged In when you refresh your browser.

We’ll handle how to use the refresh token in the next lesson.