Skip to content

armgit / core

Public Imported from GitHub
0

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

User query enhancements and JSON rule updates and fixes (#1032)

Rich Turnercb47b0737df3
diff --git a/build.gradle b/build.gradle
index eeb41e13f..24787d7ff 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,3 +1,5 @@
+import java.nio.file.Paths
+
import static org.apache.tools.ant.taskdefs.condition.Os.FAMILY_WINDOWS
import static org.apache.tools.ant.taskdefs.condition.Os.isFamily
@@ -35,6 +37,8 @@ task checkFilesGitIgnoredNew(type: Exec) {
commandLine args
}
+// openremote .git dir doesn't exist when used as a submodule
+checkFilesGitIgnoredNew.enabled = Paths.get(projectDir.path, ".git").toFile().exists()
task clean() {
doLast {
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index b060e2b87..f21be9a35 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -1707,7 +1707,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
isFirst = false;
final int pos = binders.size() + 1;
sb.append(pred.caseSensitive ? "A.NAME " : "upper(A.NAME)");
- sb.append(buildMatchFilter(pred, pos));
+ sb.append(StringPredicate.toSQLParameter(pred, pos, false));
binders.add((em, st) -> st.setParameter(pos, pred.prepareValue()));
}
sb.append(")");
@@ -1901,7 +1901,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
);
final int pos = binders.size() + 1;
- attributeBuilder.append(buildMatchFilter(nameValuePredicate.name, pos));
+ attributeBuilder.append(StringPredicate.toSQLParameter(nameValuePredicate.name, pos, false));
binders.add((em, st) -> st.setParameter(pos, nameValuePredicate.name.prepareValue()));
}
@@ -1948,7 +1948,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
attributeBuilder.append(")");
}
final int pos = binders.size() + 1;
- attributeBuilder.append(buildMatchFilter(stringPredicate, pos));
+ attributeBuilder.append(StringPredicate.toSQLParameter(stringPredicate, pos, false));
binders.add((em, st) -> st.setParameter(pos, stringPredicate.prepareValue()));
} else if (nameValuePredicate.value instanceof BooleanPredicate) {
BooleanPredicate booleanPredicate = (BooleanPredicate) nameValuePredicate.value;
@@ -2152,21 +2152,4 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
throw new IllegalArgumentException("Unsupported operator: " + operator);
}
-
- public static String buildMatchFilter(StringPredicate predicate, int pos) {
- switch (predicate.match) {
- case BEGIN:
- case END:
- case CONTAINS:
- if (predicate.negate) {
- return " not like ?" + pos + " ";
- }
- return " like ?" + pos + " ";
- default:
- if (predicate.negate) {
- return " <> ?" + pos + " ";
- }
- return " = ?" + pos + " ";
- }
- }
}
diff --git a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
index 5a5c9ffd4..83cde983d 100644
--- a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
@@ -33,7 +33,8 @@ import org.openremote.model.notification.Notification;
import org.openremote.model.notification.NotificationSendResult;
import org.openremote.model.query.UserQuery;
import org.openremote.model.query.filter.RealmPredicate;
-import org.openremote.model.query.filter.UserAssetPredicate;
+import org.openremote.model.query.filter.StringPredicate;
+import org.openremote.model.security.User;
import org.openremote.model.util.TextUtil;
import java.io.UnsupportedEncodingException;
@@ -43,7 +44,7 @@ import java.util.logging.Logger;
import java.util.stream.Collectors;
import static org.openremote.container.util.MapAccess.*;
-import static org.openremote.manager.security.ManagerKeycloakIdentityProvider.KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED;
+import static org.openremote.model.security.User.EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE;
import static org.openremote.model.Constants.*;
public class EmailNotificationHandler implements NotificationHandler {
@@ -192,17 +193,22 @@ public class EmailNotificationHandler implements NotificationHandler {
).ifPresent(mappedTargets::add);
}
- userQuery = new UserQuery().asset(new UserAssetPredicate(targetId));
+ userQuery = new UserQuery().assets(targetId);
break;
}
// Filter users that don't have disabled email notifications attribute
if (userQuery != null) {
+ // Exclude service accounts, system accounts and accounts with disabled email notifications
+ userQuery.serviceUsers(false).attributes(
+ new UserQuery.AttributeValuePredicate(true, new StringPredicate(User.SYSTEM_ACCOUNT_ATTRIBUTE)),
+ new UserQuery.AttributeValuePredicate(true, new StringPredicate(EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE), new StringPredicate("true"))
+ );
List<Notification.Target> userTargets = Arrays.stream(managerIdentityService
.getIdentityProvider()
.queryUsers(userQuery))
- .filter(user -> !Boolean.parseBoolean(user.getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0)))
- .filter(user -> !TextUtil.isNullOrEmpty(user.getEmail()))
+ // Exclude system accounts and accounts without emails
+ .filter(user -> !user.isSystemAccount() && !TextUtil.isNullOrEmpty(user.getEmail()))
.map(user -> {
Notification.Target emailTarget = new Notification.Target(Notification.TargetType.USER, user.getId());
emailTarget.setData(new EmailNotificationMessage.Recipient(user.getFullName(), user.getEmail()));
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
index 2a2286c72..17806bb1c 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
@@ -39,6 +39,8 @@ import org.openremote.model.notification.NotificationSendResult;
import org.openremote.model.notification.RepeatFrequency;
import org.openremote.model.notification.SentNotification;
import org.openremote.model.query.UserQuery;
+import org.openremote.model.query.filter.StringPredicate;
+import org.openremote.model.security.User;
import org.openremote.model.util.TextUtil;
import org.openremote.model.util.TimeUtil;
@@ -522,18 +524,20 @@ public class NotificationService extends RouteBuilder implements ContainerServic
}
// Requester must be in the same realm as all target users
- boolean realmMatch = false;
+ boolean realmMatch;
if (target.getType() == Notification.TargetType.USER) {
- realmMatch = Arrays.stream(identityService.getIdentityProvider().queryUsers(new UserQuery().ids(target.getId())))
- .allMatch(user -> realm.equals(user.getRealm()));
+ realmMatch = Arrays.stream(identityService.getIdentityProvider().queryUsers(
+ // Exclude service accounts and system accounts
+ new UserQuery().ids(target.getId()).serviceUsers(false).attributes(new UserQuery.AttributeValuePredicate(true, new StringPredicate(User.SYSTEM_ACCOUNT_ATTRIBUTE)))
+ )).allMatch(user -> realm.equals(user.getRealm()));
} else {
- // Can only send to the same realm as the requestor realm
+ // Can only send to the same realm as the requester realm
realmMatch = realm.equals(target.getId());
}
if (!realmMatch) {
- throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be in the same realm as the requestor");
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be in the same realm as the requester");
}
break;
diff --git a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
index 01a032f07..5e11dc942 100644
--- a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
@@ -47,6 +47,7 @@ import org.openremote.model.query.UserQuery;
import org.openremote.model.query.filter.AttributePredicate;
import org.openremote.model.query.filter.NameValuePredicate;
import org.openremote.model.query.filter.RealmPredicate;
+import org.openremote.model.query.filter.StringPredicate;
import org.openremote.model.security.User;
import org.openremote.model.util.TextUtil;
import org.openremote.model.util.ValueUtil;
@@ -62,8 +63,9 @@ import java.util.stream.StreamSupport;
import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.manager.gateway.GatewayService.isNotForGateway;
-import static org.openremote.manager.security.ManagerKeycloakIdentityProvider.KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED;
import static org.openremote.model.notification.PushNotificationMessage.TargetType.*;
+import static org.openremote.model.security.User.EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE;
+import static org.openremote.model.security.User.PUSH_NOTIFICATIONS_DISABLED_ATTRIBUTE;
@SuppressWarnings("deprecation")
public class PushNotificationHandler extends RouteBuilder implements NotificationHandler {
@@ -250,33 +252,32 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
if (!consoleAssetIds.isEmpty()) {
// Special handling if target type is user (don't need to find all linked users)
if (targetType == Notification.TargetType.USER) {
- User[] matchedUsers = managerIdentityService.getIdentityProvider().queryUsers(new UserQuery().ids(targetId));
- if (matchedUsers.length != 1) {
+ if (Arrays.stream(managerIdentityService.getIdentityProvider().queryUsers(
+ // Exclude service accounts, system accounts and accounts with disabled push notifications
+ new UserQuery().ids(targetId).serviceUsers(false).attributes(
+ new UserQuery.AttributeValuePredicate(true, new StringPredicate(User.SYSTEM_ACCOUNT_ATTRIBUTE)),
+ new UserQuery.AttributeValuePredicate(true, new StringPredicate(PUSH_NOTIFICATIONS_DISABLED_ATTRIBUTE), new StringPredicate("true"))
+ )))
+ .allMatch(User::isSystemAccount)) {
consoleAssetIds = Collections.emptyList();
- } else {
- boolean disabled = Boolean.parseBoolean(matchedUsers[0].getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0));
- if (disabled) {
- consoleAssetIds = Collections.emptyList();
- }
}
} else {
- // Any consoles linked to users; the user should not have push notification disabled attribute
- Map<String, List<String>> consoleUserIdsMap = assetStorageService.findUserAssetLinks(null, null, consoleAssetIds)
- .stream()
- .map(UserAssetLink::getId)
- .collect(Collectors.groupingBy(UserAssetLink.Id::getAssetId, Collectors.mapping(UserAssetLink.Id::getUserId, Collectors.toList())));
consoleAssetIds = consoleAssetIds.stream()
.filter(consoleId -> {
- if (!consoleUserIdsMap.containsKey(consoleId)) {
- return true;
- }
+ // Check there are no regular users with disabled push notifications linked to this console
+ // TODO: This should be handled by the console provider on the console itself
long count = Arrays.stream(managerIdentityService.getIdentityProvider().queryUsers(
- new UserQuery().ids(consoleUserIdsMap.get(consoleId).toArray(new String[0]))))
- .filter(user -> !Boolean.parseBoolean(user.getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0)))
- .count();
- return count > 0;
+ // Exclude service accounts, system accounts and accounts with disabled email notifications
+ new UserQuery()
+ .assets(consoleId)
+ .serviceUsers(false).attributes(
+ new UserQuery.AttributeValuePredicate(true, new StringPredicate(User.SYSTEM_ACCOUNT_ATTRIBUTE)),
+ new UserQuery.AttributeValuePredicate(false, new StringPredicate(PUSH_NOTIFICATIONS_DISABLED_ATTRIBUTE), new StringPredicate("true"))
+ )
+ )).count();
+ return count == 0;
}).collect(Collectors.toList());
}
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
index 32748a0aa..a24449d80 100644
--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
@@ -22,9 +22,10 @@ package org.openremote.manager.rules;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
-import org.openremote.model.PersistenceEvent;
+import jakarta.ws.rs.core.MediaType;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.asset.AssetStorageService;
+import org.openremote.model.PersistenceEvent;
import org.openremote.model.asset.Asset;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.geo.GeoJSONPoint;
@@ -35,7 +36,6 @@ import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.LogicGroup;
import org.openremote.model.query.UserQuery;
import org.openremote.model.query.filter.AttributePredicate;
-import org.openremote.model.query.filter.UserAssetPredicate;
import org.openremote.model.rules.*;
import org.openremote.model.rules.json.*;
import org.openremote.model.util.EnumUtil;
@@ -47,11 +47,11 @@ import org.openremote.model.webhook.Webhook;
import org.quartz.CronExpression;
import org.shredzone.commons.suncalc.SunTimes;
-import jakarta.ws.rs.core.MediaType;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
@@ -621,7 +621,7 @@ public class JsonRulesBuilder extends RulesBuilder {
RuleState ruleState = new RuleState(rule);
ruleStateMap.put(rule.name, ruleState);
- addRuleConditionStates(rule.when, rule.otherwise != null, 0, ruleState.conditionStateMap);
+ addRuleConditionStates(rule.when, rule.otherwise != null, new AtomicInteger(0), ruleState.conditionStateMap);
Condition condition = buildLhsCondition(rule, ruleState);
Action action = buildRhsAction(rule, ruleState);
@@ -639,16 +639,16 @@ public class JsonRulesBuilder extends RulesBuilder {
return this;
}
- protected void addRuleConditionStates(LogicGroup<RuleCondition> ruleConditionGroup, boolean trackUnmatched, int index, Map<String, RuleConditionState> triggerStateMap) throws Exception {
+ protected void addRuleConditionStates(LogicGroup<RuleCondition> ruleConditionGroup, boolean trackUnmatched, AtomicInteger index, Map<String, RuleConditionState> triggerStateMap) throws Exception {
if (ruleConditionGroup != null) {
if (ruleConditionGroup.getItems().size() > 0) {
for (RuleCondition ruleCondition : ruleConditionGroup.getItems()) {
if (TextUtil.isNullOrEmpty(ruleCondition.tag)) {
- ruleCondition.tag = Integer.toString(index);
+ ruleCondition.tag = index.toString();
}
triggerStateMap.put(ruleCondition.tag, new RuleConditionState(ruleCondition, trackUnmatched, timerService));
- index++;
+ index.incrementAndGet();
}
}
if (ruleConditionGroup.groups != null && ruleConditionGroup.groups.size() > 0) {
@@ -1124,9 +1124,17 @@ public class JsonRulesBuilder extends RulesBuilder {
.collect(Collectors.toList());
}
- // Find linked users
- return compareAssetIds.stream().flatMap(assetId ->
- usersFacade.getResults(new UserQuery().asset(new UserAssetPredicate(assetId)))).collect(Collectors.toList());
+ // Find linked users - apply any user query if it is present or create a new one
+ UserQuery userQuery = target.users != null ? target.users : new UserQuery();
+ if (userQuery.assets == null) {
+ userQuery.assets = compareAssetIds.toArray(String[]::new);
+ } else {
+ List<String> assetIds = new ArrayList<>(Arrays.asList(userQuery.assets));
+ assetIds.addAll(compareAssetIds);
+ userQuery.assets = assetIds.toArray(String[]::new);
+ }
+
+ return usersFacade.getResults(userQuery).collect(Collectors.toList());
}
if (target.assets != null) {
diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java
index cec3b64ff..0c024a699 100644
--- a/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java
+++ b/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java
@@ -26,8 +26,11 @@ import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.query.UserQuery;
import org.openremote.model.query.filter.PathPredicate;
import org.openremote.model.query.filter.RealmPredicate;
-import org.openremote.model.query.filter.UserAssetPredicate;
-import org.openremote.model.rules.*;
+import org.openremote.model.query.filter.StringPredicate;
+import org.openremote.model.rules.AssetRuleset;
+import org.openremote.model.rules.RealmRuleset;
+import org.openremote.model.rules.Ruleset;
+import org.openremote.model.rules.Users;
import org.openremote.model.security.User;
import java.util.ArrayList;
@@ -65,28 +68,20 @@ public class UsersFacade<T extends Ruleset> extends Users {
userQuery.realmPredicate = null;
String assetId = rulesEngineId.getAssetId().orElseThrow(() -> new IllegalArgumentException("Asset ID missing: " + rulesEngineId));
- // Asset<?> must be this engines asset or a child
- if (userQuery.assetPredicate != null) {
- if (assetId.equals(userQuery.assetPredicate.id)) {
- userQuery.pathPredicate = null;
- } else {
- userQuery.pathPredicate = new PathPredicate(rulesEngineId.getAssetId().orElseThrow(IllegalArgumentException::new));
- }
- } else if (userQuery.pathPredicate != null) {
- // Path must contain this engines asset ID
- List<String> path = new ArrayList<>(Arrays.asList(userQuery.pathPredicate.path));
- if (!path.contains(assetId)) {
- path.add(assetId);
- userQuery.pathPredicate.path = path.toArray(new String[userQuery.pathPredicate.path.length + 1]);
- }
+ if (userQuery.pathPredicate == null || userQuery.pathPredicate.path == null) {
+ userQuery.pathPredicate = new PathPredicate(assetId);
} else {
- // Force scope to this asset
- userQuery.assetPredicate = new UserAssetPredicate(assetId);
+ List<String> path = new ArrayList<>(Arrays.asList(userQuery.pathPredicate.path));
+ path.add(assetId);
+ userQuery.pathPredicate.path = path.toArray(new String[0]);
}
}
// Prevent system users being retrieved
- userQuery.select(new UserQuery.Select().excludeSystemUsers(true));
+ userQuery.attributes(new UserQuery.AttributeValuePredicate(true, new StringPredicate(User.SYSTEM_ACCOUNT_ATTRIBUTE), null));
+
+ // Prevent service users being retrieved
+ userQuery.serviceUsers(false);
return Arrays.stream(identityService.getIdentityProvider().queryUsers(userQuery))
.map(User::getId);
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java
index 61b448122..430274fa7 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java
@@ -161,14 +161,6 @@ public class ManagerBasicIdentityProvider extends BasicIdentityProvider implemen
.map(role -> new Role(UUID.randomUUID().toString(), role, false, true, null))
.toArray(Role[]::new);
}
- public void updateUserAttributes(String realm, String userId, Map<String, List<String>> attributes) {
- throw new UnsupportedOperationException("This provider does not support attributes");
- }
-
- @Override
- public Map<String, List<String>> getUserAttributes(String realm, String userId) {
- throw new UnsupportedOperationException("This provider does not support attributes");
- }
@Override
public void updateClientRoles(String realm, String client, Role[] roles) {
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
index 6f7bdc85a..831c778a9 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
@@ -19,22 +19,24 @@
*/
package org.openremote.manager.security;
+import jakarta.persistence.Query;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.security.AuthContext;
import org.openremote.container.security.IdentityProvider;
import org.openremote.model.event.shared.RealmFilter;
+import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.UserQuery;
import org.openremote.model.query.filter.StringPredicate;
import org.openremote.model.security.*;
import org.openremote.model.util.TextUtil;
import jakarta.persistence.Tuple;
-import jakarta.persistence.TypedQuery;
+
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
-import static org.openremote.manager.asset.AssetStorageService.buildMatchFilter;
+import static org.openremote.model.query.filter.StringPredicate.toSQLParameter;
import static org.openremote.model.Constants.MASTER_REALM;
// TODO: Normalise interface for Basic and Keycloak providers and add client CRUD
@@ -58,10 +60,6 @@ public interface ManagerIdentityProvider extends IdentityProvider {
String resetSecret(String realm, String userId, String secret);
- void updateUserAttributes(String realm, String userId, Map<String, List<String>> attributes);
-
- Map<String, List<String>> getUserAttributes(String realm, String userId);
-
Role[] getRoles(String realm, String client);
void updateClientRoles(String realm, String client, Role[] roles);
@@ -119,64 +117,112 @@ public interface ManagerIdentityProvider extends IdentityProvider {
return realmRoles.toArray(new String[0]);
}
+ @SuppressWarnings("unchecked")
static User[] getUsersFromDb(PersistenceService persistenceService, UserQuery query) {
StringBuilder sb = new StringBuilder();
List<Object> parameters = new ArrayList<>();
final UserQuery userQuery = query != null ? query : new UserQuery();
+ // Limit to regular/service users
+ if (userQuery.serviceUsers != null) {
+ // Not ideal mutating the query but seems excessive cloning it
+ if (userQuery.usernames == null) {
+ userQuery.usernames = new StringPredicate[1];
+ userQuery.usernames(new StringPredicate(AssetQuery.Match.BEGIN, User.SERVICE_ACCOUNT_PREFIX).negate(!userQuery.serviceUsers));
+ } else {
+ userQuery.usernames = Arrays.copyOf(userQuery.usernames, userQuery.usernames.length+1);
+ userQuery.usernames[userQuery.usernames.length-1] = new StringPredicate(AssetQuery.Match.BEGIN, User.SERVICE_ACCOUNT_PREFIX).negate(!userQuery.serviceUsers);
+ }
+ }
+
// BUILD SELECT
- sb.append("SELECT u");
+ sb.append("SELECT u.*, (SELECT C.SECRET FROM PUBLIC.CLIENT C WHERE C.ID = SERVICE_ACCOUNT_CLIENT_LINK) as secret, r.name as realm");
// BUILD FROM
- sb.append(" FROM User u");
- if (userQuery.assetPredicate != null || userQuery.pathPredicate != null) {
- sb.append(" join UserAssetLink ua on ua.id.userId = u.id");
+ sb.append(" FROM public.user_entity u join PUBLIC.REALM r on r.ID = u.REALM_ID");
+ if (userQuery.assets != null || userQuery.pathPredicate != null) {
+ sb.append(" join user_asset_link ua on ua.user_id = u.id");
}
// BUILD WHERE
- sb.append(" WHERE 1=1");
+ sb.append(" WHERE TRUE");
if (userQuery.realmPredicate != null && !TextUtil.isNullOrEmpty(userQuery.realmPredicate.name)) {
- sb.append(" AND u.realm = ?").append(parameters.size() + 1);
+ sb.append(" AND r.name = ?").append(parameters.size() + 1);
parameters.add(userQuery.realmPredicate.name);
}
- if (userQuery.assetPredicate != null) {
- sb.append(" AND ua.id.assetId = ?").append(parameters.size() + 1);
- parameters.add(userQuery.assetPredicate.id);
+ if (userQuery.assets != null) {
+ sb.append(" AND ua.asset_id IN (?").append(parameters.size() + 1).append(")");
+ parameters.add(Arrays.asList(userQuery.assets));
}
if (userQuery.pathPredicate != null) {
sb.append(" AND ?").append(parameters.size() + 1).append(" <@ get_asset_tree_path(ua.asset_id)");
parameters.add(userQuery.pathPredicate.path);
}
if (userQuery.ids != null && userQuery.ids.length > 0) {
- sb.append(" AND u.id IN (?").append(parameters.size() + 1);
- parameters.add(userQuery.ids[0]);
-
- for (int i = 1; i < userQuery.ids.length; i++) {
- sb.append(",?").append(parameters.size() + 1);
- parameters.add(userQuery.ids[i]);
- }
- sb.append(")");
+ sb.append(" AND u.id IN (?").append(parameters.size() + 1).append(")");
+ parameters.add(Arrays.asList(userQuery.ids));
}
if (userQuery.usernames != null && userQuery.usernames.length > 0) {
- sb.append(" and (");
- boolean isFirst = true;
+ sb.append(" and (FALSE");
for (StringPredicate pred : userQuery.usernames) {
- if (!isFirst) {
- sb.append(" or ");
- }
- isFirst = false;
final int pos = parameters.size() + 1;
- sb.append("upper(u.username)"); // No case support for username
- sb.append(buildMatchFilter(pred, pos));
+ // No case support for username
+ pred.caseSensitive = false;
+ sb.append(" or upper(u.username)");
+ sb.append(toSQLParameter(pred, pos, false));
parameters.add(pred.prepareValue());
}
sb.append(")");
}
- if (userQuery.select != null && userQuery.select.excludeRegularUsers) {
- sb.append(" and u.secret IS NOT NULL");
- } else if (userQuery.select != null && userQuery.select.excludeServiceUsers) {
- sb.append(" and u.secret IS NULL");
+ if (userQuery.realmRoles != null && userQuery.realmRoles.length > 0) {
+ sb.append(" and (FALSE");
+
+ Arrays.stream(userQuery.realmRoles).forEach(realmPredicate -> {
+ sb.append(" OR ");
+ if (realmPredicate.negate) {
+ // Negation implies does not contain this match so use a sub query in the where clause with not
+ // exists otherwise it will just match any other row
+ sb.append("NOT ");
+ }
+ sb.append("EXISTS (SELECT urm.user_id from public.user_role_mapping urm join public.keycloak_role kr on urm.role_id = kr.id where urm.user_id = u.id and not kr.client_role and");
+
+ sb.append(realmPredicate.caseSensitive ? " kr.name" : " upper(kr.name)");
+ sb.append(StringPredicate.toSQLParameter(realmPredicate, parameters.size() + 1, realmPredicate.negate));
+ parameters.add(realmPredicate.prepareValue());
+
+ sb.append(")");
+ });
+
+ sb.append(")");
+ }
+ if (userQuery.attributes != null && userQuery.attributes.length > 0) {
+ sb.append(" AND (TRUE");
+
+ Arrays.stream(userQuery.attributes).forEach(attributePredicate -> {
+ sb.append(" AND ");
+ if (attributePredicate.negated) {
+ // Negation implies does not contain this match so use a sub query in the where clause with not
+ // exists otherwise it will just match any other row
+ sb.append("NOT ");
+ }
+ sb.append("EXISTS (SELECT att.user_id from public.user_attribute att where att.user_id = u.id and");
+
+ sb.append(attributePredicate.name.caseSensitive ? " att.name" : " upper(att.name)");
+ sb.append(StringPredicate.toSQLParameter(attributePredicate.name, parameters.size() + 1, attributePredicate.negated));
+ parameters.add(attributePredicate.name.prepareValue());
+
+ if (attributePredicate.value != null) {
+ sb.append(" and ");
+ sb.append(attributePredicate.name.caseSensitive ? "att.value" : "upper(att.value)");
+ sb.append(StringPredicate.toSQLParameter(attributePredicate.value, parameters.size() + 1, attributePredicate.negated));
+ parameters.add(attributePredicate.value.prepareValue());
+ }
+
+ sb.append(")");
+ });
+
+ sb.append(")");
}
// BUILD ORDER BY
@@ -185,13 +231,13 @@ public interface ManagerIdentityProvider extends IdentityProvider {
sb.append(" ORDER BY");
switch(userQuery.orderBy.property) {
case CREATED_ON:
- sb.append(" u.createdOn");
+ sb.append(" u.created_on");
break;
case FIRST_NAME:
- sb.append(" u.firstName");
+ sb.append(" u.first_name");
break;
case LAST_NAME:
- sb.append(" u.lastName");
+ sb.append(" u.last_name");
break;
case USERNAME:
// Remove service user prefix
@@ -210,7 +256,7 @@ public interface ManagerIdentityProvider extends IdentityProvider {
}
List<User> users = persistenceService.doReturningTransaction(entityManager -> {
- TypedQuery<User> sqlQuery = entityManager.createQuery(sb.toString(), User.class);
+ Query sqlQuery = entityManager.createNativeQuery(sb.toString(), User.class);
IntStream.rangeClosed(1, parameters.size()).forEach(i -> sqlQuery.setParameter(i, parameters.get(i-1)));
if (userQuery.limit != null && userQuery.limit > 0) {
@@ -221,22 +267,20 @@ public interface ManagerIdentityProvider extends IdentityProvider {
sqlQuery.setFirstResult(query.offset);
}
- return sqlQuery.getResultList();
+ List<User> userList = sqlQuery.getResultList();
+ // TODO: Remove this once migrated to hibernate 6.2.x+
+ userList.forEach(u -> u.getAttributes().size());
+ return userList;
});
- if (userQuery.select != null && (userQuery.select.basic || userQuery.select.excludeSystemUsers)) {
- // TODO: Move this within the query
- return users.stream().filter(user -> {
- boolean keep = !userQuery.select.excludeSystemUsers || !user.isSystemAccount();
- if (keep && userQuery.select.basic) {
- // Clear out data and leave only basic info
- user.setAttributes(null);
- user.setEmail(null);
- user.setRealmId(null);
- user.setSecret(null);
- }
- return keep;
- }).toArray(User[]::new);
+ if (userQuery.select != null && userQuery.select.basic) {
+ users.forEach(user -> {
+ // Clear out data and leave only basic info
+ user.setAttributes((UserAttribute[]) null);
+ user.setEmail(null);
+ user.setRealmId(null);
+ user.setSecret(null);
+ });
}
return users.toArray(new User[0]);
}
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
index 0f7a31d3c..23b9565e6 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
@@ -23,6 +23,8 @@ import io.undertow.util.Headers;
import jakarta.persistence.Query;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.*;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.apache.commons.io.IOUtils;
@@ -55,7 +57,6 @@ import org.openremote.model.provisioning.ProvisioningConfig;
import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.UserQuery;
import org.openremote.model.query.filter.RealmPredicate;
-import org.openremote.model.query.filter.StringPredicate;
import org.openremote.model.rules.RealmRuleset;
import org.openremote.model.security.*;
import org.openremote.model.util.TextUtil;
@@ -92,8 +93,6 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
public static final String OR_KEYCLOAK_GRANT_FILE = "OR_KEYCLOAK_GRANT_FILE";
public static final String OR_KEYCLOAK_GRANT_FILE_DEFAULT = "manager/build/keycloak.json";
public static final String KEYCLOAK_DEFAULT_ROLES_PREFIX = "default-roles-";
- public static final String KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED = "emailNotificationsDisabled";
- public static final String KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED = "pushNotificationsDisabled";
public static final String KC_HOSTNAME = "KC_HOSTNAME";
public static final String KC_HOSTNAME_PATH = "KC_HOSTNAME_PATH";
public static final String KC_HOSTNAME_PORT = "KC_HOSTNAME_PORT";
@@ -248,18 +247,6 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
@Override
public User[] queryUsers(UserQuery userQuery) {
- if (userQuery == null) {
- userQuery = new UserQuery();
- }
-
- if (userQuery.usernames == null) {
- userQuery.usernames = new StringPredicate[1];
- userQuery.usernames(new StringPredicate(AssetQuery.Match.BEGIN, User.SERVICE_ACCOUNT_PREFIX).negate(true));
- } else {
- userQuery.usernames = Arrays.copyOf(userQuery.usernames, userQuery.usernames.length+1);
- userQuery.usernames[userQuery.usernames.length-1] = new StringPredicate(AssetQuery.Match.BEGIN, User.SERVICE_ACCOUNT_PREFIX).negate(true);
- }
-
return ManagerIdentityProvider.getUsersFromDb(persistenceService, userQuery);
}
@@ -344,6 +331,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
userRepresentation.setLastName(user.getLastName());
userRepresentation.setEmail(user.getEmail());
userRepresentation.setEnabled(user.getEnabled());
+ userRepresentation.setAttributes(user.getAttributeMap());
userResource.update(userRepresentation);
} else {
@@ -391,14 +379,6 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
}
}
- if (user.getAttributes() != null) {
- if (existingUser != null) {
- // Populate attributes for persistence event
- existingUser.setAttributes(getUserAttributes(realm, existingUser.getId()));
- }
- updateUserAttributes(realm, userRepresentation.getId(), user.getAttributes());
- }
-
User updatedUser = convert(userRepresentation, User.class);
if (updatedUser != null) {
updatedUser.setRealm(realm);
@@ -501,25 +481,6 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
});
}
- @Override
- public void updateUserAttributes(String realm, String userId, Map<String, List<String>> attributes) {
- getRealms(realmsResource -> {
- UserResource userResource = realmsResource.realm(realm).users().get(userId);
- UserRepresentation userRepresentation = realmsResource.realm(realm).users().get(userId).toRepresentation();
- userRepresentation.setAttributes(attributes);
- userResource.update(userRepresentation);
- return null;
- });
- }
-
- @Override
- public Map<String, List<String>> getUserAttributes(String realm, String userId) {
- return getRealms(realmsResource -> {
- UserRepresentation userRepresentation = realmsResource.realm(realm).users().get(userId).toRepresentation();
- return userRepresentation.getAttributes();
- });
- }
-
@Override
public Role[] getRoles(String realm, String client) {
return getRealms(realmsResource -> {
diff --git a/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java b/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java
index 6bf595d7c..d5b3b6f88 100644
--- a/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java
@@ -28,10 +28,14 @@ import org.openremote.model.Constants;
import org.openremote.model.http.RequestParams;
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.*;
import jakarta.ws.rs.*;
+
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.List;
import java.util.Objects;
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID;
@@ -71,13 +75,18 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource
// Force realm to match users
query.realm(new RealmPredicate(authContext.getAuthenticatedRealmName()));
- // Hide system service accounts from non super users
- if (query.select == null) {
- query.select = new UserQuery.Select();
+ // Hide system accounts from non super users
+ if (query.attributes == null) {
+ query.attributes(new UserQuery.AttributeValuePredicate(true, new StringPredicate(User.SYSTEM_ACCOUNT_ATTRIBUTE), null));
+ } else {
+ List<UserQuery.AttributeValuePredicate> attributeValuePredicates = new ArrayList<>(Arrays.asList(query.attributes));
+ attributeValuePredicates.add(new UserQuery.AttributeValuePredicate(true, new StringPredicate(User.SYSTEM_ACCOUNT_ATTRIBUTE), null));
+ query.attributes(attributeValuePredicates.toArray(UserQuery.AttributeValuePredicate[]::new));
}
- query.select.excludeSystemUsers = true;
}
+ // Prevent service
+
try {
return identityService.getIdentityProvider().queryUsers(query);
} catch (ClientErrorException ex) {
diff --git a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java
index 79dc4d16d..b8b651839 100644
--- a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java
@@ -33,8 +33,8 @@ import org.openremote.model.setup.Setup;
import java.util.Arrays;
import java.util.Collections;
-import static org.openremote.manager.security.ManagerKeycloakIdentityProvider.KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED;
-import static org.openremote.manager.security.ManagerKeycloakIdentityProvider.KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED;
+import static org.openremote.model.security.User.EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE;
+import static org.openremote.model.security.User.PUSH_NOTIFICATIONS_DISABLED_ATTRIBUTE;
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID;
public abstract class AbstractKeycloakSetup implements Setup {
@@ -96,10 +96,10 @@ public abstract class AbstractKeycloakSetup implements Setup {
user.setEmail(email);
user.setEnabled(enabled);
if (emailNotificationsDisabled) {
- user.setAttribute(KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED, "true");
+ user.setAttribute(EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE, "true");
}
if (pushNotificationsDisabled) {
- user.setAttribute(KEYCLOAK_USER_ATTRIBUTE_PUSH_NOTIFICATIONS_DISABLED, "true");
+ user.setAttribute(PUSH_NOTIFICATIONS_DISABLED_ATTRIBUTE, "true");
}
user = keycloakProvider.createUpdateUser(realm, user, password, true);
if (user == null) {
diff --git a/manager/src/main/java/org/openremote/manager/setup/KeycloakCleanSetup.java b/manager/src/main/java/org/openremote/manager/setup/KeycloakCleanSetup.java
index 7933fcc5e..f201e7feb 100644
--- a/manager/src/main/java/org/openremote/manager/setup/KeycloakCleanSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/KeycloakCleanSetup.java
@@ -53,7 +53,12 @@ public class KeycloakCleanSetup extends AbstractKeycloakSetup {
});
LOG.info("Deleting all non-master admin users");
- Arrays.stream(keycloakProvider.queryUsers(new UserQuery().realm(new RealmPredicate(MASTER_REALM)))).forEach(user -> {
+ Arrays.stream(keycloakProvider.queryUsers(
+ // Exclude service accounts (client deletion will remove the user)
+ new UserQuery()
+ .realm(new RealmPredicate(MASTER_REALM))
+ .serviceUsers(false)
+ )).forEach(user -> {
if (!user.getUsername().equals(MASTER_REALM_ADMIN_USER) && !user.getUsername().equals(MANAGER_CLIENT_ID)) {
LOG.info("Deleting user: " + user);
keycloakProvider.deleteUser(MASTER_REALM, user.getId());
diff --git a/model/src/main/java/org/openremote/model/query/UserQuery.java b/model/src/main/java/org/openremote/model/query/UserQuery.java
index 29329e7d4..49bca3b7a 100644
--- a/model/src/main/java/org/openremote/model/query/UserQuery.java
+++ b/model/src/main/java/org/openremote/model/query/UserQuery.java
@@ -1,35 +1,71 @@
package org.openremote.model.query;
+import com.fasterxml.jackson.annotation.JsonCreator;
import org.openremote.model.query.filter.PathPredicate;
import org.openremote.model.query.filter.RealmPredicate;
import org.openremote.model.query.filter.StringPredicate;
-import org.openremote.model.query.filter.UserAssetPredicate;
import java.util.Arrays;
public class UserQuery {
- public static class Select {
- public boolean basic;
- public boolean excludeServiceUsers;
- public boolean excludeRegularUsers;
- public boolean excludeSystemUsers;
+ public static class AttributeValuePredicate {
+ public boolean negated;
+ public StringPredicate name;
+ public StringPredicate value;
+
+ public AttributeValuePredicate(boolean negated, StringPredicate name) {
+ this.negated = negated;
+ this.name = name;
+ }
+
+ @JsonCreator
+ public AttributeValuePredicate(boolean negated, StringPredicate name, StringPredicate value) {
+ this.negated = negated;
+ this.name = name;
+ this.value = value;
+ }
+
+ public boolean isNegated() {
+ return negated;
+ }
- public Select excludeServiceUsers(boolean excludeServiceUsers) {
- this.excludeServiceUsers = excludeServiceUsers;
+ public AttributeValuePredicate setNegated(boolean negated) {
+ this.negated = negated;
return this;
}
- public Select excludeRegularUsers(boolean excludeRegularUsers) {
- this.excludeRegularUsers = excludeRegularUsers;
+ public StringPredicate getName() {
+ return name;
+ }
+
+ public AttributeValuePredicate setName(StringPredicate name) {
+ this.name = name;
return this;
}
- public Select excludeSystemUsers(boolean excludeSystemUsers) {
- this.excludeSystemUsers = excludeSystemUsers;
+ public StringPredicate getValue() {
+ return value;
+ }
+
+ public AttributeValuePredicate setValue(StringPredicate value) {
+ this.value = value;
return this;
}
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "negated=" + negated +
+ ", name=" + name +
+ ", value=" + value +
+ '}';
+ }
+ }
+
+ public static class Select {
+ public boolean basic;
+
public Select basic(boolean basic) {
this.basic = basic;
return this;
@@ -38,10 +74,7 @@ public class UserQuery {
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
- "excludeServiceUsers=" + excludeServiceUsers +
- ", excludeRegularUsers=" + excludeRegularUsers +
- ", excludeSystemUsers=" + excludeSystemUsers +
- ", basic=" + basic +
+ ", basic=" + basic +
'}';
}
}
@@ -92,11 +125,20 @@ public class UserQuery {
// Restriction predicates
public RealmPredicate realmPredicate;
- public UserAssetPredicate assetPredicate;
+ public String[] assets;
public PathPredicate pathPredicate;
public String[] ids;
public Select select;
public StringPredicate[] usernames;
+ /**
+ * AND condition is assumed between values
+ */
+ public AttributeValuePredicate[] attributes;
+ /**
+ * OR condition is assumed between values (AND filtering can be applied by the caller on the results)
+ */
+ public StringPredicate[] realmRoles;
+ public Boolean serviceUsers;
public Integer limit;
public Integer offset;
public OrderBy orderBy;
@@ -109,8 +151,8 @@ public class UserQuery {
return this;
}
- public UserQuery asset(UserAssetPredicate assetPredicate) {
- this.assetPredicate = assetPredicate;
+ public UserQuery assets(String...assetIds) {
+ this.assets = assetIds;
return this;
}
@@ -129,6 +171,21 @@ public class UserQuery {
return this;
}
+ public UserQuery attributes(AttributeValuePredicate...attributes) {
+ this.attributes = attributes;
+ return this;
+ }
+
+ public UserQuery realmRoles(StringPredicate...realmRoles) {
+ this.realmRoles = realmRoles;
+ return this;
+ }
+
+ public UserQuery serviceUsers(Boolean serviceUsers) {
+ this.serviceUsers = serviceUsers;
+ return this;
+ }
+
public UserQuery limit(int limit) {
this.limit = limit;
return this;
@@ -153,10 +210,13 @@ public class UserQuery {
public String toString() {
return getClass().getSimpleName() + "{" +
"realmPredicate=" + realmPredicate +
- ", assetPredicate=" + assetPredicate +
+ ", assets=" + assets +
", pathPredicate=" + pathPredicate +
", ids=" + (ids != null ? Arrays.toString(ids) : "null") +
", usernames=" + (usernames != null ? Arrays.toString(usernames) : "null") +
+ ", serviceUsers=" + serviceUsers +
+ ", attributes=" + (attributes != null ? Arrays.toString(attributes) : "null") +
+ ", realmRoles=" + (realmRoles != null ? Arrays.toString(realmRoles) : "null") +
", limit=" + limit +
", offset=" + offset +
", orderBy=" + orderBy +
diff --git a/model/src/main/java/org/openremote/model/query/filter/RealmPredicate.java b/model/src/main/java/org/openremote/model/query/filter/RealmPredicate.java
index 693058aef..207b8c81d 100644
--- a/model/src/main/java/org/openremote/model/query/filter/RealmPredicate.java
+++ b/model/src/main/java/org/openremote/model/query/filter/RealmPredicate.java
@@ -34,7 +34,7 @@ public class RealmPredicate {
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
- ", name='" + name + '\'' +
+ "name='" + name + '\'' +
'}';
}
}
diff --git a/model/src/main/java/org/openremote/model/query/filter/StringPredicate.java b/model/src/main/java/org/openremote/model/query/filter/StringPredicate.java
index 2c04c44c8..8884d5f24 100644
--- a/model/src/main/java/org/openremote/model/query/filter/StringPredicate.java
+++ b/model/src/main/java/org/openremote/model/query/filter/StringPredicate.java
@@ -63,6 +63,25 @@ public class StringPredicate extends ValuePredicate {
this.value = value;
}
+ public static String toSQLParameter(StringPredicate predicate, int pos, boolean ignoreNegation) {
+ switch (predicate.match) {
+ case BEGIN:
+ case END:
+ case CONTAINS:
+ if (!ignoreNegation && predicate.negate) {
+ return predicate.caseSensitive ? " not like ?" + pos : " not like upper(?" + pos + ")";
+ }
+ return predicate.caseSensitive ? " like ?" + pos : " like upper(?" + pos + ")";
+ case EXACT:
+ if (!ignoreNegation && predicate.negate) {
+ return predicate.caseSensitive ? " <> ?" + pos : " <> upper(?" + pos + ")";
+ }
+ return predicate.caseSensitive ? " = ?" + pos : " = upper(?" + pos + ")";
+ default:
+ throw new UnsupportedOperationException("Unsupported match type" + predicate.match);
+ }
+ }
+
public Predicate<Object> asPredicate(Supplier<Long> currentMillisSupplier) {
return obj -> {
@@ -111,10 +130,7 @@ public class StringPredicate extends ValuePredicate {
}
public String prepareValue() {
- String s = match.prepare(this.value);
- if (!caseSensitive)
- s = s.toUpperCase(Locale.ROOT);
- return s;
+ return match.prepare(this.value);
}
@Override
diff --git a/model/src/main/java/org/openremote/model/query/filter/UserAssetPredicate.java b/model/src/main/java/org/openremote/model/query/filter/UserAssetPredicate.java
deleted file mode 100644
index 5822d823a..000000000
--- a/model/src/main/java/org/openremote/model/query/filter/UserAssetPredicate.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.model.query.filter;
-
-public class UserAssetPredicate {
- public String id;
-
- public UserAssetPredicate() {
- }
-
- public UserAssetPredicate(String id) {
- this.id = id;
- }
-
- public UserAssetPredicate id(String id) {
- this.id = id;
- return this;
- }
-}
diff --git a/model/src/main/java/org/openremote/model/security/RealmRole.java b/model/src/main/java/org/openremote/model/security/RealmRole.java
index 1b7db01f0..4053e0a63 100644
--- a/model/src/main/java/org/openremote/model/security/RealmRole.java
+++ b/model/src/main/java/org/openremote/model/security/RealmRole.java
@@ -31,7 +31,7 @@ import jakarta.persistence.Id;
import java.util.Objects;
@Entity
-@Subselect("select * from PUBLIC.KEYCLOAK_ROLE where CLIENT is NULL") // Map this immutable to an SQL view, don't use/create table
+@Subselect("select * from PUBLIC.KEYCLOAK_ROLE where NOT CLIENT_ROLE") // Map this immutable to an SQL view, don't use/create table
public class RealmRole {
@JsonIgnore
diff --git a/model/src/main/java/org/openremote/model/security/User.java b/model/src/main/java/org/openremote/model/security/User.java
index b3797eaf1..4b09e95dd 100644
--- a/model/src/main/java/org/openremote/model/security/User.java
+++ b/model/src/main/java/org/openremote/model/security/User.java
@@ -22,23 +22,22 @@ package org.openremote.model.security;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
-import org.hibernate.annotations.Formula;
-import org.hibernate.annotations.Subselect;
-import org.openremote.model.persistence.EpochMillisInstantType;
-
import jakarta.persistence.*;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
-import jakarta.ws.rs.core.MultivaluedHashMap;
-import jakarta.ws.rs.core.MultivaluedMap;
+import org.hibernate.annotations.Formula;
+import org.hibernate.annotations.Subselect;
+import org.openremote.model.persistence.EpochMillisInstantType;
+
import java.lang.reflect.Field;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
/**
* This can be used (among other things) to query the USER_ENTITY table in JPA queries.
@@ -49,6 +48,8 @@ import java.util.Map;
public class User {
public static final String SERVICE_ACCOUNT_PREFIX = "service-account-";
public static final String SYSTEM_ACCOUNT_ATTRIBUTE = "systemAccount";
+ public static final String EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE = "emailNotificationsDisabled";
+ public static final String PUSH_NOTIFICATIONS_DISABLED_ATTRIBUTE = "pushNotificationsDisabled";
protected static Field[] propertyFields;
@Formula("(select r.NAME from PUBLIC.REALM r where r.ID = REALM_ID)")
@@ -146,40 +147,49 @@ public class User {
return username != null && username.startsWith(SERVICE_ACCOUNT_PREFIX);
}
+ @JsonIgnore
+ public List<UserAttribute> getAttributes() {
+ return attributes;
+ }
+
+ @JsonIgnore
+ public User setAttributes(UserAttribute...attributes) {
+ this.attributes = attributes == null ? null : Arrays.asList(attributes);
+ return this;
+ }
+
@JsonProperty
- public Map<String, List<String>> getAttributes() {
- if (this.attributes == null) {
- return null;
+ protected User setAttributes(Map<String, List<String>> attributes) {
+ if (attributes == null) {
+ this.attributes = new ArrayList<>();
+ } else {
+ this.attributes = new ArrayList<>(attributes.entrySet().stream().flatMap(entry -> entry.getValue().stream().map(v -> new UserAttribute(entry.getKey(), v))).toList());
}
- MultivaluedMap<String, String> attrs = new MultivaluedHashMap<>();
- this.attributes.forEach(attribute -> attrs.add(attribute.getName(), attribute.getValue()));
- return attrs;
+ return this;
}
- public User setAttributes(Map<String, List<String>> attributes) {
+ @JsonProperty("attributes")
+ public Map<String, List<String>> getAttributeMap() {
if (attributes == null) {
- this.attributes = null;
- return this;
+ return null;
}
- List<UserAttribute> attrs = new ArrayList<>();
- attributes.forEach((k, v) -> v.forEach(val -> attrs.add(new UserAttribute(k, val))));
- this.attributes = attrs;
- return this;
+ return attributes.stream().collect(Collectors.groupingBy(UserAttribute::getName, Collectors.mapping(UserAttribute::getValue, Collectors.toList())));
}
- public User setAttribute(String key, String...values) {
+ public User setAttribute(String key, String value) {
if (attributes == null) {
attributes = new ArrayList<>();
} else {
attributes.removeIf(attr -> attr.getName().equals(key));
}
-
- if (values != null && values.length > 0) {
- Arrays.stream(values).forEach((value) -> attributes.add(new UserAttribute(key, value)));
- }
+ attributes.add(new UserAttribute(key, value));
return this;
}
+ public boolean hasAttribute(String key) {
+ return attributes != null && attributes.stream().anyMatch(attr -> attr.getName().equals(key));
+ }
+
public User removeAttribute(String key) {
if (attributes != null) {
attributes.removeIf(attr -> attr.getName().equals(key));
@@ -197,8 +207,7 @@ public class User {
}
public boolean isSystemAccount() {
- Map<String, List<String>> attributes = getAttributes();
- return attributes != null && attributes.containsKey(SYSTEM_ACCOUNT_ATTRIBUTE);
+ return hasAttribute(SYSTEM_ACCOUNT_ATTRIBUTE);
}
/**
@@ -209,7 +218,7 @@ public class User {
if (systemAccount) {
setAttribute(SYSTEM_ACCOUNT_ATTRIBUTE, "true");
} else {
- setAttribute(SYSTEM_ACCOUNT_ATTRIBUTE);
+ removeAttribute(SYSTEM_ACCOUNT_ATTRIBUTE);
}
return this;
}
diff --git a/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java b/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java
index 444c1d867..3e7a83f72 100644
--- a/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java
+++ b/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java
@@ -19,6 +19,8 @@
*/
package org.openremote.setup.integration;
+import org.keycloak.admin.client.resource.RealmResource;
+import org.keycloak.representations.idm.RoleRepresentation;
import org.openremote.container.util.UniqueIdentifierGenerator;
import org.openremote.manager.security.ManagerIdentityProvider;
import org.openremote.manager.setup.AbstractKeycloakSetup;
@@ -50,7 +52,8 @@ import static org.openremote.model.Constants.RESTRICTED_USER_REALM_ROLE;
public class KeycloakTestSetup extends AbstractKeycloakSetup {
private static final Logger LOG = Logger.getLogger(KeycloakTestSetup.class.getName());
-
+ public static final String REALM_ROLE_TEST = "test-realm-role";
+ public static final String REALM_ROLE_TEST2 = "test-realm-role-2";
public String testuser1Id;
public String testuser2Id;
public String testuser3Id;
@@ -77,6 +80,14 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {
realmCity = createRealm("smartcity", "Smart City", true);
realmEnergy = createRealm("energy", "Energy Test", true);
+ // Add a test realm roles
+ keycloakProvider.getRealms(realmsResource -> {
+ RealmResource realmResource = realmsResource.realm(realmBuilding.getName());
+ realmResource.roles().create(new RoleRepresentation(REALM_ROLE_TEST, "Test role", false));
+ realmResource.roles().create(new RoleRepresentation(REALM_ROLE_TEST2, "Test role 2", false));
+ return null;
+ });
+
// Don't allow demo users to write assets
ClientRole[] noWriteAccess = Arrays.stream(REGULAR_USER_ROLES)
.filter(clientRole -> clientRole != ClientRole.WRITE_ASSETS)
@@ -97,9 +108,13 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {
User testuser3 = createUser(realmBuilding.getName(), "testuser3", "testuser3", "DemoA3", "DemoLast", "[email protected]", true, true, false, REGULAR_USER_ROLES);
this.testuser3Id = testuser3.getId();
keycloakProvider.updateUserRoles(realmBuilding.getName(), testuser3Id, "account"); // Remove all roles for account client
+ // Add realm role
+ keycloakProvider.updateUserRealmRoles(realmBuilding.getName(), testuser3Id, keycloakProvider.addRealmRoles(realmBuilding.getName(), testuser3Id, REALM_ROLE_TEST));
User buildingUser = createUser(realmBuilding.getName(), "building", "building", "Building", "User", "[email protected]", true, noWriteAccess);
this.buildingUserId = buildingUser.getId();
keycloakProvider.updateUserRoles(realmBuilding.getName(), buildingUserId, "account"); // Remove all roles for account client
+ // Add realm role
+ keycloakProvider.updateUserRealmRoles(realmBuilding.getName(), buildingUserId, keycloakProvider.addRealmRoles(realmBuilding.getName(), buildingUserId, REALM_ROLE_TEST2));
User smartCityUser = createUser(realmCity.getName(), "smartcity", "smartcity", "Smart", "City", null, true, noWriteAccess);
this.smartCityUserId = smartCityUser.getId();
keycloakProvider.updateUserRoles(realmCity.getName(), smartCityUserId, "account"); // Remove all roles for account client
diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
index 7807caee4..00bb736a7 100644
--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
@@ -574,7 +574,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
expect: "the demo users to be created"
conditions.eventually {
- def users = identityService.getIdentityProvider().queryUsers(new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmBuilding.name)).select(new UserQuery.Select().excludeServiceUsers(true)))
+ def users = identityService.getIdentityProvider().queryUsers(new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmBuilding.name)).serviceUsers(false))
assert users.size() == 3
assert users.count { !TextUtil.isNullOrEmpty(it.email)} == 3
}
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
index 45f71d921..3bf92edc1 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
@@ -106,9 +106,8 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
def "Turn all lights off when console exits the residence geofence"() {
- List<PushNotificationMessage> pushMessages = []
+ List<Tuple2<Notification.Target, PushNotificationMessage>> pushTargetsAndMessages = []
List<jakarta.mail.Message> emailMessages = []
- List<Notification.Target> pushTargets = []
List<Notification.Target> emailTargets = []
given: "the geofence notifier debounce is set to a small value for testing"
@@ -135,8 +134,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
mockPushNotificationHandler.isValid() >> true
mockPushNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {
id, source, sourceId, target, message ->
- pushMessages << message
- pushTargets << target
+ pushTargetsAndMessages << new Tuple2<>(target, message)
callRealMethod()
}
// Assume sent to FCM
@@ -154,7 +152,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
callRealMethod()
}
- // Assume sent to FCM
+ // Assume sent to server
mockEmailNotificationHandler.sendMessage(_ as jakarta.mail.Message) >> {
email ->
emailMessages << email.get(0)
@@ -199,7 +197,16 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
"testuser3"
).token
- and: "a console is registered by that user"
+ and: "another user authenticates"
+ def accessToken2 = authenticate(
+ container,
+ keycloakTestSetup.realmBuilding.name,
+ KEYCLOAK_CLIENT_ID,
+ "building",
+ "building"
+ ).token
+
+ and: "a console is registered by the first user"
def authenticatedConsoleResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken).proxy(ConsoleResource.class)
def consoleRegistration = new ConsoleRegistration(null,
"Test Console",
@@ -231,6 +238,38 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
["manager"] as String[])
consoleRegistration = authenticatedConsoleResource.register(null, consoleRegistration)
+ and: "a console is registered by the second user"
+ def authenticatedConsoleResource2 = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, accessToken2).proxy(ConsoleResource.class)
+ def consoleRegistration2 = new ConsoleRegistration(null,
+ "Test Console",
+ "1.0",
+ "Android 7.0",
+ new HashMap<String, ConsoleProvider>() {
+ {
+ put("geofence", new ConsoleProvider(
+ ORConsoleGeofenceAssetAdapter.NAME,
+ true,
+ false,
+ false,
+ false,
+ false,
+ null
+ ))
+ put("push", new ConsoleProvider(
+ "fcm",
+ true,
+ true,
+ true,
+ true,
+ false,
+ ((ObjectNode) parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)
+ )))
+ }
+ },
+ "",
+ ["manager"] as String[])
+ consoleRegistration2 = authenticatedConsoleResource2.register(null, consoleRegistration2)
+
and: "the console location is marked as RULE_STATE"
def asset = assetStorageService.find(consoleRegistration.id)
asset.getAttribute(Asset.LOCATION).ifPresent { it.addMeta(new MetaItem<>(MetaItemType.RULE_STATE))}
@@ -238,12 +277,15 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "a geofence refresh notification should have been sent to the console"
conditions.eventually {
- assert pushMessages.size() == 1
+ assert pushTargetsAndMessages.size() == 1
}
- when:"an additional user is linked to this console (to help with testing)"
+ when:"additional users are linked to this console (to help with testing)"
assetStorageService.storeUserAssetLinks(
- Collections.singletonList(new UserAssetLink(keycloakTestSetup.realmBuilding.getName(), keycloakTestSetup.testuser2Id, consoleRegistration.id))
+ [
+ new UserAssetLink(keycloakTestSetup.realmBuilding.getName(), keycloakTestSetup.testuser2Id, consoleRegistration.id),
+ new UserAssetLink(keycloakTestSetup.realmBuilding.getName(), keycloakTestSetup.buildingUserId, consoleRegistration.id)
+ ]
)
and: "the console location is set to the apartment"
@@ -285,14 +327,19 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
and: "a push notification should have been sent to the console via the asset target with the title 'Test title'"
conditions.eventually {
- assert pushMessages.findAll {it.title == "Test title"}.size() == 1
- assert pushTargets.any {it.type == Notification.TargetType.ASSET && it.id == consoleRegistration.id}
+ assert pushTargetsAndMessages.count {it.v2.title == "Test title" && it.v1.type == Notification.TargetType.ASSET && it.v1.id == consoleRegistration.id} == 1
+ }
+
+ and: "two push notifications should have been sent to the consoles via the linked user targets with test-realm-role% realm attribute with the title 'Linked user test'"
+ conditions.eventually {
+ assert pushTargetsAndMessages.count {it.v2.title == "Linked user test" && it.v1.type == Notification.TargetType.ASSET && it.v1.id == consoleRegistration.id} == 1
+ assert pushTargetsAndMessages.count {it.v2.title == "Linked user test" && it.v1.type == Notification.TargetType.ASSET && it.v1.id == consoleRegistration2.id} == 1
}
- and: "a push notification should have been sent to the console via the user target with the title 'Linked user test'"
+ and: "a push notifications should have been sent to the consoles of the linked user target with test-realm-role-2 realm attribute with the title 'Linked user test 2'"
conditions.eventually {
- assert pushMessages.findAll {it.title == "Linked user test"}.size() == 1
- assert pushTargets.any {it.type == Notification.TargetType.ASSET && it.id == consoleRegistration.id}
+ assert pushTargetsAndMessages.count {it.v2.title == "Linked user test 2" && it.v1.type == Notification.TargetType.ASSET && it.v1.id == consoleRegistration.id} == 1
+ assert pushTargetsAndMessages.count {it.v2.title == "Linked user test 2" && it.v1.type == Notification.TargetType.ASSET && it.v1.id == consoleRegistration2.id} == 1
}
and: "an email notification should have been sent to [email protected] with the triggered asset in the body"
@@ -311,7 +358,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
and: "after a few seconds the rule should not have fired again"
new PollingConditions(timeout: 5, initialDelay: 1).eventually {
- assert pushMessages.findAll {it.title == "Test title"}.size() == 1
+ assert pushTargetsAndMessages.findAll {it.v2.title == "Test title"}.size() == 1
}
when: "the console device moves back inside the home geofence (as defined in the rule)"
@@ -328,7 +375,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "another notification should have been sent to the console"
conditions.eventually {
- assert pushMessages.findAll {it.title == "Test title"}.size() == 2
+ assert pushTargetsAndMessages.findAll {it.v2.title == "Test title"}.size() == 2
}
when: "the console sends a location update with a new location but still outside the geofence"
@@ -338,7 +385,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "after a few seconds the rule should not have fired again"
new PollingConditions(timeout: 5, initialDelay: 1).eventually {
- assert pushMessages.findAll {it.title == "Test title"}.size() == 2
+ assert pushTargetsAndMessages.findAll {it.v2.title == "Test title"}.size() == 2
}
when: "the ruleset is modified to add a 4hr recurrence per asset"
@@ -356,7 +403,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
and: "another notification should have been sent to the console when rule is redeployed"
conditions.eventually {
- assert pushMessages.findAll {it.title == "Test title"}.size() == 3
+ assert pushTargetsAndMessages.findAll {it.v2.title == "Test title"}.size() == 3
}
when: "the console device moves back inside the home geofence (as defined in the rule)"
@@ -374,7 +421,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "after a few seconds the rule should not have fired again"
new PollingConditions(timeout: 5, initialDelay: 1).eventually {
- assert pushMessages.findAll {it.title == "Test title"}.size() == 3
+ assert pushTargetsAndMessages.findAll {it.v2.title == "Test title"}.size() == 3
}
when: "the console device moves back inside the home geofence (as defined in the rule)"
@@ -395,8 +442,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "another notification should have been sent to the console"
conditions.eventually {
- assert pushMessages.findAll {it.title == "Test title"}.size() == 4
- assert pushTargets[3].id == consoleRegistration.id
+ assert pushTargetsAndMessages.findAll {it.v2.title == "Test title" && it.v1.id == consoleRegistration.id}.size() == 4
}
when: "the Rules PAUSE_SCHEDULER is overridden to facilitate testing"
@@ -451,7 +497,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
}
and: "no notification should have been sent as outside the validity period"
- assert pushMessages.findAll {it.title == "Test title"}.size() == 4
+ assert pushTargetsAndMessages.findAll {it.v2.title == "Test title"}.size() == 4
when: "the pause elapses"
engine.unPauseRuleset(deployment)
@@ -474,7 +520,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
and: "another notification should have been sent as inside the validity period"
conditions.eventually {
- assert pushMessages.findAll {it.title == "Test title"}.size() == 5
+ assert pushTargetsAndMessages.findAll {it.v2.title == "Test title"}.size() == 5
}
when: "the un-pause elapses"
@@ -497,7 +543,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
}
and: "no notification should have been sent as outside the validity period"
- assert pushMessages.findAll {it.title == "Test title"}.size() == 5
+ assert pushTargetsAndMessages.findAll {it.v2.title == "Test title"}.size() == 5
when: "the pause elapses"
engine.unPauseRuleset(deployment)
diff --git a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
index 293c26b8c..960e0cfa0 100644
--- a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
@@ -24,6 +24,8 @@ import org.openremote.manager.setup.SetupService
import org.openremote.model.Constants
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.User
import org.openremote.setup.integration.KeycloakTestSetup
import org.openremote.model.security.ClientRole
import org.openremote.model.security.Role
@@ -40,13 +42,16 @@ import static org.openremote.container.util.MapAccess.getString
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
import static org.openremote.model.Constants.MASTER_REALM
import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER
+import static org.openremote.model.security.User.EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE
class UserResourceTest extends Specification implements ManagerContainerTrait {
@Shared
static UserResource adminUserResource
@Shared
- static UserResource regularUserResource
+ static UserResource regularUserMasterResource
+ @Shared
+ static UserResource regularUserBuildingResource
@Shared
static KeycloakTestSetup keycloakTestSetup
@@ -63,7 +68,15 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
).token
- def regularAccessToken = authenticate(
+ def regularMasterAccessToken = authenticate(
+ container,
+ MASTER_REALM,
+ KEYCLOAK_CLIENT_ID,
+ "testuser1",
+ "testuser1"
+ ).token
+
+ def regularBuildingAccessToken = authenticate(
container,
keycloakTestSetup.realmBuilding.name,
KEYCLOAK_CLIENT_ID,
@@ -72,7 +85,8 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
).token
adminUserResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(UserResource.class)
- regularUserResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, regularAccessToken).proxy(UserResource.class)
+ regularUserMasterResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, regularMasterAccessToken).proxy(UserResource.class)
+ regularUserBuildingResource = getClientApiTarget(serverUri(serverPort), keycloakTestSetup.realmBuilding.name, regularBuildingAccessToken).proxy(UserResource.class)
}
def "User queries"() {
@@ -82,11 +96,20 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
then: "all users should be returned including system users"
users.size() == 3
- users.count {it.isSystemAccount() && it.username == Constants.MANAGER_CLIENT_ID} == 1
- users.count {!it.isServiceAccount()} == 3
+ users.find {it.isSystemAccount() && it.username == Constants.MANAGER_CLIENT_ID} != null
+ users.find {it.username == MASTER_REALM_ADMIN_USER} != null
+ users.find {it.id == keycloakTestSetup.testuser1Id} != null
- when: "a request is made for all users by a regular user"
- users = regularUserResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)))
+ when: "a request is made for all users in the same realm by a regular user"
+ users = regularUserMasterResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)))
+
+ then: "only non system users of the users realm should be returned"
+ users.size() == 2
+ users.find {it.username == MASTER_REALM_ADMIN_USER} != null
+ users.find {it.id == keycloakTestSetup.testuser1Id} != null
+
+ when: "a request is made for all users in a different realm by a regular user"
+ users = regularUserBuildingResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)))
then: "only non system users of the users realm should be returned"
users.size() == 5
@@ -98,7 +121,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
users.find {it.isServiceAccount() && it.id == keycloakTestSetup.serviceUser2.id} != null
when: "a request is made for all users ordered by username"
- users = regularUserResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)).orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, false)))
+ users = regularUserBuildingResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)).orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, false)))
then: "only non system users of the users realm should be returned in username order"
users.size() == 5
@@ -109,7 +132,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
users[4].username == "testuser3"
when: "a request is made for subset of users ordered by username descending"
- users = regularUserResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)).orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, true)).limit(2))
+ users = regularUserBuildingResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)).orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, true)).limit(2))
then: "the correct users should be returned"
users.size() == 2
@@ -117,15 +140,15 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
users[1].username == "testuser2"
when: "a request is made for another subset of users ordered by username descending"
- users = regularUserResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)).orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, true)).limit(2).offset(3))
+ users = regularUserBuildingResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)).orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, true)).limit(2).offset(3))
then: "the correct users should be returned"
users.size() == 2
users[0].username == keycloakTestSetup.serviceUser.username
users[1].username == "building"
- when: "a request is made for only service users"
- users = adminUserResource.query(null, new UserQuery().select(new UserQuery.Select().excludeRegularUsers(true)).realm(new RealmPredicate(keycloakTestSetup.realmBuilding.name)))
+ when: "a request is made for only service users (users with a secret)"
+ users = adminUserResource.query(null, new UserQuery().serviceUsers(true).realm(new RealmPredicate(keycloakTestSetup.realmBuilding.name)))
then: "only service users of the requested realm should be returned"
users.size() == 2
@@ -133,6 +156,47 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
users.find {it.isServiceAccount() && it.id == keycloakTestSetup.serviceUser2.id} != null
users.find {it.isServiceAccount() && it.id == keycloakTestSetup.serviceUser.id}.secret != null
users.find {it.isServiceAccount() && it.id == keycloakTestSetup.serviceUser2.id}.secret != null
+
+ when: "a request is made for only restricted users"
+ users = regularUserBuildingResource.query(null,
+ new UserQuery()
+ .realm(new RealmPredicate(keycloakTestSetup.realmBuilding.name))
+ .realmRoles(new StringPredicate(Constants.RESTRICTED_USER_REALM_ROLE))
+ .orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, false)))
+
+ then: "only restricted users of this realm should be returned"
+ users.size() == 3
+ users[0].username == "building"
+ users[1].username == keycloakTestSetup.serviceUser2.username
+ users[2].username == "testuser3"
+
+ when: "a request is made for non restricted users"
+ users = regularUserBuildingResource.query(null,
+ new UserQuery()
+ .realm(new RealmPredicate(keycloakTestSetup.realmBuilding.name))
+ .realmRoles(new StringPredicate(Constants.RESTRICTED_USER_REALM_ROLE).negate(true))
+ .orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, false)))
+
+ then: "only non restricted users of this realm should be returned"
+ users.size() == 2
+ users[0].username == keycloakTestSetup.serviceUser.username
+ users[1].username == "testuser2"
+
+ when: "a request is made based on user attributes"
+ users = regularUserBuildingResource.query(null,
+ new UserQuery()
+ .realm(new RealmPredicate(keycloakTestSetup.realmBuilding.name))
+ .attributes(
+ new UserQuery.AttributeValuePredicate(true, new StringPredicate(User.SYSTEM_ACCOUNT_ATTRIBUTE)),
+ new UserQuery.AttributeValuePredicate(true, new StringPredicate(EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE), new StringPredicate("true"))
+ ).orderBy(new UserQuery.OrderBy(UserQuery.OrderBy.Property.USERNAME, false)))
+
+ then: "only matching users of this realm should be returned"
+ users.size() == 4
+ users[0].username == "building"
+ users[1].username == keycloakTestSetup.serviceUser.username
+ users[2].username == keycloakTestSetup.serviceUser2.username
+ users[3].username == "testuser2"
}
def "Get and update roles"() {
@@ -157,7 +221,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
readAssets.compositeRoleIds == null
when: "a request is made for the roles in the smart building realm by a regular user"
- regularUserResource.getRoles(null, keycloakTestSetup.realmBuilding.name)
+ regularUserBuildingResource.getRoles(null, keycloakTestSetup.realmBuilding.name)
then: "a not allowed exception should be thrown"
thrown(ForbiddenException.class)
@@ -199,4 +263,28 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
writeRole.compositeRoleIds.length == 1
writeRole.compositeRoleIds.contains(roles.find {it.name == ClientRole.READ_ASSETS.value}.id)
}
+
+ def "Get and update users"() {
+ when: "a user is retrieved"
+ def user = adminUserResource.get(null, keycloakTestSetup.realmBuilding.name, keycloakTestSetup.testuser3Id)
+
+ then: "all data should be available"
+ user != null
+ user.attributes != null
+ user.attributes.size() == 1
+ user.attributes.get(0).getName() == EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE
+ user.attributes.get(0).getValue() == "true"
+ user.id == keycloakTestSetup.testuser3Id
+ user.realm == keycloakTestSetup.realmBuilding.name
+ user.username == "testuser3"
+
+ when: "a new attribute is added to the user"
+ user.setAttribute("test", "testvalue")
+ user = adminUserResource.update(null, keycloakTestSetup.realmBuilding.name, user)
+
+ then: "the update should have succeeded"
+ user.attributes.size() == 2
+ user.attributes.any {it.name == EMAIL_NOTIFICATIONS_DISABLED_ATTRIBUTE && it.value == "true"}
+ user.attributes.any {it.name == "test" && it.value == "testvalue"}
+ }
}
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
index 679864306..a24239ee7 100644
--- a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
+++ b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
@@ -54,7 +54,16 @@
{
"action": "notification",
"target": {
- "linkedUsers": true
+ "linkedUsers": true,
+ "users": {
+ "realmRoles": [
+ {
+ "predicateType": "string",
+ "match": "BEGIN",
+ "value": "test-realm-role"
+ }
+ ]
+ }
},
"notification": {
"name": "linkedPushTest",
@@ -64,6 +73,27 @@
}
}
},
+ {
+ "action": "notification",
+ "target": {
+ "linkedUsers": true,
+ "users": {
+ "realmRoles": [
+ {
+ "predicateType": "string",
+ "value": "test-realm-role-2"
+ }
+ ]
+ }
+ },
+ "notification": {
+ "name": "linkedPushTest",
+ "message": {
+ "type": "push",
+ "title": "Linked user test 2"
+ }
+ }
+ },
{
"action": "notification",
"target": {
diff --git a/test/src/test/resources/org/openremote/test/rules/ResidenceNotifyAlarmTrigger.groovy b/test/src/test/resources/org/openremote/test/rules/ResidenceNotifyAlarmTrigger.groovy
index 386d4ed06..e5c57e045 100644
--- a/test/src/test/resources/org/openremote/test/rules/ResidenceNotifyAlarmTrigger.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/ResidenceNotifyAlarmTrigger.groovy
@@ -11,7 +11,6 @@ import org.openremote.model.notification.PushNotificationButton
import org.openremote.model.query.AssetQuery
import org.openremote.model.notification.PushNotificationMessage
import org.openremote.model.query.UserQuery
-import org.openremote.model.query.filter.UserAssetPredicate
import org.openremote.model.rules.Notifications
import org.openremote.model.rules.Users
@@ -146,7 +145,7 @@ rules.add()
// Get users linked to this residence
UserQuery query = new UserQuery()
- .asset(new UserAssetPredicate(alarmTrigger.residenceId))
+ .assets(alarmTrigger.residenceId)
Collection<String> userIds = users.getResults(query).collect(Collectors.toList())
diff --git a/ui/app/manager/src/pages/page-users.ts b/ui/app/manager/src/pages/page-users.ts
index 50318e035..6ae6d2246 100644
--- a/ui/app/manager/src/pages/page-users.ts
+++ b/ui/app/manager/src/pages/page-users.ts
@@ -208,10 +208,6 @@ export class PageUsers extends Page<AppStateKeyed> {
@state()
protected _realmRoles: Role[] = [];
- protected _realmRolesFilter = (role: Role) => {
- return role.name === "admin" || (!role.composite && !["uma_authorization", "offline_access", "create-realm"].includes(role.name) && !role.name.startsWith("default-roles"))
- };
-
@state()
protected _compositeRoles: Role[] = [];
protected _loading: boolean = false;
@@ -439,7 +435,7 @@ export class PageUsers extends Page<AppStateKeyed> {
}
const compositeRoleOptions: string[] = this._compositeRoles.map(cr => cr.name);
- const realmRoleOptions: [string, string][] = this._realmRoles ? this._realmRoles.filter(r => this._realmRolesFilter(r)).map(r => [r.name, i18next.t("realmRole." + r.name, Util.camelCaseToSentenceCase(r.name.replace("_", " ").replace("-", " ")))]) : [];
+ const realmRoleOptions: [string, string][] = this._realmRoles ? this._realmRoles.filter(r => Util.realmRoleFilter(r)).map(r => [r.name, i18next.t("realmRole." + r.name, Util.camelCaseToSentenceCase(r.name.replace("_", " ").replace("-", " ")))]) : [];
const readonly = !manager.hasRole(ClientRole.WRITE_ADMIN);
// Content of User Table
@@ -877,13 +873,13 @@ export class PageUsers extends Page<AppStateKeyed> {
<or-mwc-input
?readonly="${readonly}"
?disabled="${isSameUser}"
- .value="${user.realmRoles && user.realmRoles.length > 0 ? user.realmRoles.filter(r => this._realmRolesFilter(r)).map(r => r.name) : undefined}"
+ .value="${user.realmRoles && user.realmRoles.length > 0 ? user.realmRoles.filter(r => Util.realmRoleFilter(r)).map(r => r.name) : undefined}"
.type="${InputType.SELECT}" multiple
.options="${realmRoleOptions}"
.label="${i18next.t("realm_role_plural")}"
@or-mwc-input-changed="${(e: OrInputChangedEvent) => {
const roleNames = e.detail.value as string[];
- const excludedAndCompositeRoles = user.realmRoles.filter(r => !this._realmRolesFilter(r));
+ const excludedAndCompositeRoles = user.realmRoles.filter(r => !Util.realmRoleFilter(r));
const selectedRoles = this._realmRoles.filter(cr => roleNames.some(name => cr.name === name)).map(r => {
return {...r, assigned: true} as Role;
});
diff --git a/ui/component/core/src/util.ts b/ui/component/core/src/util.ts
index 3abd7de7a..31d8d5b40 100644
--- a/ui/component/core/src/util.ts
+++ b/ui/component/core/src/util.ts
@@ -22,6 +22,7 @@ import {
AbstractNameValueDescriptorHolder,
MetaItemDescriptor,
ValueFormatStyleRepresentation,
+ Role,
} from "@openremote/model";
import i18next from "i18next";
import Qs from "qs";
@@ -1070,3 +1071,7 @@ export function blobToBase64(blob:Blob) {
};
});
}
+
+export function realmRoleFilter(role: Role) {
+ return role.name === "admin" || (!role.composite && !["uma_authorization", "offline_access", "create-realm"].includes(role.name!) && !role.name!.startsWith("default-roles"));
+}
diff --git a/ui/component/model/build.gradle b/ui/component/model/build.gradle
index 9904e1d17..cb6864a0f 100644
--- a/ui/component/model/build.gradle
+++ b/ui/component/model/build.gradle
@@ -39,7 +39,6 @@ generateTypeScript {
"org.openremote.model.util.**",
"org.openremote.model.flow.**",
"java.io.**",
- "java.lang.**",
"org.hibernate.**",
"com.vladmihalcea.**",
"jakarta.**"
diff --git a/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts b/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts
index 86abb59db..79f416a42 100644
--- a/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts
+++ b/ui/component/or-dashboard-builder/src/or-dashboard-widget.ts
@@ -51,7 +51,7 @@ export class OrDashboardWidget extends LitElement {
// Update config if some values in the spec are not set.
// Useful for when migrations have taken place.
if(this.widget) {
- const widgetType = widgetTypes.get(this.widget.widgetTypeId);
+ const widgetType = widgetTypes.get(this.widget.widgetTypeId!);
if(widgetType) {
this.widget.widgetConfig = widgetType.verifyConfigSpec(this.widget);
}
@@ -107,7 +107,7 @@ export class OrDashboardWidget extends LitElement {
const _widget = Object.assign({}, widget);
if(_widget.gridItem) {
- const widgetEntity = widgetTypes.get(widget.widgetTypeId);
+ const widgetEntity = widgetTypes.get(widget.widgetTypeId!);
return widgetEntity!.getWidgetHTML(this.widget!, this.editMode!, this.realm!);
}
diff --git a/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.ts b/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.ts
index eeb01cc29..fcb83349c 100644
--- a/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.ts
+++ b/ui/component/or-dashboard-builder/src/widgets/or-chart-widget.ts
@@ -170,7 +170,7 @@ export class OrChartWidgetContent extends LitElement {
this.assetAttributes = this.widget?.widgetConfig.attributeRefs.map((attrRef: AttributeRef) => {
const assetIndex = assets!.findIndex((asset) => asset.id === attrRef.id);
const foundAsset = assetIndex >= 0 ? assets![assetIndex] : undefined;
- return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name]] : undefined;
+ return foundAsset && foundAsset.attributes ? [assetIndex, foundAsset.attributes[attrRef.name!]] : undefined;
}).filter((indexAndAttr: any) => !!indexAndAttr) as [number, Attribute<any>][];
});
}
@@ -212,9 +212,9 @@ export class OrChartWidgetContent extends LitElement {
// Generating random coordinates on the chart
let data: any[] = [];
- const cached: { period: any, data: any[] } | undefined = this.cachedMockData?.get(widget.id);
+ const cached: { period: any, data: any[] } | undefined = this.cachedMockData?.get(widget.id!);
if(cached && (cached.data.length == widget.widgetConfig?.attributeRefs?.length) && (cached.period == widget.widgetConfig?.period)) {
- data = this.cachedMockData?.get(widget.id)!.data!;
+ data = this.cachedMockData?.get(widget.id!)!.data!;
} else {
widget.widgetConfig?.attributeRefs?.forEach((_attrRef: AttributeRef) => {
let valueEntries: any[] = [];
@@ -229,7 +229,7 @@ export class OrChartWidgetContent extends LitElement {
}
data.push(valueEntries);
});
- this.cachedMockData?.set(widget.id, { period: widget.widgetConfig?.period, data: data });
+ this.cachedMockData?.set(widget.id!, { period: widget.widgetConfig?.period, data: data });
}
// Making a line for each attribute
diff --git a/ui/component/or-gauge/src/index.ts b/ui/component/or-gauge/src/index.ts
index 77caa83a0..e45f285e6 100644
--- a/ui/component/or-gauge/src/index.ts
+++ b/ui/component/or-gauge/src/index.ts
@@ -175,7 +175,7 @@ export class OrGauge extends LitElement {
willUpdate(changedProps: Map<string, any>) {
if(changedProps.has('assetAttribute')) {
const attr = this.assetAttribute![1];
- const attributeDescriptor = AssetModelUtil.getAttributeDescriptor(attr.name, this.asset!.type);
+ const attributeDescriptor = AssetModelUtil.getAttributeDescriptor(attr.name!, this.asset!.type!);
this.unit = Util.resolveUnits(Util.getAttributeUnits(attr, attributeDescriptor, this.asset!.type));
this.value = attr.value != null ? attr.value : NaN;
}
@@ -299,12 +299,12 @@ export class OrGauge extends LitElement {
}
async loadData(attrRef: AttributeRef) {
- const response = await manager.rest.api.AssetResource.queryAssets({ ids: [attrRef.id] });
+ const response = await manager.rest.api.AssetResource.queryAssets({ ids: [attrRef.id!] });
const assets = response.data;
const assetAttributes = [attrRef].map((attrRef) => {
const assetIndex = assets.findIndex((asset) => asset.id === attrRef.id);
const asset = assetIndex >= 0 ? assets[assetIndex] : undefined;
- return asset && asset.attributes ? [assetIndex, asset.attributes[attrRef.name]] : undefined;
+ return asset && asset.attributes ? [assetIndex, asset.attributes[attrRef.name!]] : undefined;
}).filter((indexAndAttr) => !!indexAndAttr) as [number, Attribute<any>][];
this.asset = assets[0];
diff --git a/ui/component/or-icon/package.json b/ui/component/or-icon/package.json
index f03b47d47..e9e8cfb38 100644
--- a/ui/component/or-icon/package.json
+++ b/ui/component/or-icon/package.json
@@ -21,7 +21,7 @@
"lit": "^2.0.2"
},
"devDependencies": {
- "@mdi/font": "^6.5.95",
+ "@mdi/font": "latest",
"terser-webpack-plugin": "^5.2.5",
"typescript": ">=4.5.2",
"webpack": "^5.76.0",
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts b/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts
index ca3197b62..dc3bc0303 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-action-notification.ts
@@ -122,17 +122,41 @@ export class OrRuleActionNotification extends LitElement {
let value: string | undefined;
if (targetType === NotificationTargetType.USER) {
- targetValuesGenerator = manager.rest.api.UserResource.query({realm: manager.displayRealm} as UserQuery).then(
- (usersResponse) => usersResponse.data.map((user) => [user.id!, user.username!])
+ // Get users excluding system accounts and service users
+ const query: UserQuery = {
+ realmPredicate: {name: manager.displayRealm},
+ select: {basic: true},
+ serviceUsers: false,
+ attributes: [{name: {value: "systemAccount", predicateType: "string"}, negated: true}]
+ }
+ targetValuesGenerator = manager.rest.api.UserResource.query(query).then(
+ async (usersResponse) => {
+ const linkedLabel = i18next.t("linked");
+
+ // Get realm roles and add as options
+ const realm = await manager.rest.api.RealmResource.get(manager.displayRealm);
+ let realmRoleOpts: [string, string][] = realm.data.realmRoles!.filter(r => Util.realmRoleFilter(r)).map(r => ["linked-" + r.name!, linkedLabel + ": " + i18next.t("realmRole." + r.name, Util.camelCaseToSentenceCase(r.name!.replace("_", " ").replace("-", " ")))]);
+ let values: [string, string][] = usersResponse.data.map((user) => [user.id!, user.username!]);
+ return [["linkedUsers", linkedLabel], ...realmRoleOpts, ...values];
+ }
);
label = i18next.t("user_plural");
+ const userQuery = action.target!.users!;
- if (action.target!.users) {
- const userQuery = action.target!.users!;
-
+ if (action.target!.linkedUsers) {
+ if (userQuery && userQuery.realmRoles) {
+ if (userQuery.realmRoles.length > 1) {
+ console.warn("Rule action user target query is unsupported: " + JSON.stringify(userQuery, null, 2));
+ return;
+ }
+ value = "linked-" + userQuery.realmRoles[0].value;
+ } else {
+ value = "linkedUsers";
+ }
+ } else if (userQuery) {
if ((userQuery.ids && userQuery.ids.length > 1)
|| userQuery.usernames
- || userQuery.assetPredicate
+ || userQuery.assets
|| userQuery.limit
|| userQuery.pathPredicate
|| userQuery.realmPredicate) {
@@ -143,8 +167,9 @@ export class OrRuleActionNotification extends LitElement {
if (userQuery.ids && userQuery.ids.length === 1) {
value = userQuery.ids[0];
}
- } else if (action.target!.linkedUsers) {
- value = "linkedUsers";
+ } else {
+ console.warn("Rule action user target query is unsupported: " + JSON.stringify(userQuery, null, 2));
+ return;
}
} else {
@@ -154,7 +179,20 @@ export class OrRuleActionNotification extends LitElement {
};
targetValuesGenerator = manager.rest.api.AssetResource.queryAssets(assetQuery).then(
- (response) => response.data.map((asset) => [asset.id!, asset.name! + " (" + asset.id! + ")"])
+ (response) => {
+ let values: [string, string][] = response.data.map((asset) => [asset.id!, asset.name! + " (" + asset.id! + ")"]);
+
+ // Add additional options for assets
+ const additionalValues: [string, string][] = [["allMatched", i18next.t("matched")]];
+ if (targetTypeMap && targetTypeMap.length > 1) {
+ targetTypeMap.forEach((typeAndTag) => {
+ if (!additionalValues.find((av) => av[0] === typeAndTag[0])) {
+ additionalValues.push([typeAndTag[0], i18next.t("matchedOfType", {type: Util.getAssetTypeLabel(typeAndTag[0])})]);
+ }
+ });
+ }
+ return [...additionalValues, ...values];
+ }
);
label = i18next.t("asset_plural");
if (!action.target) {
@@ -186,22 +224,6 @@ export class OrRuleActionNotification extends LitElement {
targetValueTemplate = targetValuesGenerator.then((values) => {
- // Add additional options for assets
- if (targetType === NotificationTargetType.ASSET) {
- const additionalValues: [string, string][] = [["allMatched", i18next.t("matched")]];
- if (targetTypeMap && targetTypeMap.length > 1) {
- targetTypeMap.forEach((typeAndTag) => {
- if (!additionalValues.find((av) => av[0] === typeAndTag[0])) {
- additionalValues.push([typeAndTag[0], i18next.t("matchedOfType", {type: Util.getAssetTypeLabel(typeAndTag[0])})]);
- }
- });
- }
- values = [...additionalValues, ...values];
- } else if (targetType === NotificationTargetType.USER) {
- // Add additional option for linked users
- values = [["linkedUsers", i18next.t("linked")], ...values];
- }
-
return html`
<or-mwc-input type="${InputType.SELECT}"
class="min-width"
@@ -320,6 +342,18 @@ export class OrRuleActionNotification extends LitElement {
this.action.target = {
linkedUsers: true
}
+ } else if (value?.startsWith("linked-")) {
+ this.action.target = {
+ users: {
+ realmRoles: [
+ {
+ predicateType: "string",
+ value: value?.substring(7)
+ }
+ ]
+ },
+ linkedUsers: true
+ }
} else if (value) {
this.action.target = {
users: {ids: [value]}
diff --git a/yarn.lock b/yarn.lock
index 99b547679..ba956faa9 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2096,10 +2096,10 @@ __metadata:
languageName: node
linkType: hard
-"@mdi/font@npm:^6.5.95":
- version: 6.6.96
- resolution: "@mdi/font@npm:6.6.96"
- checksum: d305fa4a9e572cfebc148676d80f4d193dfc423850c8172c0585ceda6e0e041ea0eed26b2aed444d0e51bba419b7085452484cfaa5463de0ee58666982e1c5b9
+"@mdi/font@npm:latest":
+ version: 7.2.96
+ resolution: "@mdi/font@npm:7.2.96"
+ checksum: f193bb99175e723864a7fd4010594637395a77c8011668f65856aa65abd70848239ab8642fe8aabb0f57f0ffe513a32687fddcd1a927f5aa6c7329b8d8c13e75
languageName: node
linkType: hard
@@ -2502,7 +2502,7 @@ __metadata:
version: 0.0.0-use.local
resolution: "@openremote/or-icon@workspace:ui/component/or-icon"
dependencies:
- "@mdi/font": ^6.5.95
+ "@mdi/font": latest
lit: ^2.0.2
terser-webpack-plugin: ^5.2.5
typescript: ">=4.5.2"