Reader small image

You're reading from  Enterprise React Development with UmiJS

Product typeBook
Published inMay 2022
Reading LevelIntermediate
PublisherPackt
ISBN-139781803238968
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Douglas Alves Venancio
Douglas Alves Venancio
author image
Douglas Alves Venancio

Douglas has a background in systems analysis and development, his passion is to help customers and the community solve problems. Over the past few years, he has mainly worked with digital products and innovation, delivering the best user experience with modern web applications.
Read more about Douglas Alves Venancio

Right arrow

Chapter 4: Error Handling, Authentication, and Route Protection

We need to implement error handling and security measures in our interfaces to ensure that the quality and user experience of the application is good.

In this chapter, we'll modify the login page created in Chapter 1, Environment Setup and Introduction to UmiJS and configure the default HTML template for our application. You'll learn how to store and globally access data by configuring your application's initial state. Next, you'll learn how to block unauthorized access using the Umi plugin-access. Finally, you'll learn how to handle HTTP error responses and display feedback messages by configuring Umi requests.

In this chapter, we'll cover the following main topics:

  • Modifying the login page and defining the HTML template
  • Storing and globally accessing user information
  • Protecting application routes based on user roles
  • Handling HTTP error responses

By the end...

Technical requirements

To complete this chapter's exercises, you only need a computer with any OS (I recommend Ubuntu 20.04 or higher) and the software installed in Chapter 1, Environment Setup and Introduction to UmiJS (VS Code, Node.js, and Yarn).

You can find the complete project of this chapter in the Chapter04 folder in the GitHub repository available at https://github.com/PacktPublishing/Enterprise-React-Development-with-UmiJs.

Modifying the login page and defining the HTML template

In this section, we'll create a Umi mock file and requests to simulate user authentication, a login page for users to log in, and we'll configure the default HTML template for our application.

Let's start with the mock file. We'll create endpoints for login, logout, and getting user information. Follow these steps to create the file:

  1. Create a new file named user.ts in the mock folder. Next, create the login function as follows:
    import { User } from '@/types/user.d';
    import { Request, Response } from 'express';
    const user: { currentUser: User } = {
      currentUser: {
        isLoggedIn: false,
      },
    };
    const login = (req: Request, res: Response) => {
      const { email, password } = req.body;
    };
  2. Add the following if statement to the login function:
      if (email == 'john@doe.com' && password == 'user&apos...

Storing and globally accessing user information

In this section, we'll configure the plugin-initial-state plugin to store and globally access user information.

To configure the initial state, we only need to create a function named getInitialState in the app.tsx file. The getInitialState function will be executed before React renders the entire application, and its return value will be used as the global state. We can use the @@initialState model to access the values.

Let's configure the initial state by following these steps:

  1. Create a new file called globalState.d.ts in the types folder, and create the GlobalState interface as follows:
    import { User } from '@/types/user.d';
    export interface GlobalState {
      login?: (email: string, password: string) => 
        Promise<User>;
      logout?: () => Promise<void>;
      fetchUser?: () => Promise<User>;
      currentUser?: User;
    }
  2. ...

Protecting application routes based on user roles

In this section, we'll configure the Umi plugin-access plugin to define user permissions and protect routes and features from unauthorized access.

To configure the access plugin, we must create an access.ts file in the src folder. The access.ts file must export a function that returns an object, and each property of that object must be a Boolean value representing permissions. Consider the following example:

export default function (initialState: any) {
  const { access } = initialState;
  return {
    readOnly: access == 'basic',
  };
}

In this example, we read the access property from the initial state and returned the readOnly: true permission if access is equal to basic.

Let's create an access.ts file for our application.

Create a new file called access.ts in the src folder and create the default function as follows:

import { GlobalState } from...

Handling HTTP error responses

In this section, we'll configure the umi-request library to handle error responses and display visual feedback.

We'll use the errorHandler function, one of the many umi-request library configurations. I recommend you read the documentation available at https://github.com/umijs/umi-request to learn more about other features.

The umi-request library will trigger the errorHandler function every time it receives an HTTP error response, and we will read the response status and show a message to inform the user why the action they tried to execute failed.

Follow these steps to configure the umi-request library:

  1. In the app.tsx file, create a new function and add the request configuration as follows:
    const errorHandler = (error: ResponseError) => {
      const { response } = error;
      let messages = undefined;
      switch (getLocale()) {
        case 'en-US':
        ...

Summary

In this chapter, we created the login page and the document.ejs file, and learned how to set the viewport scale to display our pages on mobile devices correctly. You learned how to store and globally access data by configuring the initial state plugin and reading the initial state properties on the login and home page.

We created user permissions by configuring the access plugin and created the workflow page on which we blocked unauthorized access using the access plugin. We enabled the ProTable row selection feature only for authorized users using the access plugin.

Finally, we configured the umi-request library to handle HTTP error responses and display feedback messages to inform users what happened.

In the next chapter, you'll learn about code style, formatting, and how to improve your code using linters and formatting tools.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Enterprise React Development with UmiJS
Published in: May 2022Publisher: PacktISBN-13: 9781803238968
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.
undefined
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 £13.99/month. Cancel anytime

Author (1)

author image
Douglas Alves Venancio

Douglas has a background in systems analysis and development, his passion is to help customers and the community solve problems. Over the past few years, he has mainly worked with digital products and innovation, delivering the best user experience with modern web applications.
Read more about Douglas Alves Venancio