Subscription app (part 5)

In the previous post, I created a login route.

In this post, I’ll be creating a user route and a middleware to verify a user.

Before a user can access the profile page after logging in or signing up, a request needs to be sent with the token received to verify the user before getting access to the profile page.

The user route will be a protected route and it’ll send the user details. The user needs to sign up or login before hitting the route.

The user route will receive the token, extract the payload from the token, verify it and return the data to the client.

A middleware will be created for this steps.

This middleware intercepts the request to get access to a protected route.

It will extract the token from the request header, verify it and check if the user is authenticated before getting access to a protected route. If the the user is not authenticated, then it will throw an error.

Creating the middleware

In the src directory, create a new directory named “middleware.”

Then inside it, create a file named “checkAuth.ts”

auth 1

auth 2
Create and export a function which takes in the request, response and next parameters

Logic for verifying the token:

  1. get the token from the request header (ln 9)
  2. check if there’s a token (ln 11–19)
  3. extract the token (ln 21).
  4. In a try-and-catch block, verify the token with JWT and set a property on the user to have the verified email and catch any errors.( ln 23–41)

c-3
Make sure to define the type for Typescript

  • To define the property for the user in typescript
  • in the project root, create a @types directory, express directory and an index.ts file

c-4
And add the types to the tsconfig.json file.

  1. execute the next route (ln 31)

Using the middleware…

Create the user route

In the auth.ts file, create a get request for getting the user profile.

And import the middleware.

using the middleware

  • right here, the user route is created with the middleware placed in-between the path and the call-back function
  • find the user in the DB (ln 146)
  • send the data to the client (ln. 148–157)

Testing the code…

In postman:

testing the user route

  • create a new GET request
  • change the route url
  • login an existing user to get a token
  • copy the token and place inside of the header
  • send

Yay! I got the token verified and the user data.

In the next post, I will be setting up Stripe and creating the subs/prices route.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Mastering wordpress website design : fundamentals you need to know.