Skip to content

Require Auth And Require Admin

Documentation for RequireAuth and RequireAdmin Components

Overview

The RequireAuth and RequireAdmin components in our application serve as Higher Order Components (HOCs) to manage access control based on user authentication and authorization.

RequireAuth Component

  • Purpose: To ensure that only authenticated users can access certain routes/pages.
  • Functionality: Checks if the user is logged in (user object is present). If not, redirects to the home page (”/”).
  • Usage: Wrap around components or routes that require user authentication.

RequireAdmin Component

  • Purpose: To restrict access to certain routes/pages to only admin users.
  • Functionality: Verifies if the logged-in user has admin privileges (user.is_admin). If the user isn’t an admin or isn’t logged in, redirects to the appropriate page (“/client” for non-admin users, ”/” for unauthenticated users).
  • Usage: Wrap around components or routes that require admin access.

Context

Both components use UserContext to access the current user’s details.

Implementation

These components are implemented using React’s useContext hook for accessing the global user state and the Navigate component from react-router-dom for redirection.

Example Usage

<Route path="/admin-dashboard" element={<RequireAdmin><AdminDashboard /></RequireAdmin>} />
<Route path="/protected-route" element={<RequireAuth><ProtectedComponent /></RequireAuth>} />

These components are crucial for maintaining the security and integrity of the application by ensuring that content and functionalities are accessed only by the appropriate users.