In this guide, we will walk you through the steps to implement authentication in your Jumbo React template. Jumbo provides various tools and components to simplify the process of securing your application. The authentication implementation can be broken down into the following steps:
1. AuthProvider
Jumbo offers an AuthProvider component that utilizes the Context API. This component provides four key values: isAuthenticated, loading, login, and logout. These values can be accessed using the useAuth hook as shown below:
isAuthenticated: A boolean indicating if the user is authenticated.
loading: A boolean indicating if the authentication state is being determined.
login: A handler to log the user in.
logout: A handler to log the user out.
Usage Example:
typescriptCopy code// AuthContext.tsximport React, { createContext, useContext, useState, ReactNode, FC } from'react';interfaceAuthContextType { isAuthenticated:boolean; loading:boolean;login: () =>void;logout: () =>void; authUser?:any; // Add this if you want to provide user information}constAuthContext=createContext<AuthContextType|null>(null);exportconstAuthProvider:FC<{ children:ReactNode }> = ({ children }) => {const [isAuthenticated,setIsAuthenticated] =useState<boolean>(false);const [loading,setLoading] =useState<boolean>(false);const [authUser,setAuthUser] =useState<any>(null); // Manage user informationconstlogin= () => {setLoading(true);// Add your login logic heresetIsAuthenticated(true);setAuthUser({ name:'John Doe' }); // Example user infosetLoading(false); };constlogout= () => {// Add your logout logic heresetIsAuthenticated(false);setAuthUser(null); };return (<AuthContext.Provider value={{ isAuthenticated, loading, login, logout, authUser }}> {children}</AuthContext.Provider> );};exportconstuseAuth= ():AuthContextType=> {constcontext=useContext(AuthContext);if (!context) {thrownewError('useAuth must be used within an AuthProvider'); }return context;};
This is the first place where you can place your logic and customize the login and logout handlers as per your project requirements. Additionally, you can export the authUser information to get full details of the authenticated user. The logic here can vary per project, so feel free to modify it to suit your needs.
2. Creating a HOC Function
In this step, you can create various Higher-Order Component (HOC) functions that act as middleware to apply authentication or authorization logic. Below is an example of an withAuth HOC function: