This React higher-order component handles authentication and authorization by wrapping the provided component with authentication checks, ensuring onl...
Back to Snippets
javascript
• 43 lines
JavaScript
PHP
PHP
React Higher Order Component For Authentication And Authorization In Large Scale Applications
This React higher order component handles authentication and authorization by checking user credentials before rendering the wrapped component. It utilizes React hooks for state management and error handling, making it suitable for large-scale applications where authentication logic needs to be reused. The component checks for user authentication and authorization based on predefined roles. It is particularly useful in complex applications with multiple authorization levels.
Snippet Stats
Lines
43
Characters
1,247
Read
2 mins
import React, { useState, useEffect, useContext } from 'react';
import { AuthContext } from './AuthContext';
const withAuth = (WrappedComponent, allowedRoles) => {
const AuthComponent = () => {
const { user, isAuthenticated } = useContext(AuthContext);
const [isAuthorized, setIsAuthorized] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const checkAuthorization = async () => {
try {
if (isAuthenticated && user.roles.some(role => allowedRoles.includes(role))) {
setIsAuthorized(true);
} else {
setIsAuthorized(false);
}
} catch (error) {
setError(error.message);
}
};
checkAuthorization();
}, [isAuthenticated, user?.roles, allowedRoles]);
if (!isAuthenticated) {
return <div>You are not authenticated.</div>;
}
if (!isAuthorized) {
return <div>You are not authorized to access this resource.</div>;
}
if (error) {
return <div>Error: {error}</div>;
}
return <WrappedComponent />;
};
return AuthComponent;
};
export default withAuth;
Found an issue with this snippet? Help us improve by reporting it. Report it →
Related Snippets
View allThis snippet provides a custom WordPress plugin that utilizes hooks to modify the user registration process, allowing for additional validation and cu...
Complete form handling pattern — nonce verification, input sanitization, validation with error messages, and secure redirect. Production-ready.