Team based role auth for routes

This commit is contained in:
2024-05-23 09:32:22 -04:00
parent 55bc1acbb3
commit c03ad48615
6 changed files with 63 additions and 26 deletions

View File

@@ -9,6 +9,10 @@ import {
import routes from './routes';
import { useAuthStore } from 'src/stores/auth';
const publicRoutes = routes
.filter((route) => route.meta?.publicRoute)
.map((r) => r.path);
/*
* If not building with SSR mode, you can
* directly export the Router instantiation;
@@ -35,15 +39,33 @@ export default route(function (/* { store, ssrContext } */) {
history: createHistory(process.env.VUE_ROUTER_BASE),
});
Router.beforeEach((to) => {
const publicPages = routes
.filter((route) => route.meta?.publicRoute)
.map((r) => r.path);
const authRequired = !publicPages.includes(to.path);
Router.beforeEach(async (to, from, next) => {
const authStore = useAuthStore();
const currentUser = authStore.currentUser;
const authRequired = !publicRoutes.includes(to.path);
const requiredRoles = to.meta?.requiredRoles as string[];
if (authRequired && !useAuthStore().currentUser) {
return '/login';
if (authRequired && !currentUser) {
return next('/login');
}
if (requiredRoles) {
if (!currentUser) {
return next('/login');
}
try {
const hasRole = await authStore.hasRequiredRole(requiredRoles);
if (!hasRole) {
return next(from);
}
} catch (error) {
console.error('Failed to fetch user teams:', error);
return next('/error'); // Redirect to an error page or handle it as needed
}
}
next();
});
return Router;