Apply automatic percentage discount for logged-in WooCommerce customers with a shop page notice. Handles admin and product type checks.
Back to Snippets
javascript
• 49 lines
React Higher Order Component For Role-Based Authentication And Authorization
This React Higher Order Component handles authentication and authorization by restricting access to components based on user roles. It utilizes React Context API and localStorage for user data storage, incorporating error handling and type validation for robustness. The component is particularly useful when implementing role-based access control in React applications. It assumes you have a basic understanding of React and its ecosystem.
Snippet Stats
Lines
49
Characters
1,355
Read
2 mins
import React, { useState, useEffect } from 'react';
import { useContext } from 'react';
import { AuthContext } from './AuthContext';
const withAuth = (WrappedComponent, allowedRoles) => {
if (!Array.isArray(allowedRoles)) {
throw new Error('allowedRoles must be an array');
}
const WithAuthComponent = () => {
const { user, isLoading, error } = useContext(AuthContext);
const [isAuthorized, setIsAuthorized] = useState(false);
const [authError, setAuthError] = useState(null);
useEffect(() => {
if (!isLoading && user) {
try {
if (!user || !user.roles) {
throw new Error('User or user roles is not defined');
}
const userRoles = user.roles;
if (!Array.isArray(userRoles)) {
throw new Error('User roles must be an array');
}
const isAllowed = allowedRoles.some(role => userRoles.includes(role));
setIsAuthorized(isAllowed);
} catch (error) {
setAuthError(error.message);
}
} else if (error) {
setAuthError(error.message);
}
}, [user, isLoading, allowedRoles]);
if (authError) {
return Error: {authError};
}
if (isAuthorized) {
return ;
} else {
return Forbidden;
}
};
return WithAuthComponent;
};
export default withAuth;
Found an issue with this snippet? Help us improve by reporting it. Report it →