Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Accelerating Server-Side Development with Fastify

You're reading from  Accelerating Server-Side Development with Fastify

Product type Book
Published in Jun 2023
Publisher Packt
ISBN-13 9781800563582
Pages 406 pages
Edition 1st Edition
Languages
Authors (3):
Manuel Spigolon Manuel Spigolon
Profile icon Manuel Spigolon
Maksim Sinik Maksim Sinik
Profile icon Maksim Sinik
Matteo Collina Matteo Collina
Profile icon Matteo Collina
View More author details

Table of Contents (21) Chapters

Preface 1. Part 1:Fastify Basics
2. Chapter 1: What Is Fastify? 3. Chapter 2: The Plugin System and the Boot Process 4. Chapter 3: Working with Routes 5. Chapter 4: Exploring Hooks 6. Chapter 5: Exploring Validation and Serialization 7. Part 2:Build a Real-World Project
8. Chapter 6: Project Structure and Configuration Management 9. Chapter 7: Building a RESTful API 10. Chapter 8: Authentication, Authorization, and File Handling 11. Chapter 9: Application Testing 12. Chapter 10: Deployment and Process Monitoring for a Healthy Application 13. Chapter 11: Meaningful Application Logging 14. Part 3:Advanced Topics
15. Chapter 12: From a Monolith to Microservices 16. Chapter 13: Performance Assessment and Improvement 17. Chapter 14: Developing a GraphQL API 18. Chapter 15: Type-Safe Fastify 19. Index 20. Other Books You May Enjoy

Authentication, Authorization, and File Handling

In this chapter, we will continue evolving our application, mainly covering two distinct topics: user authentication and file handling. First, we will implement a reusable JWT authentication plugin that will allow us to manage users, authentication, and sessions. It will also act as an authorization layer, protecting our application’s endpoints from unauthorized access. We will also see how decorators can expose the authenticated user’s data inside the route handlers. Then, moving on to file handling, we will develop a dedicated plugin enabling users to import and export their to-do tasks in CSV format.

In this chapter, we will learn about the following:

  • Authentication and authorization flow
  • Building the authentication layer
  • Adding the authorization layer
  • Managing uploads and downloads

Technical requirements

To follow along with this chapter, you will need these technical requirements mentioned in the previous chapters:

Once more, the code of the project can be found on GitHub at https://github.com/PacktPublishing/Accelerating-Server-Side-Development-with-Fastify/tree/main/Chapter%208.

Finally, it’s time to start our exploration. In the next section, we will take a deep dive into the authentication flow in Fastify, understanding all the pieces we need to implement a complete solution.

Authentication and authorization flow

Authentication and authorization are usually challenging topics. Based on use cases, specific strategies may or may not be feasible. For this project, we will implement the authentication layer via JSON Web Tokens, commonly known as JWTs.

JWT

This is a widely used standard for token-based authentication for web and mobile applications. It is an open standard that allows information to be transmitted securely between the client and the server. Every token has three parts. First, the header contains information about the type of token and the cryptographic algorithms used to sign and encrypt the token. Then, the payload includes any metadata about the user. Finally, the signature is used to verify the token’s authenticity and ensure it has not been tampered with.

Before looking at the implementation in Fastify, let’s briefly explore how this authentication works. First, the API needs to expose an endpoint for the registration...

Building the authentication layer

Since we need to add new non-trivial functionality to our application, we need to implement mainly two pieces:

  • An authentication plugin to generate tokens, check the incoming requests, and revoke old or not used tokens
  • A bunch of new routes to handle the registration, authentication, and life cycle of the tokens

Before jumping directly into the code, we need to add one last note. In this chapter’s code snippets, we will use a new data source called userDataSource ([1]). Since it exposes only createUser ([3]) and readUser ([2]) methods and the implementation is trivial, we will not show it in this book. However, the complete code is in the ./routes/auth/autohooks.js file inside the GitHub repository.

Since we must implement both, we can add the authentication plugin first.

Authentication plugin

First, create the ./plugins/auth.js file inside the project’s root folder. The auth.js code snippet shows the implementation...

Adding the authorization layer

Now that we can have all authentication pieces in place, we can finally move on to implementing the authorization layer of our application. To adequately protect our endpoints, we need to do two main things to the ./routes/todos module from Chapter 7:

  • Add the authentication layer to ./routes/todos/routes.js
  • Update the to-do data source inside ./routes/todos/autohook.js

Fortunately, we need only a one-liner change to implement the first point. On the other hand, the second point is more complex. We will examine both in the following subsections.

Adding the authentication layer

Let’s start with the simpler task. As we already said, this is a fast addition to the Chapter 7 code that we can see in the following snippet:

module.exports = async function todoRoutes (fastify, _opts) {
  fastify.addHook('onRequest', fastify.authenticate) // [1]
  // omitted route implementations from chapter 7
}
...

Managing uploads and downloads

We need to add two more functionalities to our application, and we will do it by developing a dedicated Fastify plugin. The first will allow our users to upload CSV files to create to-do tasks in bulk. We will rely on two external dependencies to do it:

  • @fastify/multipart for file uploads
  • csv-parse for CSV parsing

The second plugin will expose an endpoint to download items as a CSV file. Again, we need the external csv-stringify library to serialize objects and create the document.

While we will split the code into two snippets in the book, the complete code can be found in ./routes/todos/files/routes.js. Let’s explore the following snippet, which contains the file upload and items bulk creation logic:

const fastifyMultipart = require('@fastify/multipart')
const { parse: csvParse } = require('csv-parse')
// ... omitted for brevity
  await fastify.register(fastifyMultipart, { // [1]
 &...

Summary

In this chapter, we added an authentication layer to ensure that only registered users can perform actions on the to-do items. Moreover, thanks to the modest authorization layer, we ensured that users could only access tasks they created. Finally, we showed how simple upload and download capabilities are to implement using a real-world example of bulk imports and exports.

In the next chapter, we will learn how to make our application reliable in production. We will use the tools that Fastify integrates to test our endpoints thoroughly. We want to prevent introducing any disruptions for our users because of lousy code pushed to production.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Accelerating Server-Side Development with Fastify
Published in: Jun 2023 Publisher: Packt ISBN-13: 9781800563582
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}