Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Simplified Dashboard permissions model (#1727)

Martin Peeters1246f6e7b1e5
diff --git a/manager/src/main/java/org/openremote/manager/dashboard/DashboardResourceImpl.java b/manager/src/main/java/org/openremote/manager/dashboard/DashboardResourceImpl.java
index cd78dfd98..87e790e0d 100644
--- a/manager/src/main/java/org/openremote/manager/dashboard/DashboardResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/dashboard/DashboardResourceImpl.java
@@ -34,8 +34,8 @@ import org.openremote.model.query.filter.RealmPredicate;
import org.openremote.model.security.ClientRole;
import org.openremote.model.util.ValueUtil;
-import java.util.Collections;
import java.util.HashSet;
+import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
@@ -90,12 +90,8 @@ public class DashboardResourceImpl extends ManagerWebResource implements Dashboa
public Dashboard[] query(RequestParams requestParams, DashboardQuery query) {
if(query == null) {
query = this.createDashboardQuery(getRequestRealmName());
- }
- if(query.realm == null || query.realm.name == null) {
- query.realm(new RealmPredicate(getRequestRealmName()));
- }
- if(isAuthenticated() && !isSuperUser() && !(getAuthenticatedRealmName().equals(query.realm.name))) {
- throw new WebApplicationException(FORBIDDEN);
+ } else {
+ query = this.sanitizeDashboardQuery(query);
}
return dashboardStorageService.query(query, getUserId());
@@ -112,11 +108,8 @@ public class DashboardResourceImpl extends ManagerWebResource implements Dashboa
}
try {
dashboard.setOwnerId(getUserId());
- dashboard.setViewAccess(DashboardAccess.SHARED);
- dashboard.setEditAccess(DashboardAccess.SHARED);
-
+ dashboard.setAccess(DashboardAccess.SHARED);
return this.dashboardStorageService.createNew(ValueUtil.clone(dashboard));
-
} catch (IllegalStateException ex) {
ex.printStackTrace();
throw new WebApplicationException(ex, INTERNAL_SERVER_ERROR);
@@ -161,39 +154,39 @@ public class DashboardResourceImpl extends ManagerWebResource implements Dashboa
}
/**
- * Function that builds an {@link DashboardQuery} object, based on user permissions.
+ * Function that corrects an {@link DashboardQuery} object, based on user permissions.
* Automatically fills NULL values, adjusts access filters based on roles, etc.
*
- * @param realm
- * @return An instantiated DashboardQuery with the correct permissions based on the user.
+ * @param query The query to correct
+ * @return A DashboardQuery with the correct permissions based on the user.
*/
- protected DashboardQuery createDashboardQuery(String realm) {
- if(realm == null) {
- realm = getRequestRealmName();
+ protected DashboardQuery sanitizeDashboardQuery(DashboardQuery query) {
+ Set<DashboardAccess> userAccess = new HashSet<>(Set.of(
+ Optional.ofNullable(query.getConditions().getDashboard().getAccess()).orElse(new DashboardAccess[0])
+ ));
+ Set<DashboardQuery.AssetAccess> assetAccess = new HashSet<>(Set.of(
+ Optional.ofNullable(query.getConditions().getAsset().getAccess()).orElse(new DashboardQuery.AssetAccess[0])
+ ));
+
+ if(query.getRealm() == null || query.getRealm().name == null) {
+ query.realm(new RealmPredicate(getRequestRealmName()));
}
- DashboardQuery query = new DashboardQuery().realm(new RealmPredicate(realm));
- Set<DashboardAccess> userViewAccess = new HashSet<>(Set.of(query.conditions.getDashboard().getViewAccess()));
- Set<DashboardAccess> userEditAccess = new HashSet<>(Set.of(query.conditions.getDashboard().getEditAccess()));
- Set<DashboardQuery.AssetAccess> assetAccess = new HashSet<>(Set.of(query.conditions.getAsset().getAccess()));
// Detect cross realm access
- if(isAuthenticated() && !isSuperUser() && !realm.equals(getAuthenticatedRealmName())) {
+ if(isAuthenticated() && !isSuperUser() && !query.getRealm().name.equals(getAuthenticatedRealmName())) {
throw new WebApplicationException(FORBIDDEN);
}
// User always has access to public dashboards
- userViewAccess.add(DashboardAccess.PUBLIC);
- userEditAccess.add(DashboardAccess.PUBLIC);
+ userAccess.add(DashboardAccess.PUBLIC);
assetAccess.add(DashboardQuery.AssetAccess.REALM);
// Adjust query object based on user roles/permissions
if (isAuthenticated()) {
assetAccess.add(DashboardQuery.AssetAccess.LINKED);
- if (hasResourceRole(ClientRole.READ_INSIGHTS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
- Collections.addAll(userViewAccess, DashboardAccess.SHARED, DashboardAccess.PRIVATE);
- }
- if (hasResourceRole(ClientRole.WRITE_INSIGHTS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
- Collections.addAll(userEditAccess, DashboardAccess.SHARED, DashboardAccess.PRIVATE);
+ if (!hasResourceRole(ClientRole.READ_INSIGHTS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
+ userAccess.remove(DashboardAccess.SHARED);
+ userAccess.remove(DashboardAccess.PRIVATE);
}
if (isRestrictedUser()) {
assetAccess = new HashSet<>(Set.of(DashboardQuery.AssetAccess.RESTRICTED));
@@ -202,19 +195,31 @@ public class DashboardResourceImpl extends ManagerWebResource implements Dashboa
// If not logged in, force only public read/write access
else {
- userViewAccess = new HashSet<>(Set.of(DashboardAccess.PUBLIC));
- userEditAccess = new HashSet<>(Set.of(DashboardAccess.PUBLIC));
+ userAccess = new HashSet<>(Set.of(DashboardAccess.PUBLIC));
assetAccess = new HashSet<>(Set.of(DashboardQuery.AssetAccess.REALM));
}
// Build query object and return
return query.conditions(new DashboardQuery.Conditions(
new DashboardQuery.DashboardConditions()
- .viewAccess(userViewAccess.toArray(new DashboardAccess[0]))
- .editAccess(userEditAccess.toArray(new DashboardAccess[0])),
+ .access(userAccess.toArray(new DashboardAccess[0])),
new DashboardQuery.AssetConditions()
.access(assetAccess.toArray(new DashboardQuery.AssetAccess[0]))
)
);
}
+
+ /**
+ * Function that builds an {@link DashboardQuery} object, based on user permissions.
+ * Automatically fills NULL values, adjusts access filters based on roles, etc.
+ *
+ * @param realm The realm to create a DashboardQuery for.
+ * @return An instantiated DashboardQuery with the correct permissions based on the user.
+ */
+ protected DashboardQuery createDashboardQuery(String realm) {
+ if(realm == null) {
+ realm = getRequestRealmName();
+ }
+ return this.sanitizeDashboardQuery(new DashboardQuery().realm(new RealmPredicate(realm)));
+ }
}
diff --git a/manager/src/main/java/org/openremote/manager/dashboard/DashboardStorageService.java b/manager/src/main/java/org/openremote/manager/dashboard/DashboardStorageService.java
index 1ca5d7b86..8a215d1c7 100644
--- a/manager/src/main/java/org/openremote/manager/dashboard/DashboardStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/dashboard/DashboardStorageService.java
@@ -90,40 +90,43 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe
*/
@SuppressWarnings({"unchecked", "SqlSourceToSinkFlow"})
protected Dashboard[] query(DashboardQuery dashboardQuery, String userId) {
+ if(dashboardQuery.getRealm() == null) {
+ return new Dashboard[0];
+ }
- return (Dashboard[]) persistenceService.doReturningTransaction((em) -> {
+ StringBuilder sql = new StringBuilder("SELECT * FROM Dashboard WHERE realm LIKE :realm");
+ Map<String, Object> parameters = new HashMap<>();
+ parameters.put("realm", dashboardQuery.getRealm().name);
- StringBuilder sql = new StringBuilder("SELECT * FROM Dashboard WHERE realm LIKE :realm");
- Map<String, Object> parameters = new HashMap<>();
- parameters.put("realm", dashboardQuery.realm.name);
+ if(dashboardQuery.getIds() != null) {
+ this.appendSqlIdFilter(sql, dashboardQuery, parameters);
+ }
+ if(dashboardQuery.getNames() != null) {
+ this.appendSqlNamesFilter(sql, dashboardQuery, parameters);
+ }
+ if(dashboardQuery.getUserIds() != null) {
+ this.appendSqlUserIdsFilter(sql, dashboardQuery, parameters);
+ }
+ if(dashboardQuery.getConditions().getDashboard() != null) {
+ this.appendSqlDashboardConditionsFilter(sql, dashboardQuery, parameters, userId);
+ }
+ if(dashboardQuery.getConditions().getAsset() != null) {
+ this.appendSqlAssetConditionsFilter(sql, dashboardQuery, parameters, userId);
+ }
- if(dashboardQuery.ids != null) {
- this.appendSqlIdFilter(sql, dashboardQuery, parameters);
- }
- if(dashboardQuery.names != null) {
- this.appendSqlNamesFilter(sql, dashboardQuery, parameters);
- }
- if(dashboardQuery.userIds != null) {
- this.appendSqlUserIdsFilter(sql, dashboardQuery, parameters);
- }
- if(dashboardQuery.conditions.getDashboard() != null) {
- this.appendSqlDashboardConditionsFilter(sql, dashboardQuery, parameters, userId);
- }
- if(dashboardQuery.conditions.getAsset() != null) {
- this.appendSqlAssetConditionsFilter(sql, dashboardQuery, parameters, userId);
- }
+ /** TODO: Implement SELECT filtering {@link org.openremote.model.query.DashboardQuery.Select} */
- /** TODO: Implement SELECT filtering {@link org.openremote.model.query.DashboardQuery.Select} */
+ // Apply pagination
+ if(dashboardQuery.start != null) {
+ sql.append(" OFFSET :start");
+ parameters.put("start", dashboardQuery.start);
+ }
+ if(dashboardQuery.limit != null) {
+ sql.append(" LIMIT :limit");
+ parameters.put("limit", dashboardQuery.limit);
+ }
- // Apply pagination
- if(dashboardQuery.start != null) {
- sql.append(" OFFSET :start");
- parameters.put("start", dashboardQuery.start);
- }
- if(dashboardQuery.limit != null) {
- sql.append(" LIMIT :limit");
- parameters.put("limit", dashboardQuery.limit);
- }
+ return (Dashboard[]) persistenceService.doReturningTransaction((em) -> {
// Create query object and apply parameters
Query query = em.createNativeQuery(sql.toString(), Dashboard.class);
@@ -140,7 +143,7 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe
*/
protected StringBuilder appendSqlIdFilter(StringBuilder sqlBuilder, DashboardQuery query, Map<String, Object> sqlParams) {
sqlBuilder.append(" AND id IN (:ids)");
- sqlParams.put("ids", List.of(query.ids));
+ sqlParams.put("ids", List.of(Optional.ofNullable(query.getIds()).orElse(new String[0])));
return sqlBuilder;
}
@@ -150,9 +153,9 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe
* @return {@link StringBuilder} used for building
*/
protected StringBuilder appendSqlNamesFilter(StringBuilder sqlBuilder, DashboardQuery query, Map<String, Object> sqlParams) {
- IntStream.range(0, query.names.length).forEach(index -> {
+ IntStream.range(0, query.getNames().length).forEach(index -> {
String key = "name" + index;
- StringPredicate pred = query.names[index];
+ StringPredicate pred = query.getNames()[index];
sqlBuilder.append(" AND ").append(pred.caseSensitive ? "display_name" : "UPPER(display_name)").append(pred.negate ? " NOT" : "");
switch (pred.match) {
case BEGIN -> sqlBuilder.append(" LIKE :").append(key).append(" || '%'");
@@ -167,7 +170,7 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe
protected StringBuilder appendSqlUserIdsFilter(StringBuilder sqlBuilder, DashboardQuery query, Map<String, Object> sqlParams) {
sqlBuilder.append(" AND owner_id IN (:ownerIds)");
- sqlParams.put("ownerIds", List.of(query.userIds));
+ sqlParams.put("ownerIds", List.of(Optional.ofNullable(query.getUserIds()).orElse(new String[0])));
return sqlBuilder;
}
@@ -177,30 +180,23 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe
* @return {@link StringBuilder} used for building
*/
protected StringBuilder appendSqlDashboardConditionsFilter(StringBuilder sqlBuilder, DashboardQuery query, Map<String, Object> sqlParams, String userId) {
- var dashboardConditions = query.conditions.getDashboard();
- if(dashboardConditions.getViewAccess() != null || dashboardConditions.getEditAccess() != null) {
+ var dashboardConditions = query.getConditions().getDashboard();
+ if(dashboardConditions.getAccess() != null) {
- List<DashboardAccess> viewAccess = new ArrayList<>(Arrays.asList(dashboardConditions.getViewAccess()));
- List<DashboardAccess> editAccess = new ArrayList<>(Arrays.asList(dashboardConditions.getEditAccess()));
+ List<DashboardAccess> access = new ArrayList<>(Arrays.asList(dashboardConditions.getAccess()));
sqlBuilder.append(" AND (");
// When requesting PRIVATE dashboards, check whether the user is also the owner
- if(userId != null && viewAccess.contains(DashboardAccess.PRIVATE)) {
- viewAccess.remove(DashboardAccess.PRIVATE);
- sqlBuilder.append("(view_access = 2 AND owner_id = :userId) OR ");
- sqlParams.put("userId", userId);
- }
- if(userId != null && editAccess.contains(DashboardAccess.PRIVATE)) {
- editAccess.remove(DashboardAccess.PRIVATE);
- sqlBuilder.append("(edit_access = 2 AND owner_id = :userId) OR ");
+ if(userId != null && access.contains(DashboardAccess.PRIVATE)) {
+ access.remove(DashboardAccess.PRIVATE);
+ sqlBuilder.append("(access = 2 AND owner_id = :userId) OR ");
sqlParams.put("userId", userId);
}
// Append simple SQL filter by dashboard access
- sqlBuilder.append("(view_access IN (:viewAccess) OR edit_access IN (:editAccess)))");
+ sqlBuilder.append("(access IN (:access)))");
- sqlParams.put("viewAccess", viewAccess.stream().map(DashboardAccess::ordinal).collect(Collectors.toList()));
- sqlParams.put("editAccess", editAccess.stream().map(DashboardAccess::ordinal).collect(Collectors.toList()));
+ sqlParams.put("access", access.stream().map(DashboardAccess::ordinal).collect(Collectors.toList()));
/** TODO: Implement filtering by {@link org.openremote.model.query.DashboardQuery.DashboardConditions.minWidgets} */
@@ -216,24 +212,24 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe
* @return {@link StringBuilder} used for building
*/
protected StringBuilder appendSqlAssetConditionsFilter(StringBuilder sqlBuilder, DashboardQuery query, Map<String, Object> sqlParams, String userId) {
- var assetConditions = query.conditions.getAsset();
- if(assetConditions.access != null) {
- List<DashboardQuery.AssetAccess> levels = Arrays.asList(assetConditions.access);
+ var assetConditions = query.getConditions().getAsset();
+ if(assetConditions.getAccess() != null) {
+ List<DashboardQuery.AssetAccess> levels = Arrays.asList(Optional.ofNullable(assetConditions.getAccess()).orElse(new DashboardQuery.AssetAccess[0]));
if (levels.size() == 1 && levels.contains(DashboardQuery.AssetAccess.RESTRICTED)) {
// Gather asset ids the user is linked to
- List<UserAssetLink> userAssetLinks = assetStorageService.findUserAssetLinks(query.realm.name, userId, null);
+ List<UserAssetLink> userAssetLinks = assetStorageService.findUserAssetLinks(query.getRealm().name, userId, null);
List<String> assetIds = userAssetLinks.stream().map(ua -> ua.getId().getAssetId()).collect(Collectors.toList());
// AT_LEAST_ONE - When user has access to the assets of at least 1 widget
- if(assetConditions.minAmount == DashboardQuery.ConditionMinAmount.AT_LEAST_ONE) {
+ if(assetConditions.getMinAmount() == DashboardQuery.ConditionMinAmount.AT_LEAST_ONE) {
sqlBuilder.append(" AND (template IS NULL OR template->'widgets' IS NULL OR EXISTS (");
sqlBuilder.append("SELECT 1 FROM jsonb_array_elements(COALESCE(template->'widgets', '[]')) AS j(widget) ");
sqlBuilder.append("LEFT JOIN jsonb_array_elements(COALESCE(widget->'widgetConfig'->'attributeRefs', '[]')) AS a(attributeRef) ");
sqlBuilder.append("ON a->>'id' IN (:assetIds)))");
}
// ALL - User needs access to the assets of ALL widgets (or the dashboard has no widgets)
- else if(assetConditions.minAmount == DashboardQuery.ConditionMinAmount.ALL) {
+ else if(assetConditions.getMinAmount() == DashboardQuery.ConditionMinAmount.ALL) {
sqlBuilder.append(" AND NOT EXISTS (");
sqlBuilder.append("SELECT 1 FROM jsonb_array_elements(template->'widgets') AS j(widget), ");
sqlBuilder.append("jsonb_array_elements(widget->'widgetConfig'->'attributeRefs') AS a(attributeRef) ");
@@ -271,7 +267,7 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe
throw new IllegalArgumentException("No dashboard is specified.");
}
return persistenceService.doReturningTransaction(em -> {
- if(dashboard.getId() != null && dashboard.getId().length() > 0) {
+ if(dashboard.getId() != null && !dashboard.getId().isEmpty()) {
Dashboard d = em.find(Dashboard.class, dashboard.getId()); // checking whether dashboard is already in database
if(d != null) {
throw new IllegalArgumentException("This dashboard has already been created.");
@@ -292,22 +288,16 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe
if(userId == null) {
throw new IllegalArgumentException("No userId is specified.");
}
- // Query the dashboards with the same ID (which is only 1), and that userId is able to EDIT
+ // Query the dashboards with the same ID (which is only 1)
var query = new DashboardQuery()
.ids(dashboard.getId())
.realm(new RealmPredicate(realm))
- .userIds(userId)
- .limit(1)
- .conditions(new DashboardQuery.Conditions().dashboard(
- new DashboardQuery.DashboardConditions()
- .viewAccess(new DashboardAccess[]{})
- .editAccess(new DashboardAccess[]{DashboardAccess.SHARED, DashboardAccess.PRIVATE})
- ));
+ .limit(1);
Dashboard[] dashboards = this.query(query, userId);
if(dashboards != null && dashboards.length > 0) {
Dashboard d = dashboards[0];
return persistenceService.doReturningTransaction(em -> {
- dashboard.setVersion(d.getVersion());
+ dashboard.setVersion(d.getVersion()); // TODO: Investigate why versioning is not correct for Dashboard model
return em.merge(dashboard);
});
} else {
@@ -327,15 +317,11 @@ public class DashboardStorageService extends RouteBuilder implements ContainerSe
}
return persistenceService.doReturningTransaction(em -> {
- // Query the dashboards with the same ID (which is only 1), and that userId is able to EDIT
+ // Query the dashboards with the same ID (which is only 1)
Dashboard[] dashboards = this.query(new DashboardQuery()
.ids(dashboardId)
.realm(new RealmPredicate(realm))
- .userIds(userId)
- .limit(1)
- .conditions(new DashboardQuery.Conditions().dashboard(
- new DashboardQuery.DashboardConditions().editAccess(new DashboardAccess[]{ DashboardAccess.SHARED, DashboardAccess.PRIVATE })
- )),
+ .limit(1),
userId
);
if(dashboards == null || dashboards.length == 0) {
diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20250422_01__DashboardAccess.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20250422_01__DashboardAccess.sql
new file mode 100644
index 000000000..7070f51fe
--- /dev/null
+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20250422_01__DashboardAccess.sql
@@ -0,0 +1,2 @@
+ALTER TABLE DASHBOARD DROP COLUMN edit_access;
+ALTER TABLE DASHBOARD RENAME COLUMN view_access TO access;
diff --git a/model/src/main/java/org/openremote/model/dashboard/Dashboard.java b/model/src/main/java/org/openremote/model/dashboard/Dashboard.java
index 5fbeca238..f0b910db1 100644
--- a/model/src/main/java/org/openremote/model/dashboard/Dashboard.java
+++ b/model/src/main/java/org/openremote/model/dashboard/Dashboard.java
@@ -36,11 +36,8 @@ public class Dashboard {
@Column(name = "OWNER_ID", nullable = false)
protected String ownerId;
- @Column(name = "VIEW_ACCESS", nullable = false)
- protected DashboardAccess viewAccess;
-
- @Column(name = "EDIT_ACCESS", nullable = false)
- protected DashboardAccess editAccess;
+ @Column(name = "ACCESS", nullable = false)
+ protected DashboardAccess access;
@NotBlank(message = "{Dashboard.displayName.NotBlank}")
@Column(name = "DISPLAY_NAME", nullable = false)
@@ -58,10 +55,12 @@ public class Dashboard {
public Dashboard() {
}
- public Dashboard(String realm, String displayName, DashboardScreenPreset[] screenPresets) {
+ public Dashboard(String realm, String displayName, DashboardScreenPreset[] screenPresets, String ownerId) {
this.realm = realm;
this.template = new DashboardTemplate(screenPresets);
this.displayName = displayName;
+ this.access = DashboardAccess.SHARED;
+ this.ownerId = ownerId;
}
public Dashboard setId(String id) {
@@ -89,13 +88,8 @@ public class Dashboard {
return this;
}
- public Dashboard setViewAccess(DashboardAccess access) {
- this.viewAccess = access;
- return this;
- }
-
- public Dashboard setEditAccess(DashboardAccess access) {
- this.editAccess = access;
+ public Dashboard setAccess(DashboardAccess access) {
+ this.access = access;
return this;
}
@@ -130,12 +124,8 @@ public class Dashboard {
return this.ownerId;
}
- public DashboardAccess getViewAccess() {
- return this.viewAccess;
- }
-
- public DashboardAccess getEditAccess() {
- return this.editAccess;
+ public DashboardAccess getAccess() {
+ return this.access;
}
public String getDisplayName() {
diff --git a/model/src/main/java/org/openremote/model/query/DashboardQuery.java b/model/src/main/java/org/openremote/model/query/DashboardQuery.java
index 64d7705b7..250031635 100644
--- a/model/src/main/java/org/openremote/model/query/DashboardQuery.java
+++ b/model/src/main/java/org/openremote/model/query/DashboardQuery.java
@@ -70,46 +70,23 @@ public class DashboardQuery implements Serializable {
*
*/
public static class DashboardConditions {
- protected DashboardAccess[] viewAccess;
- protected DashboardAccess[] editAccess;
- protected Integer minWidgets;
+ protected DashboardAccess[] access;
public DashboardConditions() {
- this.viewAccess = new DashboardAccess[]{DashboardAccess.PUBLIC, DashboardAccess.SHARED, DashboardAccess.PRIVATE};
- this.editAccess = new DashboardAccess[]{DashboardAccess.PUBLIC, DashboardAccess.SHARED, DashboardAccess.PRIVATE};
+ this.access = new DashboardAccess[]{DashboardAccess.PUBLIC, DashboardAccess.SHARED, DashboardAccess.PRIVATE};
}
- public DashboardConditions(DashboardAccess[] viewAccess, DashboardAccess[] editAccess, Integer minWidgets) {
- this.viewAccess = viewAccess;
- this.editAccess = editAccess;
- this.minWidgets = minWidgets;
- }
-
- public DashboardConditions viewAccess(DashboardAccess[] access) {
- this.viewAccess = access;
- return this;
- }
-
- public DashboardConditions editAccess(DashboardAccess[] editAccess) {
- this.editAccess = editAccess;
- return this;
+ public DashboardConditions(DashboardAccess[] access) {
+ this.access = access;
}
- public DashboardConditions minWidgets(Integer minWidgets) {
- this.minWidgets = minWidgets;
+ public DashboardConditions access(DashboardAccess[] access) {
+ this.access = access;
return this;
}
- public DashboardAccess[] getViewAccess() {
- return viewAccess;
- }
-
- public DashboardAccess[] getEditAccess() {
- return editAccess;
- }
-
- public Integer getMinWidgets() {
- return minWidgets;
+ public DashboardAccess[] getAccess() {
+ return access;
}
}
@@ -230,7 +207,6 @@ public class DashboardQuery implements Serializable {
this.select = new Select();
this.conditions = new Conditions();
this.start = 0;
- this.limit = 50;
}
public DashboardQuery select(Select select) {
@@ -281,4 +257,36 @@ public class DashboardQuery implements Serializable {
this.limit = limit;
return this;
}
+
+ public Select getSelect() {
+ return select;
+ }
+
+ public Conditions getConditions() {
+ return conditions;
+ }
+
+ public String[] getIds() {
+ return ids;
+ }
+
+ public StringPredicate[] getNames() {
+ return names;
+ }
+
+ public String[] getUserIds() {
+ return userIds;
+ }
+
+ public RealmPredicate getRealm() {
+ return realm;
+ }
+
+ public Integer getStart() {
+ return start;
+ }
+
+ public Integer getLimit() {
+ return limit;
+ }
}
diff --git a/setup/src/demo/resources/demo/dashboards/manufacturer/harvesting.json b/setup/src/demo/resources/demo/dashboards/manufacturer/harvesting.json
index 84a538d04..f5f93cd50 100644
--- a/setup/src/demo/resources/demo/dashboards/manufacturer/harvesting.json
+++ b/setup/src/demo/resources/demo/dashboards/manufacturer/harvesting.json
@@ -4,8 +4,7 @@
"realm": "manufacturer",
"version": 11,
"ownerId": "e5ca8a39-5193-478d-ba86-57e7095679cf",
- "viewAccess": "SHARED",
- "editAccess": "SHARED",
+ "access": "SHARED",
"displayName": "Harvesting dashboard",
"template": {
"id": "vmkw9nr0i4",
diff --git a/setup/src/demo/resources/demo/dashboards/smartcity/parking.json b/setup/src/demo/resources/demo/dashboards/smartcity/parking.json
index ee1621a19..487cd4b07 100644
--- a/setup/src/demo/resources/demo/dashboards/smartcity/parking.json
+++ b/setup/src/demo/resources/demo/dashboards/smartcity/parking.json
@@ -4,8 +4,7 @@
"realm": "smartcity",
"version": 8,
"ownerId": "e5ca8a39-5193-478d-ba86-57e7095679cf",
- "viewAccess": "SHARED",
- "editAccess": "SHARED",
+ "access": "SHARED",
"displayName": "Parking dashboard",
"template": {
"id": "szpfxnrzpg",
diff --git a/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy b/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy
index 22efe81ac..4c2c0ec31 100644
--- a/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/dashboard/DashboardTest.groovy
@@ -10,7 +10,12 @@ import org.openremote.model.asset.impl.LightAsset
import org.openremote.model.attribute.MetaItem
import org.openremote.model.dashboard.*
import org.openremote.model.query.DashboardQuery
+import org.openremote.model.query.UserQuery
import org.openremote.model.query.filter.RealmPredicate
+import org.openremote.model.query.filter.StringPredicate
+import org.openremote.model.security.ClientRole
+import org.openremote.model.security.User
+import org.openremote.model.security.UserResource
import org.openremote.model.util.ValueUtil
import org.openremote.model.value.MetaItemType
import org.openremote.setup.integration.KeycloakTestSetup
@@ -45,23 +50,67 @@ class DashboardTest extends Specification implements ManagerContainerTrait {
"testuser1",
"testuser1"
).token
+ def smartcityUserAccessToken = authenticate(
+ container,
+ keycloakTestSetup.realmCity.name,
+ KEYCLOAK_CLIENT_ID,
+ "smartcity",
+ "smartcity"
+ ).token
- and: "the dashboard resource"
+ and: "the admin user has been retrieved"
def serverUri = serverUri(serverPort)
+ def adminUserResource = getClientApiTarget(serverUri, MASTER_REALM, adminUserAccessToken).proxy(UserResource)
+ def adminUser = adminUserResource.getCurrent(null)
+
+ and: "an additional user without READ_INSIGHTS is created"
+ ClientRole[] noInsightsRoles = new ClientRole[] { ClientRole.READ_ASSETS }
+ User noAccessUser = keycloakTestSetup.createUser(MASTER_REALM, "noinsights", "noinsights", "firstName", "lastName", "[email protected]", true, noInsightsRoles)
+ def noAccessUserToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "noinsights", "noinsights").token
+
+ and: "an additional user without WRITE_INSIGHTS is created"
+ ClientRole[] readonlyRoles = new ClientRole[] { ClientRole.READ_ASSETS, ClientRole.READ_INSIGHTS }
+ User readonlyUser = keycloakTestSetup.createUser(MASTER_REALM, "readinsights", "readinsights", "firstName", "lastName", "[email protected]", true, readonlyRoles)
+ def readonlyUserToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "readinsights", "readinsights").token
+
+ and: "an additional user with all permissions is created"
+ User alternativeUser = keycloakTestSetup.createUser(MASTER_REALM, "alternativeuser", "alternativeuser", "alternative", "user", "[email protected]", true, KeycloakTestSetup.REGULAR_USER_ROLES)
+ def alternativeUserToken = authenticate(container, MASTER_REALM, KEYCLOAK_CLIENT_ID, "alternativeuser", "alternativeuser").token
+
+ and: "the dashboard resource"
def adminUserDashboardResource = getClientApiTarget(serverUri, MASTER_REALM, adminUserAccessToken).proxy(DashboardResource.class)
def privateUser1DashboardResource = getClientApiTarget(serverUri, MASTER_REALM, privateUser1AccessToken).proxy(DashboardResource.class)
+ def noAccessDashboardResource = getClientApiTarget(serverUri, MASTER_REALM, noAccessUserToken).proxy(DashboardResource.class)
+ def readonlyDashboardResource = getClientApiTarget(serverUri, MASTER_REALM, readonlyUserToken).proxy(DashboardResource.class)
+ def alternativeUserDashboardResource = getClientApiTarget(serverUri, MASTER_REALM, alternativeUserToken).proxy(DashboardResource.class)
def publicUserDashboardResource = getClientApiTarget(serverUri, MASTER_REALM).proxy(DashboardResource.class)
+ def smartcityDashboardResource = getClientApiTarget(serverUri, keycloakTestSetup.realmCity.name, smartcityUserAccessToken).proxy(DashboardResource.class)
def adminUserAssetResource = getClientApiTarget(serverUri, MASTER_REALM, adminUserAccessToken).proxy(AssetResource.class)
/* ----------------------- */
// Test to verify dashboards can be CREATED and FETCHED by different users.
+ when: "a user without WRITE_INSIGHTS tries to create dashboard"
+ DashboardScreenPreset[] tempScreenPresets = Arrays.asList(new DashboardScreenPreset("preset1", DashboardScalingPreset.KEEP_LAYOUT)).toArray() as DashboardScreenPreset[]
+ Dashboard temp1NoAccess = new Dashboard(MASTER_REALM, "dashboard1", tempScreenPresets, noAccessUser.id)
+ noAccessDashboardResource.create(null, temp1NoAccess)
+
+ then: "an exception is thrown that reflects their permissions"
+ thrown ForbiddenException
+
+ when: "a user without WRITE_INSIGHTS, but with READ_INSIGHTS, tries to create dashboard"
+ Dashboard temp1Readonly = new Dashboard(MASTER_REALM, "dashboard1", tempScreenPresets, readonlyUser.id)
+ readonlyDashboardResource.create(null, temp1Readonly)
+
+ then: "an exception is also thrown"
+ thrown ForbiddenException
+
when: "a dashboard is created in the authenticated realm"
DashboardScreenPreset[] screenPresets = Arrays.asList(new DashboardScreenPreset("preset1", DashboardScalingPreset.KEEP_LAYOUT)).toArray() as DashboardScreenPreset[]
- Dashboard temp1 = new Dashboard(MASTER_REALM, "dashboard1", screenPresets)
+ Dashboard temp1 = new Dashboard(MASTER_REALM, "dashboard1", screenPresets, adminUser.id)
adminUserDashboardResource.create(null, temp1)
- Dashboard temp2 = new Dashboard(MASTER_REALM, "dashboard2", screenPresets).setOwnerId(keycloakTestSetup.testuser1Id)
+ Dashboard temp2 = new Dashboard(MASTER_REALM, "dashboard2", screenPresets, adminUser.id).setOwnerId(keycloakTestSetup.testuser1Id)
privateUser1DashboardResource.create(null, temp2)
then: "requesting the dashboard should return the same object"
@@ -74,48 +123,132 @@ class DashboardTest extends Specification implements ManagerContainerTrait {
assert adminDashboard.id == userDashboards[0].id
assert privateUser1Dashboard.id == userDashboards[1].id
+ when: "a user without READ_INSIGHTS tries to fetch a dashboard"
+ def readonlyDashboards = noAccessDashboardResource.getAllRealmDashboards(null, MASTER_REALM)
+
+ then: "an exception is thrown that reflects their lack of READ permissions"
+ assert readonlyDashboards.length == 0
+
/* ----------------------- */
// Test to verify user can query by displayName
when: "admin user tries to query dashboard by display name"
def displayNameQuery = new DashboardQuery().names("dashboard1")
- def displayNameDashboards = adminUserDashboardResource.query(null, displayNameQuery)
+ def dashboards = adminUserDashboardResource.query(null, displayNameQuery)
then: "the correct dashboard should be returned"
- assert displayNameDashboards.length == 1
- assert displayNameDashboards[0].displayName == "dashboard1"
+ assert dashboards.length == 1
+ assert dashboards[0].displayName == "dashboard1"
+ assert dashboards[0].access == DashboardAccess.SHARED
+
+ when: "a user without READ_INSIGHTS tries to query dashboard by display name"
+ dashboards = noAccessDashboardResource.query(null, displayNameQuery)
+
+ then: "no dashboards with the display name could be found"
+ assert dashboards.length == 0
+
+ when: "an unauthenticated user tries to query dashboard by display name"
+ dashboards = publicUserDashboardResource.query(null, displayNameQuery)
+
+ then: "no public dashboards with the display name could be found"
+ assert dashboards.length == 0
/* ----------------------- */
- // Test to verify "EDIT ACCESS" logic
+ // Test to verify access logic
- when: "dashboard1 is made 'edit private' by its original owner"
- privateUser1Dashboard.setEditAccess(DashboardAccess.PRIVATE)
- assert privateUser1DashboardResource.update(null, privateUser1Dashboard) != null
+ when: "dashboard1 is shared, and updated from a different realm"
+ privateUser1Dashboard.setDisplayName("New displayname")
+ smartcityDashboardResource.update(null, privateUser1Dashboard)
+
+ then: "an forbidden exception is thrown for not having cross-realm access"
+ thrown ForbiddenException
- and: "dashboard1 is actually private"
- def dashboards = privateUser1DashboardResource.getAllRealmDashboards(null, MASTER_REALM)
+ when: "dashboard1 is shared, and updated by a different user"
+ alternativeUserDashboardResource.update(null, privateUser1Dashboard)
+
+ then: "updating the dashboard succeeds as it is shared across the realm"
+ def alternativeUpdatedDashboard = alternativeUserDashboardResource.get(null, MASTER_REALM, privateUser1Dashboard.id)
+ assert alternativeUpdatedDashboard.setDisplayName("New displayname 2")
+
+ /* ----------- */
+
+ when: "dashboard1 is made 'private' by its original owner"
+ privateUser1Dashboard.setAccess(DashboardAccess.PRIVATE)
+ privateUser1Dashboard = privateUser1DashboardResource.update(null, privateUser1Dashboard)
+ assert privateUser1Dashboard != null
+
+ and: "all dashboards of the original owner are retrieved"
+ dashboards = privateUser1DashboardResource.getAllRealmDashboards(null, MASTER_REALM)
+
+ then: "dashboard1 is actually private"
assert dashboards.length == 2
- assert dashboards.find((d) -> d.id == privateUser1Dashboard.id).editAccess == DashboardAccess.PRIVATE
+ assert dashboards.find((d) -> d.id == privateUser1Dashboard.id).access == DashboardAccess.PRIVATE
+
+ /* ----------- */
+
+ when: "the original owner of dashboard1 has been changed to a user without READ_INSIGHTS and WRITE_INSIGHTS role"
+ privateUser1Dashboard.setOwnerId(noAccessUser.id)
+ privateUser1Dashboard = adminUserDashboardResource.update(null, privateUser1Dashboard)
- and: "the first dashboard cannot be edited by a different user, even if its admin user"
+ and: "the user without READ_INSIGHTS and WRITE_INSIGHTS tries to retrieve their personal dashboard"
+ noAccessDashboardResource.get(null, MASTER_REALM, privateUser1Dashboard.id)
+
+ then: "a NOT_FOUND exception is thrown as no READ_INSIGHTS role is assigned"
+ thrown NotFoundException
+
+ /* ----------- */
+
+ when: "the first dashboard cannot be edited by a different user, even if its admin user"
privateUser1Dashboard.setDisplayName("another displayname")
- adminUserDashboardResource.update(null, privateUser1Dashboard)
+ privateUser1Dashboard = adminUserDashboardResource.update(null, privateUser1Dashboard)
then: "it should throw exception"
thrown NotFoundException
+ /* ----------- */
+
+ when: "the first dashboard cannot be read by a different user, even if its admin user"
+ def adminDisplaynameDashboards = adminUserDashboardResource.query(null, new DashboardQuery().names(privateUser1Dashboard.displayName))
+
+ then: "the dashboard could not be found, since it's made 'private' by its original owner"
+ assert adminDisplaynameDashboards.length == 0
+
/* ----------------------- */
- // Test to verify "DELETE" logic
+ // Test to verify private dashboards cannot be fetched by public/unauthenticated users, even if ID is specified
- when: "admin user tries to delete a dashboard he doesn't own"
- adminUserDashboardResource.delete(null, MASTER_REALM, privateUser1Dashboard.id)
+ when: "when a public user specifically fetches a private dashboard"
+ publicUserDashboardResource.get(null, MASTER_REALM, adminDashboard.id)
then: "it should throw exception"
+ thrown ForbiddenException
+
+ /* ----------------------- */
+
+ // Test to verify "DELETE" logic
+
+ when: "admin user updates his dashboard to be private"
+ adminDashboard.setAccess(DashboardAccess.PRIVATE)
+ adminUserDashboardResource.update(null, adminDashboard)
+
+ and: "a different user tries to delete a dashboard he doesn't own"
+ privateUser1DashboardResource.delete(null, MASTER_REALM, adminDashboard.id)
+
+ then: "it should throw a NOT_FOUND exception, since it isn't visible to him"
thrown NotFoundException
+ when: "admin user makes his dashboard SHARED again"
+ adminDashboard.setAccess(DashboardAccess.SHARED)
+ adminUserDashboardResource.update(null, adminDashboard)
+
+ and: "a different user tries to delete the dashboard again"
+ privateUser1DashboardResource.delete(null, MASTER_REALM, adminDashboard.id)
+
+ then: "it should succeed, and the dashboard cannot be retrieved by the admin again"
+ assert adminUserDashboardResource.getAllRealmDashboards(null, MASTER_REALM).find { it.id === adminDashboard.id } == null
+
/* ----------------------- */
// Test to verify public/unauthenticated user cannot fetch dashboards by default
@@ -130,25 +263,23 @@ class DashboardTest extends Specification implements ManagerContainerTrait {
// Test to verify public dashboards CAN be fetched by public/unauthenticated users
- when: "dashboard1 is made 'view public' by its original owner"
- privateUser1Dashboard.setViewAccess(DashboardAccess.PUBLIC)
+ when: "dashboard1 is made 'public' by its original owner"
+ privateUser1Dashboard.setAccess(DashboardAccess.PUBLIC)
+ privateUser1Dashboard.setDisplayName("Public dashboard")
assert privateUser1DashboardResource.update(null, privateUser1Dashboard) != null
then: "when a public user fetches all dashboards, it should only return that dashboard"
def publicDashboards2 = publicUserDashboardResource.getAllRealmDashboards(null, MASTER_REALM)
assert publicDashboards2.length == 1
- assert publicDashboards2[0].viewAccess == DashboardAccess.PUBLIC
- assert publicDashboards2[0].editAccess == DashboardAccess.PRIVATE
-
- /* ----------------------- */
+ assert publicDashboards2[0].access == DashboardAccess.PUBLIC
+ assert publicDashboards2[0].displayName == "Public dashboard"
- // Test to verify private dashboards cannot be fetched by public/unauthenticated users, even if ID is specified
-
- when: "when a public user specifically fetches a private dashboard"
- publicUserDashboardResource.get(null, MASTER_REALM, adminDashboard.id)
-
- then: "it should throw exception"
- thrown ForbiddenException
+ and: "all users should be able to fetch the public dashboard"
+ assert adminUserDashboardResource.get(null, MASTER_REALM, publicDashboards2[0].id).displayName == publicDashboards2[0].displayName
+ assert privateUser1DashboardResource.get(null, MASTER_REALM, publicDashboards2[0].id).displayName == publicDashboards2[0].displayName
+ assert noAccessDashboardResource.get(null, MASTER_REALM, publicDashboards2[0].id).displayName == publicDashboards2[0].displayName
+ assert readonlyDashboardResource.get(null, MASTER_REALM, publicDashboards2[0].id).displayName == publicDashboards2[0].displayName
+ assert alternativeUserDashboardResource.get(null, MASTER_REALM, publicDashboards2[0].id).displayName == publicDashboards2[0].displayName
/* ------------------------- */
@@ -175,6 +306,8 @@ class DashboardTest extends Specification implements ManagerContainerTrait {
.setRealm(keycloakTestSetup.realmBuilding.name)
.setDisplayName("Dashboard with assets")
.setTemplate(template)
+ .setAccess(DashboardAccess.SHARED)
+ .setOwnerId(adminUser.id)
def newDashboard = adminUserDashboardResource.create(null, buildingDashboard)
diff --git a/ui/app/insights/src/components/dashboard-menu.ts b/ui/app/insights/src/components/dashboard-menu.ts
index b01d9e270..0f22b3018 100644
--- a/ui/app/insights/src/components/dashboard-menu.ts
+++ b/ui/app/insights/src/components/dashboard-menu.ts
@@ -208,22 +208,11 @@ function getDashboardListTemplate(dashboards: Dashboard[], selectedId: string, o
${when(menuItems[0] == undefined, () => html`
<span style="width: 100%; text-align: center;">${i18next.t('noDashboardFound')}</span>
`, () => html`
- ${when(menuItems[0].length > 0, () => html`
- <div>
- <span style="margin-left: 16px;">${i18next.t('dashboard.myDashboards')}</span>
- <or-mwc-list .listItems="${menuItems[0]}" .values="${selectedId}"
- @or-mwc-list-changed="${(ev: CustomEvent) => onSelect(ev.detail[0].value)}"
- ></or-mwc-list>
- </div>
- `)}
- ${when(menuItems[1].length > 0, () => html`
- <div>
- <span style="margin-left: 16px;">${i18next.t('dashboard.createdByOthers')}</span>
- <or-mwc-list .listItems="${menuItems[1]}" .values="${selectedId}"
- @or-mwc-list-changed="${(ev: CustomEvent) => onSelect(ev.detail[0].value)}"
- ></or-mwc-list>
- </div>
- `)}
+ <div>
+ <or-mwc-list .listItems="${menuItems}" .values="${selectedId}"
+ @or-mwc-list-changed="${(ev: CustomEvent) => onSelect(ev.detail[0].value)}"
+ ></or-mwc-list>
+ </div>
`)}
</div>
</div>
@@ -232,20 +221,12 @@ function getDashboardListTemplate(dashboards: Dashboard[], selectedId: string, o
`
}
-function getDashboardMenuItems(dashboards: Dashboard[], userId?: string): ListItem[][] {
- const dashboardItems: ListItem[][] = [];
- if(dashboards?.length > 0) {
- const myDashboards: Dashboard[] = [];
- const otherDashboards: Dashboard[] = [];
- dashboards?.forEach((d) => {
- (userId != null && d.ownerId == userId) ? myDashboards.push(d) : otherDashboards.push(d);
- });
- [myDashboards, otherDashboards].forEach((array, index) => {
- dashboardItems[index] = [];
- array.sort((a, b) => a.displayName ? a.displayName.localeCompare(b.displayName!) : 0).forEach((d) => {
- dashboardItems[index].push({ icon: "view-dashboard", text: d.displayName, value: d.id })
- })
- })
- }
- return dashboardItems;
+function getDashboardMenuItems(dashboards: Dashboard[], userId?: string): ListItem[] {
+ return dashboards
+ .sort((a, b) => a.displayName ? a.displayName.localeCompare(b.displayName!) : 0)
+ .map(d => ({
+ icon: "view-dashboard",
+ text: d.displayName,
+ value: d.id
+ }));
}
diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json
index fd98d7166..f6e37cdb6 100644
--- a/ui/app/shared/locales/en/or.json
+++ b/ui/app/shared/locales/en/or.json
@@ -743,8 +743,7 @@
"saveSuccessful": "Saved dashboard successfully!",
"initialName": "New Dashboard",
"openInNewTab": "Open in new tab",
- "whoCanView": "Who can <b>view</b> the dashboard?",
- "whoCanEdit": "Who can <b>edit</b> the dashboard?",
+ "whoCanView": "Who can access the dashboard?",
"numberOfColumns": "Number of columns",
"numberOfRows": "Number of rows",
"maxScreenWidth": "Max screen width",
@@ -769,8 +768,6 @@
"showHelperText": "Show time of last update",
"tableSettings": "Table settings",
"deleteWidget": "Delete widget",
- "myDashboards": "My dashboards",
- "createdByOthers": "Created by others",
"showUnits": "Show units",
"showLabels": "Show labels",
"zoom": "Zoom",
diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json
index c9c3be1a9..74ca7406e 100644
--- a/ui/app/shared/locales/nl/or.json
+++ b/ui/app/shared/locales/nl/or.json
@@ -742,8 +742,7 @@
"saveSuccessful": "Dashboard succesvol opgeslagen!",
"initialName": "Nieuw dashboard",
"openInNewTab": "Openen in een nieuw tabblad",
- "whoCanView": "Wie kan het dashboard <b>bekijken</b>?",
- "whoCanEdit": "Wie kan het dashboard <b>bewerken</b>?",
+ "whoCanView": "Wie heeft er toegang tot het dashboard?",
"numberOfColumns": "Aantal kolommen",
"numberOfRows": "Aantal rijen",
"maxScreenWidth": "Max schermbreedte",
@@ -768,8 +767,6 @@
"showHelperText": "Toon moment van bijwerken",
"tableSettings": "Tabeleigenschappen",
"deleteWidget": "Verwijder widget",
- "myDashboards": "Mijn dashboards",
- "createdByOthers": "Gemaakt door anderen",
"showUnits": "Toon eenheden",
"showLabels": "Toon labels",
"zoom": "Zoom",
diff --git a/ui/app/shared/locales/ro/or.json b/ui/app/shared/locales/ro/or.json
index 807fcc61b..54e33e861 100644
--- a/ui/app/shared/locales/ro/or.json
+++ b/ui/app/shared/locales/ro/or.json
@@ -649,8 +649,6 @@
"showGeoJson": "Arată stratul GeoJSON",
"showValueAs": "Arată valoarea ca",
"deleteWidget": "Șterge widget",
- "myDashboards": "Panourile mele",
- "createdByOthers": "Create de altii",
"showUnits": "Arată unitățile",
"showLabels": "Arată etichetele",
"zoom": "Magnificare",
diff --git a/ui/app/shared/locales/uk/or.json b/ui/app/shared/locales/uk/or.json
index 87b889507..b66ba21ab 100644
--- a/ui/app/shared/locales/uk/or.json
+++ b/ui/app/shared/locales/uk/or.json
@@ -680,8 +680,6 @@
"showHelperText": "Показати час останнього оновлення",
"tableSettings": "Налаштування таблиці",
"deleteWidget": "Видалити віджет",
- "myDashboards": "Мої панелі",
- "createdByOthers": "Створені іншими",
"showUnits": "Показати одиниці",
"showLabels": "Показати мітки",
"zoom": "Масштабування",
diff --git a/ui/component/or-dashboard-builder/src/index.ts b/ui/component/or-dashboard-builder/src/index.ts
index 4e83bc981..88663df49 100644
--- a/ui/component/or-dashboard-builder/src/index.ts
+++ b/ui/component/or-dashboard-builder/src/index.ts
@@ -544,13 +544,13 @@ export class OrDashboardBuilder extends LitElement {
}
protected _isReadonly(): boolean {
- return this.readonly || !manager.hasRole(ClientRole.WRITE_INSIGHTS);
+ return this.readonly;
}
protected _hasEditAccess(): boolean {
- return this.userId != null && (this.selectedDashboard?.editAccess == DashboardAccess.PRIVATE ? this.selectedDashboard?.ownerId == this.userId : true)
+ return manager.hasRole(ClientRole.WRITE_INSIGHTS);
}
protected _hasViewAccess(): boolean {
- return this.userId != null && (this.selectedDashboard?.viewAccess == DashboardAccess.PRIVATE ? this.selectedDashboard?.ownerId == this.userId : true)
+ return manager.hasRole(ClientRole.READ_INSIGHTS) && this.userId != null && (this.selectedDashboard?.access == DashboardAccess.PRIVATE ? this.selectedDashboard?.ownerId == this.userId : true)
}
/* ----------------- */
@@ -597,8 +597,8 @@ export class OrDashboardBuilder extends LitElement {
<div id="header-title">
<or-icon icon="view-dashboard"></or-icon>
${this.selectedDashboard != null ? html`
- <or-mwc-input .type="${InputType.TEXT}" min="1" max="1023" comfortable required outlined .label="${i18next.t('name') + '*\xa0'}"
- ?readonly="${this._isReadonly()}" .value="${this.selectedDashboard.displayName}"
+ <or-mwc-input .type="${InputType.TEXT}" min="1" max="1023" comfortable required outlined .label="${i18next.t('name')}"
+ ?readonly="${this._isReadonly() || !this._hasEditAccess()}" .value="${this.selectedDashboard.displayName}"
.disabled="${this.isLoading}" style="width: 300px;"
@or-mwc-input-changed="${(event: OrInputChangedEvent) => { this.changeDashboardName(event.detail.value); }}"
></or-mwc-input>
@@ -668,7 +668,7 @@ export class OrDashboardBuilder extends LitElement {
<or-dashboard-preview class="editor" style="background: transparent;"
.realm="${this.realm}" .template="${this.currentTemplate}"
.selectedWidget="${this.selectedDashboard?.template?.widgets?.find(w => w.id == this.selectedWidgetId)}" .editMode="${this.editMode}"
- .fullscreen="${this.fullscreen}" .readonly="${this._isReadonly()}"
+ .fullscreen="${this.fullscreen}" .readonly="${this._isReadonly() || !this._hasEditAccess()}"
@selected="${(event: CustomEvent) => { this.selectWidget(event.detail); }}"
@deselected="${() => { this.deselectWidget(); }}"
@created="${(event: CustomEvent) => { this.onWidgetCreation(event.detail); }}"
@@ -721,7 +721,7 @@ export class OrDashboardBuilder extends LitElement {
<div style="position: relative;">
<or-dashboard-browser id="browser" style="position: absolute; ${this.sidebarMenuIndex != 0 ? css`display: none` : null}"></or-dashboard-browser>
<or-dashboard-boardsettings style="position: absolute; ${this.sidebarMenuIndex != 1 ? css`display: none` : null}"
- .dashboard="${this.selectedDashboard}" .showPerms="${this.selectedDashboard?.ownerId == this.userId}"
+ .dashboard="${this.selectedDashboard}" showPerms
@update="${(event: CustomEvent) => {
this.currentTemplate = Object.assign({}, this.selectedDashboard?.template);
if(event.detail.force) { this.deselectWidget(); this.dashboardPreview?.refreshPreview(); }}}"
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts b/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts
index 8c63bd889..ddb9e1df2 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-boardsettings.ts
@@ -18,11 +18,11 @@ const boardSettingsStyling = css`
@customElement("or-dashboard-boardsettings")
export class OrDashboardBoardsettings extends LitElement {
- @property()
- protected readonly dashboard!: Dashboard;
+ @property({ type: Object })
+ public readonly dashboard!: Dashboard;
- @property()
- protected readonly showPerms?: boolean;
+ @property({ type: Boolean })
+ public readonly showPerms?: boolean;
/* ------------------------- */
@@ -36,17 +36,8 @@ export class OrDashboardBoardsettings extends LitElement {
/* -------------------------------- */
- private setViewAccess(access: DashboardAccess) {
- this.dashboard.viewAccess = access;
- if (access === DashboardAccess.PRIVATE) {
- this.dashboard.editAccess = DashboardAccess.PRIVATE; // if viewAccess changed to PRIVATE, make editAccess private as well.
- }
- this.requestUpdate();
- this.forceParentUpdate(false);
- }
-
- private setEditAccess(access: DashboardAccess) {
- this.dashboard.editAccess = access;
+ private setAccess(access: DashboardAccess) {
+ this.dashboard.access = access;
this.requestUpdate();
this.forceParentUpdate(false);
}
@@ -66,8 +57,7 @@ export class OrDashboardBoardsettings extends LitElement {
protected render() {
if (this.dashboard.template?.screenPresets != null) {
const screenPresets = sortScreenPresets(this.dashboard.template.screenPresets, true);
- const viewAccessOptions = [DashboardAccess.PRIVATE, DashboardAccess.SHARED, DashboardAccess.PUBLIC].map((access) => ({key: access, value: dashboardAccessToString(access)}));
- const editAccessOptions = [DashboardAccess.PRIVATE, DashboardAccess.SHARED].map((access) => ({key: access, value: dashboardAccessToString(access)}));
+ const accessOptions = [DashboardAccess.PRIVATE, DashboardAccess.SHARED, DashboardAccess.PUBLIC].map((access) => ({key: access, value: dashboardAccessToString(access)}));
const refreshIntervalOptions = [DashboardRefreshInterval.OFF, DashboardRefreshInterval.ONE_MIN, DashboardRefreshInterval.FIVE_MIN, DashboardRefreshInterval.QUARTER, DashboardRefreshInterval.ONE_HOUR].map(interval => ({key: interval, value: `dashboard.interval.${interval.toLowerCase()}`}))
const scalingPresets: { key: DashboardScalingPreset, value: string }[] = [];
[DashboardScalingPreset.KEEP_LAYOUT, DashboardScalingPreset.WRAP_TO_SINGLE_COLUMN, /*DashboardScalingPreset.REDIRECT,*/ DashboardScalingPreset.BLOCK_DEVICE].forEach((preset: DashboardScalingPreset) => {
@@ -79,31 +69,16 @@ export class OrDashboardBoardsettings extends LitElement {
${when(this.showPerms, () => html`
<settings-panel displayName="permissions" expanded="${true}">
<div>
- <div style="margin-bottom: 24px;">
- <div class="label">
- ${html`<span>${unsafeHTML(i18next.t('dashboard.whoCanView').toString())}</span>`}
- </div>
- <or-mwc-input class="permissionInput" comfortable type="${InputType.SELECT}" style="width: 100%;"
- .options="${viewAccessOptions.map((access) => access.value)}"
- .value="${dashboardAccessToString(this.dashboard.viewAccess!)}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- this.setViewAccess(viewAccessOptions.find((access) => access.value == event.detail.value)?.key!);
- }}"
- ></or-mwc-input>
- </div>
- <div style="margin-bottom: 24px;">
- <div class="label">
- ${html`<span>${unsafeHTML(i18next.t('dashboard.whoCanEdit').toString())}</span>`}
- </div>
- <or-mwc-input class="permissionInput" comfortable type="${InputType.SELECT}" style="width: 100%;"
- .disabled="${(this.dashboard.viewAccess == DashboardAccess.PRIVATE)}"
- .options="${editAccessOptions.map((access) => access.value)}"
- .value="${dashboardAccessToString(this.dashboard.editAccess!)}"
- @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
- this.setEditAccess(editAccessOptions.find((access) => access.value == event.detail.value)?.key!);
- }}"
- ></or-mwc-input>
+ <div class="label">
+ ${html`<span>${unsafeHTML(i18next.t('dashboard.whoCanView').toString())}</span>`}
</div>
+ <or-mwc-input class="permissionInput" comfortable type="${InputType.SELECT}" style="width: 100%;"
+ .options="${accessOptions.map((access) => access.value)}"
+ .value="${dashboardAccessToString(this.dashboard.access!)}"
+ @or-mwc-input-changed="${(event: OrInputChangedEvent) => {
+ this.setAccess(accessOptions.find((access) => access.value == event.detail.value)?.key!);
+ }}"
+ ></or-mwc-input>
</div>
</settings-panel>
`)}
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts b/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts
index 1e25b8ff1..195db1371 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-preview.ts
@@ -647,10 +647,12 @@ export class OrDashboardPreview extends LitElement {
}
protected resizeObserverCallback: ResizeObserverCallback = (entries: ResizeObserverEntry[]) => {
- if((this.previousObserverEntry?.contentRect.width + "px") !== (entries[0].contentRect.width + "px")) {
- this._onGridResize();
- }
- this.previousObserverEntry = entries[0];
+ requestAnimationFrame(() => {
+ if((this.previousObserverEntry?.contentRect.width + "px") !== (entries[0].contentRect.width + "px")) {
+ this._onGridResize();
+ }
+ this.previousObserverEntry = entries[0];
+ });
}
protected _onGridResize() {
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts b/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts
index f15cb1d56..a16156936 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-tree.ts
@@ -213,30 +213,8 @@ export class OrDashboardTree extends LitElement {
// Element render method
// TODO: Move dashboard filtering to separate method.
protected render() {
- const dashboardItems: ListItem[][] = [];
- if (this.dashboards && this.dashboards.length > 0) {
- if (this.userId) {
- const myDashboards: Dashboard[] = [];
- const otherDashboards: Dashboard[] = [];
- this.dashboards?.forEach(d => {
- (d.ownerId === this.userId) ? myDashboards.push(d) : otherDashboards.push(d);
- });
- if (myDashboards.length > 0) {
- const items: ListItem[] = [];
- myDashboards.sort((a, b) => a.displayName ? a.displayName.localeCompare(b.displayName!) : 0).forEach(d => {
- items.push({icon: 'view-dashboard', text: d.displayName, value: d.id});
- });
- dashboardItems.push(items);
- }
- if (otherDashboards.length > 0) {
- const items: ListItem[] = [];
- otherDashboards.sort((a, b) => a.displayName ? a.displayName.localeCompare(b.displayName!) : 0).forEach(d => {
- items.push({icon: 'view-dashboard', text: d.displayName, value: d.id});
- });
- dashboardItems.push(items);
- }
- }
- }
+ const dashboardItems = this.dashboards?.sort((a, b) => a.displayName ? a.displayName.localeCompare(b.displayName!) : 0)
+ .map(d => ({ icon: 'view-dashboard', text: d.displayName, value: d.id} as ListItem)) || []
return html`
<div id="menu-header">
<div id="title-container">
@@ -280,31 +258,16 @@ export class OrDashboardTree extends LitElement {
<!-- List of dashboards -->
<div id="content">
- <div style="padding-top: 8px;">
- ${dashboardItems.map((items, index) => {
- return (items != null && items.length > 0) ? html`
- <div style="padding: 8px 0;">
- <span style="font-weight: 500; padding-left: 14px; color: #000000;">
- <or-translate value="${(index === 0 ? 'dashboard.myDashboards' : 'dashboard.createdByOthers')}"></or-translate>
- </span>
- <div id="list-container" style="overflow: hidden;">
- <ol id="list">
- ${items.map((listItem: ListItem) => {
- return html`
- <li ?data-selected="${listItem.value === this.selected?.id}" @click="${(_evt: MouseEvent) => {
- this.onDashboardClick(listItem.value);
- }}">
- <div class="node-container">
- <span class="node-name">${listItem.text} </span>
- </div>
- </li>
- `;
- })}
- </ol>
+ <div id="list-container" style="overflow: hidden;">
+ <ol id="list">
+ ${dashboardItems.map((listItem: ListItem) => html`
+ <li ?data-selected="${listItem.value === this.selected?.id}" @click="${(_evt: MouseEvent) => this.onDashboardClick(listItem.value)}">
+ <div class="node-container">
+ <span class="node-name">${listItem.text} </span>
</div>
- </div>
- ` : undefined;
- })}
+ </li>
+ `)}
+ </ol>
</div>
</div>
`;
diff --git a/ui/component/or-dashboard-builder/src/util/settings-panel.ts b/ui/component/or-dashboard-builder/src/util/settings-panel.ts
index 1f61e5271..f21a8a7c5 100644
--- a/ui/component/or-dashboard-builder/src/util/settings-panel.ts
+++ b/ui/component/or-dashboard-builder/src/util/settings-panel.ts
@@ -11,7 +11,6 @@ const styling = css`
}
#panel-wrapper {
- border-top: 1px solid #E0E0E0;
border-bottom: 1px solid #E0E0E0;
}