Manage Users by Roles & Set Access Permissions in React

Spread the love

Manage Users by Roles & Set Access Permissions in React

In this tutorial, you’ll learn how to implement role-based access control (RBAC) in a React application. We’ll cover the following steps:

  1. Setup Roles: Define user roles and permissions.
  2. Authentication: Login and store user information with roles.
  3. Access Control: Restrict access to pages and components based on roles.
  4. Full Code Example: A working demo with roles like Admin, Editor, and Viewer.

Step 1: Setup Roles and Permissions

Define roles and permissions in a config file:

javascript
// roles.js
export const Roles = {
ADMIN: "admin",
EDITOR: "editor",
VIEWER: "viewer",
};
export const Permissions = {
CAN_EDIT: [Roles.ADMIN, Roles.EDITOR],
CAN_VIEW: [Roles.ADMIN, Roles.EDITOR, Roles.VIEWER],
};


Step 2: Authentication with Roles

Set up a basic authentication system with role-based login.

AuthContext.js:

javascript

import React, { createContext, useState, useContext } from "react";

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);

const login = (role) => setUser({ role }); // Simulate login with a role
const logout = () => setUser(null);

return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>

);
};

export const useAuth = () => useContext(AuthContext);


Step 3: Create Protected Routes

Use role-based logic to guard routes.

ProtectedRoute.js:

javascript
import React from "react";
import { Navigate } from "react-router-dom";
import { useAuth } from "./AuthContext";
const ProtectedRoute = ({ roles, children }) => {
const { user } = useAuth();

if (!user) {
return <Navigate to=“/login” />;
}

if (!roles.includes(user.role)) {
return <h2>Access Denied</h2>;
}

return children;
};

export default ProtectedRoute;


Step 4: Implement Routing

Set up routes with access control.

App.js:

javascript
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { AuthProvider } from "./AuthContext";
import ProtectedRoute from "./ProtectedRoute";
import LoginPage from "./pages/LoginPage";
import AdminPage from "./pages/AdminPage";
import EditorPage from "./pages/EditorPage";
import ViewerPage from "./pages/ViewerPage";
function App() {
return (
<AuthProvider>
<Router>
<Routes>
<Route path=“/login” element={<LoginPage />} />
<Route
path=“/admin”
element={
<ProtectedRoute roles={[admin“]}>

<AdminPage />
</ProtectedRoute>
}
/>
<Route
path=“/editor”
element={
<ProtectedRoute roles={[admin“, “editor“]}>

<EditorPage />
</ProtectedRoute>
}
/>
<Route
path=“/viewer”
element={
<ProtectedRoute roles={[admin“, “editor“, “viewer“]}>

<ViewerPage />
</ProtectedRoute>
}
/>
</Routes>
</Router>
</AuthProvider>

);
}

export default App;


Step 5: Role-Based Component Rendering

Use roles to show or hide elements.

NavBar.js:

javascript
import React from "react";
import { useAuth } from "./AuthContext";
const NavBar = () => {
const { user, logout } = useAuth();

return (
<nav>
<a href=“/viewer”>Viewer Page</a>
{user?.role === “admin” && <a href=“/admin”>Admin Page</a>}
{user?.role === “editor” && <a href=“/editor”>Editor Page</a>}
{user ? (
<button onClick={logout}>Logout</button>
) : (
<a href=“/login”>Login</a>
)}
</nav>

);
};

export default NavBar;


Step 6: Full Code Example

LoginPage.js:

javascript
import React, { useState } from "react";
import { useAuth } from "../AuthContext";
const LoginPage = () => {
const { login } = useAuth();
const [role, setRole] = useState(“”);

const handleLogin = () => {
if (role) login(role);
};

return (
<div>
<h2>Login</h2>
<select value={role} onChange={(e) => setRole(e.target.value)}>
<option value=“”>Select Role</option>
<option value=“admin”>Admin</option>
<option value=“editor”>Editor</option>
<option value=“viewer”>Viewer</option>
</select>
<button onClick={handleLogin}>Login</button>
</div>

);
};

export default LoginPage;

AdminPage.js, EditorPage.js, and ViewerPage.js:

javascript

import React from "react";

const AdminPage = () => <h2>Admin Page – Only admins can access</h2>;
const EditorPage = () => <h2>Editor Page – Admins and Editors can access</h2>;
const ViewerPage = () => <h2>Viewer Page – All roles can access</h2>;

export { AdminPage, EditorPage, ViewerPage };


Step 7: Deployment

Deploy your app using services like Netlify, Vercel, or AWS for hosting React apps.

With this setup, you now have a React application that manages user roles and sets access permissions dynamically. You can easily expand this by adding APIs for user management and storing roles in a database like MongoDB or Firebase.

Related Posts

Leave a Reply