From b221a83ecef1dd7f9583d5107017d24e668205a6 Mon Sep 17 00:00:00 2001 From: Kamal Wickramanayake Date: Thu, 2 Jul 2026 20:17:44 +0530 Subject: Added React global state + role based security sample app --- react/08-auth-with-context/README.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 react/08-auth-with-context/README.md (limited to 'react/08-auth-with-context/README.md') diff --git a/react/08-auth-with-context/README.md b/react/08-auth-with-context/README.md new file mode 100644 index 0000000..3f1c7a8 --- /dev/null +++ b/react/08-auth-with-context/README.md @@ -0,0 +1,30 @@ +# Maintain authentication context + +This sample project illustrates maintaining user authentication details in global state of a React application. It uses the React Context API. + +User details are fetched from a JSON server and stored in the global state. The fetched details should contain the roles into which the user belongs as well. + +Based on the login context and user roles, showing links and controlling the routes is illustrated. + +Actual authentication is not done in this sample application but the code is almost complete. + +Reference: Passing Data Deeply with Context + https://react.dev/learn/passing-data-deeply-with-context + +## Important files and configurations + +src/contexts/AuthContext.jsx +- This file defines the AuthContext and contains the AuthProvider component which adds an object to the global state that has user data and a number of useful functions like isLoggedIn() and isInRole(). It also has the useAuth() custom hook to easily access the context object (full or parts). + +src/main.jsx +- This file wraps the main application components inside the AuthProvider component so that all componets inside will be able to access the global state. + +src/components/RoleGuard.jsx +- This optinal file defines a React component that can be used to wrap other components and make sure that those wrapped components appear only if the current user is in the specified roles. An example is shown in src/components/Navbar.jsx. It's possible to not use this component but depend on functions defined in AuthProvider as well. + +src/components/Navbar.jsx +- Defines the navigation bar but the links displayed are controled based on auth context. Illustrates the use of RoleGuard component and useful functions defined in AuthProvider and maintained as global state by the AuthContext. +- Logout link is made to show the name of user. + +src/App.jsx +- Controls routes availability based on auth context. \ No newline at end of file -- cgit v1.2.3