feat: add support to check access permissions for /console (#6775)

#### What type of PR is this?

/area ui
/kind improvement
/milestone 2.20.x

#### What this PR does / why we need it:

支持检查是否有权限访问 /console。

#### Which issue(s) this PR fixes:

Fixes #6773 

#### Does this PR introduce a user-facing change?

```release-note
None
```
pull/6771/head^2
Ryan Wang 2024-10-07 17:38:51 +08:00 committed by GitHub
parent 709884212a
commit f78f7dad02
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 40 additions and 13 deletions

View File

@ -1,22 +1,49 @@
import { rbacAnnotations } from "@/constants/annotations";
import { useRoleStore } from "@/stores/role";
import { useUserStore } from "@/stores/user";
import { hasPermission } from "@/utils/permission";
import type { Router } from "vue-router";
import type { Role } from "@halo-dev/api-client";
import type { RouteLocationNormalized, Router } from "vue-router";
export function setupPermissionGuard(router: Router) {
router.beforeEach((to, _, next) => {
const userStore = useUserStore();
const roleStore = useRoleStore();
const { uiPermissions } = roleStore.permissions;
const { meta } = to;
if (meta && meta.permissions) {
const flag = hasPermission(
Array.from(uiPermissions),
meta.permissions as string[],
true
);
if (!flag) {
next({ name: "Forbidden" });
}
if (isConsoleAccessDisallowed(userStore.currentRoles)) {
window.location.href = "/uc";
return;
}
if (checkRoutePermissions(to, roleStore.permissions.uiPermissions)) {
next();
} else {
next({ name: "Forbidden" });
}
next();
});
}
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;
}