2024-10-07 09:38:51 +00:00
|
|
|
import { rbacAnnotations } from "@/constants/annotations";
|
2022-07-15 08:26:27 +00:00
|
|
|
import { useRoleStore } from "@/stores/role";
|
2024-10-07 09:38:51 +00:00
|
|
|
import { useUserStore } from "@/stores/user";
|
2022-07-15 08:26:27 +00:00
|
|
|
import { hasPermission } from "@/utils/permission";
|
2024-10-07 09:38:51 +00:00
|
|
|
import type { Role } from "@halo-dev/api-client";
|
|
|
|
import type { RouteLocationNormalized, Router } from "vue-router";
|
2022-07-15 08:26:27 +00:00
|
|
|
|
|
|
|
export function setupPermissionGuard(router: Router) {
|
2024-09-28 10:19:41 +00:00
|
|
|
router.beforeEach((to, _, next) => {
|
2024-10-07 09:38:51 +00:00
|
|
|
const userStore = useUserStore();
|
2022-07-15 08:26:27 +00:00
|
|
|
const roleStore = useRoleStore();
|
2024-10-07 09:38:51 +00:00
|
|
|
|
|
|
|
if (isConsoleAccessDisallowed(userStore.currentRoles)) {
|
|
|
|
window.location.href = "/uc";
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (checkRoutePermissions(to, roleStore.permissions.uiPermissions)) {
|
|
|
|
next();
|
|
|
|
} else {
|
|
|
|
next({ name: "Forbidden" });
|
2022-07-15 08:26:27 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2024-10-07 09:38:51 +00:00
|
|
|
|
|
|
|
function isConsoleAccessDisallowed(currentRoles?: Role[]): boolean {
|
|
|
|
return (
|
|
|
|
currentRoles?.some(
|
|
|
|
(role) =>
|
|
|
|
role.metadata.annotations?.[rbacAnnotations.DISALLOW_ACCESS_CONSOLE] ===
|
|
|
|
"true"
|
|
|
|
) || false
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
function checkRoutePermissions(
|
|
|
|
to: RouteLocationNormalized,
|
|
|
|
uiPermissions: string[]
|
|
|
|
): boolean {
|
|
|
|
const { meta } = to;
|
|
|
|
if (meta?.permissions) {
|
|
|
|
return hasPermission(
|
|
|
|
Array.from(uiPermissions),
|
|
|
|
meta.permissions as string[],
|
|
|
|
true
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|