mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-16 15:30:41 +09:00
Throw an error if an attempt is made to check for a permission that does not exist in the Web UI to prevent future bad permission checks going unnoticed.
85 lines
2.0 KiB
TypeScript
85 lines
2.0 KiB
TypeScript
import { useContext, useEffect, useState } from "react";
|
|
import { UserAccount } from "../BaseWebPlugin";
|
|
import * as lib from "@clusterio/lib";
|
|
|
|
import { notifyErrorHandler } from "../util/notify";
|
|
import ControlContext from "../components/ControlContext";
|
|
|
|
|
|
export function useAccount(): UserAccount {
|
|
let control = useContext(ControlContext);
|
|
let [name, setName] = useState<string>(control.accountName || "");
|
|
let [roles, setRoles] = useState<any[]>(control.accountRoles || []);
|
|
|
|
useEffect(() => {
|
|
function onAccountUpdate(account: lib.AccountDetails) {
|
|
setName(account.name);
|
|
setRoles(account.roles);
|
|
}
|
|
control.onAccountUpdate(onAccountUpdate);
|
|
return () => {
|
|
control.offAccountUpdate(onAccountUpdate);
|
|
};
|
|
}, [control]);
|
|
|
|
function checkPermissionExists(permission: string) {
|
|
if (!lib.permissions.has(permission)) {
|
|
throw new Error(`permission ${permission} does not exist`);
|
|
}
|
|
}
|
|
|
|
function hasPermission(permission: string): boolean {
|
|
for (let role of roles) {
|
|
if (role.permissions.includes("core.admin") || role.permissions.includes(permission)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
return {
|
|
name,
|
|
roles,
|
|
hasPermission(permission: string): boolean | null {
|
|
if (!roles) {
|
|
return null;
|
|
}
|
|
checkPermissionExists(permission);
|
|
return hasPermission(permission);
|
|
},
|
|
hasAnyPermission(...permissions: string[]): boolean | null {
|
|
if (!roles) {
|
|
return null;
|
|
}
|
|
for (let permission of permissions) {
|
|
checkPermissionExists(permission);
|
|
}
|
|
for (let permission of permissions) {
|
|
if (hasPermission(permission)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
},
|
|
hasAllPermission(...permissions: string[]): boolean | null {
|
|
if (!roles) {
|
|
return null;
|
|
}
|
|
for (let permission of permissions) {
|
|
checkPermissionExists(permission);
|
|
}
|
|
for (let permission of permissions) {
|
|
if (!hasPermission(permission)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
},
|
|
logOut() {
|
|
control.loggingOut = true;
|
|
notifyErrorHandler("Error logging out");
|
|
control.shutdown();
|
|
},
|
|
};
|
|
}
|