100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Feature/new restricted access (#528)
vlichtenberg98d65b093427
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.jsonindex d58c6e503..997886752 100644--- a/manager/src/web/shared/locales/en/or.json+++ b/manager/src/web/shared/locales/en/or.json@@ -263,6 +263,9 @@"repeatPassword": "Repeat password","details": "Details","permissions":"Permissions",+ "restrictAccess": "Restrict access",+ "selectRestrictedAssets": "{{number}} assets",+ "restrictedAccessToAssets": "Restricted access to","fullAccessLabel":"Admin: full access; manage users and roles","noChildAssets": "No child assets","account": "Account",diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.jsonindex a1bc18c21..2535db9e1 100644--- a/manager/src/web/shared/locales/nl/or.json+++ b/manager/src/web/shared/locales/nl/or.json@@ -263,6 +263,9 @@"repeatPassword": "Herhaal wachtwoord","details": "Details","permissions":"Rechten",+ "restrictAccess": "Beperkte toegang",+ "selectRestrictedAssets": "{{number}} assets",+ "restrictedAccessToAssets": "Beperkte toegang tot","fullAccessLabel":"Admin: volledige toegang; gebruikers en rollen beheren","noChildAssets": "Geen onderliggende assets","account": "Account",diff --git a/ui/app/manager/src/pages/page-users.ts b/ui/app/manager/src/pages/page-users.tsindex 5b851db11..f7824e6ba 100644--- a/ui/app/manager/src/pages/page-users.ts+++ b/ui/app/manager/src/pages/page-users.ts@@ -5,13 +5,13 @@ import "@openremote/or-components/or-panel";import "@openremote/or-translate";import {EnhancedStore} from "@reduxjs/toolkit";import {AppStateKeyed, Page, PageProvider} from "@openremote/or-app";-import {ClientRole, Role, User} from "@openremote/model";+import {ClientRole, Role, User, UserAsset} from "@openremote/model";import {i18next} from "@openremote/or-translate";import {OrIcon} from "@openremote/or-icon";import {InputType, OrInputChangedEvent, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";-import {showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";+import {OrMwcDialog, showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";-import {GenericAxiosResponse, RestResponse} from "@openremote/rest";+import {GenericAxiosResponse} from "@openremote/rest";const tableStyle = require("@material/data-table/dist/mdc.data-table.css");@@ -28,6 +28,8 @@ export function pageUsersProvider<S extends AppStateKeyed>(store: EnhancedStore<interface UserModel extends User {password?: string;roles?: Role[];+ realmRoles?: Role[];+ userAssetLinks?: UserAsset[];}@customElement("page-users")@@ -205,9 +207,13 @@ class PageUsers<S extends AppStateKeyed> extends Page<S> {@state()protected _serviceUsers: UserModel[] = [];@state()+ protected _activeUser: UserModel;+ @state()protected _roles: Role[] = [];@state()protected _compositeRoles: Role[] = [];+ @state()+ protected _userAssetLinks: UserAsset[] = [];get name(): string {return "user_plural";@@ -237,6 +243,7 @@ class PageUsers<S extends AppStateKeyed> extends Page<S> {this._roles = [];this._users = [];this._serviceUsers = [];+ this._userAssetLinks = [];if (!manager.authenticated || !manager.hasRole(ClientRole.READ_USERS)) {console.warn("Not authenticated or insufficient access");@@ -288,6 +295,10 @@ class PageUsers<S extends AppStateKeyed> extends Page<S> {const roleLoaders = [...users, ...serviceUsers].map(async user => {const userRolesResponse = await (user.serviceAccount ? manager.rest.api.UserResource.getUserClientRoles(manager.displayRealm, user.id, user.username) : manager.rest.api.UserResource.getUserRoles(manager.displayRealm, user.id));user.roles = userRolesResponse.data.filter(r => r.assigned);+ const userAssetLinksResponse = await manager.rest.api.AssetResource.getUserAssetLinks({realm: manager.displayRealm, userId: user.id});+ this._userAssetLinks = this._userAssetLinks.concat(userAssetLinksResponse.data);+ const userRealmRoles = await manager.rest.api.UserResource.getUserRealmRoles(manager.displayRealm, user.id);+ user.realmRoles = userRealmRoles.data.filter(r => r.assigned);});await Promise.all(roleLoaders);@@ -316,6 +327,9 @@ class PageUsers<S extends AppStateKeyed> extends Page<S> {}(response.data as UserModel).roles = user.roles;await this._updateRoles(response.data);+ await this.handleRestrictedUserBoolean(user);+ await this.handleRestrictedAccessSelection(user);+ this._activeUser = null;} finally {this.loadUsers();}@@ -338,7 +352,7 @@ class PageUsers<S extends AppStateKeyed> extends Page<S> {await manager.rest.api.UserResource.updateUserClientRoles(manager.displayRealm, user.id, user.username, roles);}}-+private _deleteUser(user) {showOkCancelDialog(i18next.t("delete"), i18next.t("deleteUserConfirm"), i18next.t("delete")).then((ok) => {@@ -478,6 +492,45 @@ class PageUsers<S extends AppStateKeyed> extends Page<S> {}}+ protected _openAssetSelector(user: UserModel) {+ this._activeUser = user;+ const userAssetLinks = this.getUserAssetLinksByUser(user.id);+ this._activeUser.userAssetLinks = userAssetLinks;+ const hostElement = document.body;++ const dialog = new OrMwcDialog();+ dialog.isOpen = true;+ dialog.dialogTitle = i18next.t("restrictAccess");+ dialog.dialogContent = html`+ <or-asset-tree+ id="chart-asset-tree" readonly .selectedIds="${this._activeUser.userAssetLinks.map(ual => ual.id.assetId)}"+ .showSortBtn="${false}" .expandNodes="${true}" .checkboxes="${true}"+ @or-asset-tree-selection="${e => this.handleAssetIdSelection(e, this._activeUser)}"></or-asset-tree>+ `;+ dialog.dialogActions = [+ {+ default: true,+ actionName: "cancel",+ content: i18next.t("cancel"),+ action: () => {+ this._activeUser.userAssetLinks = userAssetLinks;+ this.updateAssetLinksForUser(userAssetLinks, user.id);+ }+ },+ {+ actionName: "ok",+ content: i18next.t("ok"),+ action: () => {+ this.updateAssetLinksForUser(this._activeUser.userAssetLinks, user.id);+ this._activeUser = null;+ }+ }+ ];++ hostElement.append(dialog);+ return dialog;+ }+protected _onPasswordChanged(user: UserModel, suffix: string) {const passwordComponent = this.shadowRoot.getElementById("password-" + suffix) as OrMwcInput;@@ -638,7 +691,7 @@ class PageUsers<S extends AppStateKeyed> extends Page<S> {}}"></or-mwc-input><!-- roles -->- <div style="display:flex;flex-wrap:wrap;" id="role-list-${suffix}">+ <div style="display:flex;flex-wrap:wrap;margin-bottom: 20px;" id="role-list-${suffix}">${this._roles.map(r => {return html`<or-mwc-input@@ -660,7 +713,18 @@ class PageUsers<S extends AppStateKeyed> extends Page<S> {</div><!-- restricted access -->- <!-- placeholder -->+ <div>+ <or-mwc-input+ id="${user.id}-restricted"+ .type="${InputType.CHECKBOX}"+ .label="${i18next.t("restrictedAccessToAssets") + ':'}"+ .value="${!!user.realmRoles.find(r => r.name === 'restricted_user')}"></or-mwc-input>++ <or-mwc-input outlined+ .type="${InputType.BUTTON}"+ .label="${i18next.t("selectRestrictedAssets", {number: this._userAssetLinks.filter(ual => ual.id.userId === user.id).length})}"+ @click="${() => this._openAssetSelector(user)}"></or-mwc-input>+ </div></div></div>@@ -687,4 +751,48 @@ class PageUsers<S extends AppStateKeyed> extends Page<S> {</tr>`}++ private async handleRestrictedAccessSelection(user: UserModel) {+ // delete all userassetlinks for user+ const delPromises = this.getUserAssetLinksByUser(user.id).map((ual: UserAsset) => {+ return manager.rest.api.AssetResource.deleteUserAsset(ual.id.realm, user.id, ual.id.assetId);+ });+ await Promise.all(delPromises);++ // post all new userassetlinks+ const addPromises = this._userAssetLinks.filter(ual => ual.id.userId === user.id).map((ual: UserAsset) => {+ const payload: UserAsset = {+ id: { realm: manager.displayRealm, userId: user.id, assetId: ual.id.assetId },+ };+ return manager.rest.api.AssetResource.createUserAsset(payload);+ });+ await Promise.all(addPromises)++ }++ private async handleRestrictedUserBoolean(user: UserModel) {+ const checkboxElem = this.shadowRoot.getElementById(user.id + "-restricted") as OrMwcInput;+ const role = user.realmRoles.find(r => r.name === 'restricted_user');+ role.assigned = checkboxElem.value;+ await manager.rest.api.UserResource.updateUserRealmRoles(manager.displayRealm, user.id, [role]);+ }++ private getUserAssetLinksByUser(userId): UserAsset[] {+ return this._userAssetLinks.filter(ual => ual.id.userId === userId) || [];+ }++ private updateAssetLinksForUser(userAssetLinks: UserAsset[], userId: string) {+ const linksWithoutCurrentUser = this._userAssetLinks.filter(ual => ual.id.userId !== userId);+ this._userAssetLinks = linksWithoutCurrentUser.concat(userAssetLinks);+ }++ private handleAssetIdSelection(e, user?: UserModel) {+ this._activeUser.userAssetLinks = e.detail.newNodes.map(e => ({+ id: {+ realm: manager.displayRealm,+ userId: user.id,+ assetId: e.asset.id+ }+ }));+ }}diff --git a/ui/component/or-asset-tree/src/index.ts b/ui/component/or-asset-tree/src/index.tsindex 60d995a3a..5d8b9f693 100644--- a/ui/component/or-asset-tree/src/index.ts+++ b/ui/component/or-asset-tree/src/index.ts@@ -21,7 +21,7 @@ import {style} from "./style";import manager, {AssetModelUtil, EventCallback, OREvent, subscribe, Util} from "@openremote/core";import {InputType, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";import Qs from "qs";-import {getAssetDescriptorIconTemplate} from "@openremote/or-icon";+import {getAssetDescriptorIconTemplate, OrIcon} from "@openremote/or-icon";import "@openremote/or-mwc-components/or-mwc-menu";import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";import {ListItem} from "@openremote/or-mwc-components/or-mwc-list";@@ -64,6 +64,8 @@ export interface UiAssetTreeNode extends AssetTreeNode {expanded: boolean;parent: UiAssetTreeNode;children: UiAssetTreeNode[];+ someChildrenSelected: boolean;+ allChildrenSelected: boolean;}export interface NodeSelectEventDetail {@@ -246,6 +248,12 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {@property({type: String})public sortBy?: string = "name";+ @property({type: Boolean})+ public expandNodes?: boolean = false;++ @property({type: Boolean})+ public checkboxes?: boolean = false;+protected config?: AssetTreeConfig;@property({attribute: false})@@ -376,6 +384,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {actuallySelectedIds.push(node.asset!.id!);selectedNodes.push(node);node.selected = true;+// Expand every ancestorlet parent = node.parent;while (parent) {@@ -385,6 +394,26 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {} else {node.selected = false;}++ if (this.checkboxes) {+ let parent = node.parent;+ while (parent) {+ const allChildren: UiAssetTreeNode[] = [];+ OrAssetTree._forEachNodeRecursive(parent.children, (child) => {+ allChildren.push(child);+ });+ parent.someChildrenSelected = false;+ parent.allChildrenSelected = false;++ if (allChildren.every(c => actuallySelectedIds.includes(c.asset!.id!))) {+ parent.allChildrenSelected = true;+ } else if (allChildren.some(c => actuallySelectedIds.includes(c.asset!.id!))) {+ parent.someChildrenSelected = true;+ }++ parent = parent.parent;+ }+ }});this.selectedIds = actuallySelectedIds;@@ -415,6 +444,7 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {}const isExpander = evt && (evt.target as HTMLElement).className.indexOf("expander") >= 0;+ const isParentCheckbox = evt && (evt.target as OrIcon)?.icon?.includes("checkbox-multiple");if (isExpander) {if (node && node.expandable) {@@ -441,14 +471,29 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {let deselectOthers = true;const multiSelect = !this._isReadonly() && (!this.config || !this.config.select || !this.config.select.multiSelect);- if (multiSelect && evt && (evt.ctrlKey || evt.metaKey)) {+ // determine if node was already selected+ if (this.checkboxes || (multiSelect && evt && (evt.ctrlKey || evt.metaKey))) {deselectOthers = false;if (index >= 0 && this.selectedIds && this.selectedIds.length > 1) {select = false;}}- if (deselectOthers) {+ // handle selected state+ if (isParentCheckbox) {+ selectedNodes = [...this.selectedNodes];++ const childNodes: UiAssetTreeNode[] = [];+ OrAssetTree._forEachNodeRecursive(node.children, (childNode) => {+ childNodes.push(childNode);+ });++ // based on multiple-box already selected, remove or add to array of selected nodes+ selectedNodes = (!node.allChildrenSelected)+ ? selectedNodes.concat(childNodes)+ : selectedNodes.filter(n => !childNodes.map(cn => cn.asset!.id).includes(n.asset!.id));++ } else if (deselectOthers) {selectedNodes = [node];} else if (select) {if (index < 0) {@@ -866,6 +911,14 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {if (this.selectedIds && this.selectedIds.length > 0) {this._updateSelectedNodes();}++ if (this.expandNodes) {+ OrAssetTree._forEachNodeRecursive(this._nodes, (node) => {+ if (node.children && node.children.length > 0) {+ node.expanded = true;+ }+ });+ }}protected _buildChildTreeNodes(treeNode: UiAssetTreeNode, assets: Asset[], sortFunction: (a: UiAssetTreeNode, b: UiAssetTreeNode) => number) {@@ -889,6 +942,15 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {const descriptor = AssetModelUtil.getAssetDescriptor(treeNode.asset!.type!);+ let parentCheckboxIcon;+ if (treeNode.allChildrenSelected) {+ parentCheckboxIcon = 'checkbox-multiple-marked';+ } else if (treeNode.someChildrenSelected) {+ parentCheckboxIcon = 'checkbox-multiple-marked-outline';+ }else {+ parentCheckboxIcon = 'checkbox-multiple-blank-outline';+ }+return html`<li ?data-selected="${treeNode.selected}" ?data-expanded="${treeNode.expanded}" @click="${(evt: MouseEvent) => this._onNodeClicked(evt, treeNode)}"><div class="node-container" style="padding-left: ${level * 22}px">@@ -896,6 +958,18 @@ export class OrAssetTree extends subscribe(manager)(LitElement) {<div class="expander" ?data-expandable="${treeNode.expandable}"></div>${getAssetDescriptorIconTemplate(descriptor)}<span>${treeNode.asset!.name}</span>+ ${this.checkboxes ? html`+ <span class="mdc-list-item__graphic">+ ${treeNode.expandable+ ? html`<div class="mdc-checkbox">+ <or-icon class="mdc-checkbox--parent" icon="${parentCheckboxIcon}"></or-icon>+ </div>`+ : ``}+ <div class="mdc-checkbox">+ ${treeNode.selected ? html`<or-icon icon="checkbox-marked"></or-icon>`: html`<or-icon icon="checkbox-blank-outline"></or-icon>`}+ </div>+ </span>`+ : ``}</div></div><ol>diff --git a/ui/component/or-asset-tree/src/style.ts b/ui/component/or-asset-tree/src/style.tsindex a043432e3..077d4c8f2 100644--- a/ui/component/or-asset-tree/src/style.ts+++ b/ui/component/or-asset-tree/src/style.ts@@ -190,5 +190,32 @@ export const style = css`width: 26px;}}++ .mdc-list-item__graphic {+ margin-left: auto;+ display: flex;+ margin-right: 5px;+ }++ .mdc-checkbox {+ display: flex;+ height: 100%;+ align-items: center;+ }++ .mdc-checkbox or-icon {+ height: 15px;+ width: auto;+ color: var(--internal-or-asset-tree-line-color);+ }+ .mdc-checkbox or-icon.mdc-checkbox--parent {+ height: 17px;+ }++ .mdc-checkbox or-icon[icon="checkbox-marked"],+ .mdc-checkbox or-icon[icon="checkbox-multiple-marked"],+ .mdc-checkbox or-icon[icon="checkbox-multiple-marked-outline"] {+ color: var(--internal-or-asset-tree-selected-color);+ }`;