Last active
April 9, 2025 20:27
-
-
Save khesayed/58bc7cd4525c190b02c3f90303c1bb0d to your computer and use it in GitHub Desktop.
🛡️ React protected & RBAC route - Router Data Mode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Outlet } from "react-router"; | |
const Layout = () => <Outlet />; | |
export const Home = () => <>Home</>; | |
const Dashboard = () => <>Dashboard</>; | |
const Users = () => <>Users</>; | |
const Login = () => <>Login</>; | |
export const NotAuthorized = () => <h1>Not Authorized</h1>; | |
export const routes = [ | |
{ | |
Component: Layout, | |
children: [ | |
{ | |
index: true, | |
Component: Home, | |
}, | |
{ | |
path: "dashboard", | |
Component: Dashboard, | |
authenticated: true, | |
}, | |
{ | |
path: "users", | |
Component: Users, | |
roles: ["users-management"], | |
}, | |
{ | |
path: "login", | |
Component: Login, | |
guest: true, | |
}, | |
], | |
}, | |
]; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { redirect } from "react-router"; | |
import { NotAuthorized } from "./index"; | |
// mock hasRoles | |
const hasRoles = (roles) => { | |
const userRoles = ["users-management", "admin"]; | |
if (!userRoles) return false; | |
return roles.some((role) => userRoles.includes(role)); | |
}; | |
const authenticated = true; | |
export const RBACRoute = (routes) => { | |
return routes.map((route) => { | |
if (route.children) { | |
route = { | |
...route, | |
children: RBACRoute(route.children), | |
}; | |
} | |
if (route.authenticated && !authenticated) { | |
delete route.Component; | |
route = { | |
...route, | |
Component: () => <NotAuthorized />, | |
}; | |
} | |
if (route.roles && !hasRoles(route.roles)) { | |
delete route.Component; | |
route = { | |
...route, | |
Component: () => <NotAuthorized />, | |
}; | |
} | |
if (route.guest && authenticated) { | |
route = { | |
...route, | |
/** | |
// redirect to home page if authenticated | |
change / to any path you want | |
*/ | |
loader: async () => redirect("/"), | |
}; | |
} | |
return route; | |
}); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment