Protect Routes on Front End

Purpose: To add a component to your React app that uses your AuthContext to protect unauthorized content. In Exercise 6.3, you created an @access_required route on the back end that gives an API error response when a user's authorization is beneath a certain level. Since the front end is a UI, not an API, two useful functions for unauthorized content are (1) hiding content, and (2) redirecting pages. You will create a component that can do either and can be placed anywhere.

Create AccessRequired Component

The AccessRequired component below has two props: minLevel (setting the minimum access level) and redirect (specifying where to redirect). When the redirect prop is empty, it simply hides any content wrapped within it when access is less than minLevel. When the redirect prop has a value, a <Navigate> component is used to redirect when access is less than minLevel.

AccessRequired.jsx
App.jsx
Wrap the <Secret /> component in AccessRequired with a redirect.
Nav.jsx
For cleaner-looking code, in the Nav, remove the conditional rendering for the "Secret Identity" NavLink and wrap in <AccessRequired> instead, with NO redirect.

Test the Route by Changing User Level on the Back End

Change the "users" global variable so that the user has a "level" of 1 and 3 and test that the button disappears appropriately when the level is too low and reappears when it is high enough.