mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-15 23:24:52 +09:00
Adds a permissions array to PluginDeclaration, a type-level Permissions registry that plugins extend with module augmentation, and registerPluginPermissions() called from all entrypoints. checkPermission and the web UI hasPermission helpers now take PermissionName so typos are compile errors. Core definitions move into a corePermissions array that the interface derives its keys from. Closes #987 Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: Cooldude2606 <25043174+Cooldude2606@users.noreply.github.com>
85 lines
2.1 KiB
TypeScript
85 lines
2.1 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: lib.PermissionName) {
|
|
if (!lib.permissions.has(permission)) {
|
|
throw new Error(`permission ${permission} does not exist`);
|
|
}
|
|
}
|
|
|
|
function hasPermission(permission: lib.PermissionName): 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: lib.PermissionName): boolean | null {
|
|
if (!roles) {
|
|
return null;
|
|
}
|
|
checkPermissionExists(permission);
|
|
return hasPermission(permission);
|
|
},
|
|
hasAnyPermission(...permissions: lib.PermissionName[]): 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: lib.PermissionName[]): 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();
|
|
},
|
|
};
|
|
}
|