Skip to content

Instantly share code, notes, and snippets.

@milad1367
Last active November 26, 2023 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milad1367/8e8e06353b396c8118ea2979f3c8c9a4 to your computer and use it in GitHub Desktop.
Save milad1367/8e8e06353b396c8118ea2979f3c8c9a4 to your computer and use it in GitHub Desktop.
import VueRouter from 'vue-router';
import { getUser } from './auth'; // Replace with your authentication utility
// Step 1: Define Routes with Role Metadata
const routes = [
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true, roles: ['admin', 'user'] } // Dashboard accessible by both admins and users
},
{
path: '/admin',
component: AdminPanel,
meta: { requiresAuth: true, roles: ['admin'] } // Admin panel accessible only by admins
},
// ... other routes
];
// Initialize VueRouter with the defined routes
const router = new VueRouter({ routes });
// Step 2: Implement Navigation Guards
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
const user = getUser(); // Fetch the user's role
if (!user) {
next({ path: '/login' }); // Redirect to login if not authenticated
} else if (to.meta.roles && !hasAccess(user.role, to.meta.roles)) {
next({ path: '/unauthorized' }); // Redirect to unauthorized if user doesn't have the role
} else {
next(); // Proceed to route if authorized
}
} else {
next(); // Proceed to route if no authentication required
}
});
// Step 3: Dynamic Route Addition Based on User Role
function addRoutesForRole(userRole) {
if (userRole === 'admin') {
// Add routes specific to 'admin' role
router.addRoutes(/* admin specific routes */);
} else if (userRole === 'user') {
// Add routes specific to 'user' role
router.addRoutes(/* user specific routes */);
}
// ... handle other roles
}
// Step 4: Role Check Function
// Function to check if the user's role matches the required roles for a route
function hasAccess(userRole, routeRoles) {
return routeRoles.includes(userRole);
}
// Example usage
const user = getUser(); // Assume this fetches the authenticated user's details
addRoutesForRole(user.role); // Add routes based on the authenticated user's role
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment