Authentication Functionality in React + Redux Application
This document focuses on the authentication functionality within your React + Redux application, specifically the components/auth
folder.
Components:
- AuthenticateGuard:
- Restricts access to protected routes based on user authentication status.
- Uses
useAppDispatch
anduseAppSelector
hooks for Redux store interactions. - Tracks login tokens and account details through
account
andauth
slices. - Handles refresh token logic upon errors using
authOperations
anduseResponseState
. - Fetches account details on mount using
accountOperations
. - Renders a loading indicator if data is being fetched.
- Redirects to login page if no tokens are present.
- Allows access to protected routes if user is authenticated (both tokens and account data exist).
- UnAuthenticateGuard:
- Prevents access to specific routes for authenticated users.
- Checks for access token presence using
cookies
library. - Redirects to home page if a token is found.
- Allows access to non-protected routes if no token is present.
Key Functionalities:
- Protected Routes: Ensures access to certain pages only for authenticated users.
- Automatic Token Refresh: Refreshes expired access tokens using the refresh token.
- Error Handling: Handles errors during data fetching and token refreshing.
- Redirection: Redirects users to appropriate pages based on authentication status.
Integration with AppRoutes:
AppRoutes
component utilizes these guards to define protected and unprotected routes.AuthenticateGuard
is used for routes within theDashboard
layout, requiring authentication.UnAuthenticateGuard
is used for routes within theAuth
layout, allowing only unauthenticated users.
Benefits:
- Improved security by protecting sensitive routes.
- Enhanced user experience with seamless token refresh and error handling.
- Clear separation of authentication logic for better maintainability.