Skip to content

armgit / core

Public Imported from GitHub
0

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

Work on startup using stored credentials

Rich Turner20fef5f3cd48
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIoClient.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIoClient.java
index 877233ec6..d6c73cd53 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIoClient.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIoClient.java
@@ -270,8 +270,7 @@ public class WebsocketIoClient<T> extends AbstractNettyIoClient<T, InetSocketAdd
ResteasyClient client = createClient(executorService, 1, CONNECTION_TIMEOUT_MILLISECONDS, null);
try {
- WebTarget authTarget = client.target(oAuthGrant.getTokenEndpointUri());
- OAuthFilter oAuthFilter = new OAuthFilter(authTarget, oAuthGrant);
+ OAuthFilter oAuthFilter = new OAuthFilter(client, oAuthGrant);
authHeaderValue = oAuthFilter.getAuthHeader();
if (TextUtil.isNullOrEmpty(authHeaderValue)) {
throw new RuntimeException("Returned access token is null");
diff --git a/container/src/main/java/org/openremote/container/security/IdentityService.java b/container/src/main/java/org/openremote/container/security/IdentityService.java
index 941ad0f1a..4f982e6cf 100644
--- a/container/src/main/java/org/openremote/container/security/IdentityService.java
+++ b/container/src/main/java/org/openremote/container/security/IdentityService.java
@@ -58,7 +58,6 @@ public abstract class IdentityService implements ContainerService {
@Override
public void init(Container container) throws Exception {
devMode = container.isDevMode();
-
String identityProviderType = getString(container.getConfig(), IDENTITY_PROVIDER, IDENTITY_PROVIDER_DEFAULT);
identityProvider = createIdentityProvider(container, identityProviderType);
identityProvider.init(container);
diff --git a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
index 75acea43a..2b61522d4 100644
--- a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
+++ b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
@@ -43,14 +43,15 @@ import org.openremote.container.web.WebService;
import org.openremote.container.web.WebTargetBuilder;
import org.openremote.model.Container;
import org.openremote.model.auth.OAuthGrant;
+import org.openremote.model.auth.OAuthPasswordGrant;
import javax.ws.rs.NotFoundException;
-import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
@@ -64,8 +65,7 @@ import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL;
import static org.openremote.container.util.MapAccess.*;
import static org.openremote.container.web.WebClient.getTarget;
import static org.openremote.container.web.WebService.pathStartsWithHandler;
-import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID;
-import static org.openremote.model.Constants.REQUEST_HEADER_REALM;
+import static org.openremote.model.Constants.*;
public abstract class KeycloakIdentityProvider implements IdentityProvider {
@@ -73,11 +73,13 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
// an access token from authentication directly, which gives us full access to import/delete
// demo data as needed.
public static final String ADMIN_CLI_CLIENT_ID = "admin-cli";
+ public static final String MANAGER_CLIENT_ID = "manager-keycloak";
public static final List<String> DEFAULT_CLIENTS = Arrays.asList(
"account",
ADMIN_CLI_CLIENT_ID,
"broker",
"master-realm",
+ MANAGER_CLIENT_ID,
"security-admin-console");
public static final String KEYCLOAK_HOST = "KEYCLOAK_HOST";
@@ -116,6 +118,7 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
// The client we use to access Keycloak
protected ResteasyClient httpClient;
protected ResteasyWebTarget keycloakTarget;
+ protected OAuthGrant oAuthGrant;
protected ConcurrentLinkedQueue<RealmsResource> realmsResourcePool = new ConcurrentLinkedQueue<>();
// Cache Keycloak deployment per realm/client so we don't have to access Keycloak for every token validation
protected LoadingCache<KeycloakRealmClient, KeycloakDeployment> keycloakDeploymentCache;
@@ -123,19 +126,32 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
protected KeycloakConfigResolver keycloakConfigResolver;
// Optional reverse proxy that listens to KEYCLOAK_AUTH_PATH and forwards requests to Keycloak (used in dev mode to allow same url to be used for manager and keycloak) - handled by proxy in production
protected HttpHandler authProxyHandler;
- protected OAuthGrant oAuthGrant;
/**
* The supplied {@link OAuthGrant} will be used to authenticate with keycloak so we can programmatically make changes.
* It must be credentials for the master realm for a user with `admin` role so that they can perform CRUD on realms,
* clients and users.
*/
- protected KeycloakIdentityProvider(OAuthGrant oAuthGrant) {
- this.oAuthGrant = oAuthGrant;
+ protected KeycloakIdentityProvider() {
+ }
+
+ public OAuthGrant getDefaultKeycloakGrant(Container container) {
+ return new OAuthPasswordGrant(
+ getTokenUri(MASTER_REALM).toString(),
+ ADMIN_CLI_CLIENT_ID,
+ null,
+ "openid",
+ MASTER_REALM_ADMIN_USER,
+ container.getConfig().getOrDefault(SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)
+ );
}
@Override
public void init(Container container) {
+ if (httpClient != null) {
+ return;
+ }
+
boolean identityNetworkSecure = getBoolean(container.getConfig(), IDENTITY_NETWORK_SECURE, IDENTITY_NETWORK_SECURE_DEFAULT);
String identityNetworkHost = getString(container.getConfig(), IDENTITY_NETWORK_HOST, IDENTITY_NETWORK_HOST_DEFAULT);
int identityNetworkPort = getInteger(container.getConfig(), IDENTITY_NETWORK_WEBSERVER_PORT, IDENTITY_NETWORK_WEBSERVER_PORT_DEFAULT);
@@ -149,8 +165,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
externalServerUri = externalServerUri.port(identityNetworkPort);
}
- LOG.info("External system base URL: " + externalServerUri.build());
-
sessionMaxSeconds = getInteger(container.getConfig(), IDENTITY_SESSION_MAX_MINUTES, IDENTITY_SESSION_MAX_MINUTES_DEFAULT) * 60;
if (sessionMaxSeconds < 60) {
throw new IllegalArgumentException(IDENTITY_SESSION_MAX_MINUTES + " must be more than 1 minute");
@@ -164,6 +178,7 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
throw new IllegalArgumentException(IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES + " must be more than 1 minute");
}
+ LOG.info("External system base URL: " + externalServerUri.build());
keycloakServiceUri =
UriBuilder.fromPath("/")
.scheme("http")
@@ -188,8 +203,7 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
);
httpClient = WebClient.registerDefaults(clientBuilder).build();
- // Generate the keycloak proxy for
- updateCredentials(oAuthGrant);
+ setActiveCredentials(getDefaultKeycloakGrant(container));
keycloakDeploymentCache = createKeycloakDeploymentCache();
@@ -232,19 +246,6 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
httpClient.close();
}
- /**
- * Update the credentials used to interact with keycloak; the token endpoint will be overwritten with this instances
- * keycloak server URI and for the master realm.
- */
- public void updateCredentials(OAuthGrant grant) {
- this.oAuthGrant = grant;
- // Force token endpoint to master realm as this is the realm we need to be in to do keycloak CRUD
- oAuthGrant.setTokenEndpointUri(getTokenUri("master").toString());
- WebTargetBuilder targetBuilder = new WebTargetBuilder(httpClient, keycloakServiceUri.build());
- targetBuilder.setOAuthAuthentication(grant);
- keycloakTarget = targetBuilder.build();
- }
-
@Override
public void secureDeployment(DeploymentInfo deploymentInfo) {
LoginConfig loginConfig = new LoginConfig(SimpleKeycloakServletExtension.AUTH_MECHANISM, "OpenRemote");
@@ -264,25 +265,31 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
});
}
- final protected <T> T getRealms(Function<RealmsResource, T> consumer) {
+ final synchronized protected <T> T getRealms(Function<RealmsResource, T> consumer) {
RealmsResource realmsResource;
-
+ ResteasyWebTarget target = keycloakTarget; // Track this in case active credentials updated
if ((realmsResource = realmsResourcePool.poll()) == null) {
realmsResource = keycloakTarget.proxy(RealmsResource.class);
}
try {
return consumer.apply(realmsResource);
} finally {
- realmsResourcePool.offer(realmsResource);
+ if (target == this.keycloakTarget) {
+ realmsResourcePool.offer(realmsResource);
+ }
}
}
protected void waitForKeycloak() {
boolean keycloakAvailable = false;
+ WebTargetBuilder targetBuilder = new WebTargetBuilder(httpClient, keycloakServiceUri.build());
+ ResteasyWebTarget target = targetBuilder.build();
+ KeycloakResource keycloakResource = target.proxy(KeycloakResource.class);
+
while (!keycloakAvailable) {
LOG.info("Connecting to Keycloak server: " + keycloakServiceUri.build());
try {
- pingKeycloak();
+ pingKeycloak(keycloakResource);
keycloakAvailable = true;
} catch (Exception ex) {
LOG.info("Keycloak server not available, waiting...");
@@ -295,10 +302,11 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
}
}
- protected void pingKeycloak() throws Exception {
+ protected void pingKeycloak(KeycloakResource resource) throws Exception {
Response response = null;
+
try {
- response = getKeycloak().getWelcomePage();
+ response = resource.getWelcomePage();
if (response != null &&
(response.getStatusInfo().getFamily() == SUCCESSFUL
|| response.getStatusInfo().getFamily() == REDIRECTION)) {
@@ -337,8 +345,7 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
* Convenience method for generating access tokens from a given OAuth compliant server
*/
public Supplier<String> getAccessTokenSupplier(OAuthGrant grant) {
- WebTarget authTarget = httpClient.target(grant.getTokenEndpointUri());
- OAuthFilter oAuthFilter = new OAuthFilter(authTarget, grant);
+ OAuthFilter oAuthFilter = new OAuthFilter(httpClient, grant);
return () -> {
try {
return oAuthFilter.getAccessToken();
@@ -349,6 +356,30 @@ public abstract class KeycloakIdentityProvider implements IdentityProvider {
};
}
+ /**
+ * Update the active credentials used to interact with keycloak; the token endpoint will be overwritten with this
+ * instances keycloak server URI and for the master realm.
+ */
+ public synchronized void setActiveCredentials(OAuthGrant grant) {
+
+ if (Objects.equals(this.oAuthGrant, grant)) {
+ return;
+ }
+
+ this.oAuthGrant = grant;
+
+ // Force token endpoint to master realm as this is the realm we need to be in to do full keycloak CRUD
+ if (grant != null) {
+ grant.setTokenEndpointUri(getTokenUri("master").toString());
+ }
+
+ WebTargetBuilder targetBuilder = new WebTargetBuilder(httpClient, keycloakServiceUri.build())
+ .setOAuthAuthentication(grant);
+ keycloakTarget = targetBuilder.build();
+ realmsResourcePool.clear();
+ LOG.info("Keycloak proxy credentials set to: " + grant);
+ }
+
protected LoadingCache<KeycloakRealmClient, KeycloakDeployment> createKeycloakDeploymentCache() {
CacheLoader<KeycloakRealmClient, KeycloakDeployment> loader =
new CacheLoader<KeycloakRealmClient, KeycloakDeployment>() {
diff --git a/container/src/main/java/org/openremote/container/web/OAuthFilter.java b/container/src/main/java/org/openremote/container/web/OAuthFilter.java
index 251e888c6..905dc2eeb 100644
--- a/container/src/main/java/org/openremote/container/web/OAuthFilter.java
+++ b/container/src/main/java/org/openremote/container/web/OAuthFilter.java
@@ -19,6 +19,7 @@
*/
package org.openremote.container.web;
+import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.util.BasicAuthHelper;
import org.openremote.model.auth.OAuthGrant;
import org.openremote.model.auth.OAuthRefreshTokenGrant;
@@ -46,13 +47,15 @@ public class OAuthFilter implements ClientRequestFilter {
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, OAuthFilter.class);
public static final String BEARER_AUTH = "Bearer";
protected OAuthServerResponse authServerResponse;
+ protected ResteasyClient client;
protected WebTarget authTarget;
protected OAuthGrant oAuthGrant;
- public OAuthFilter(WebTarget authTarget, OAuthGrant oAuthGrant) {
- Objects.requireNonNull(authTarget);
+ public OAuthFilter(ResteasyClient client, OAuthGrant oAuthGrant) {
+ Objects.requireNonNull(client);
Objects.requireNonNull(oAuthGrant);
- this.authTarget = authTarget;
+ this.client = client;
+ this.authTarget = client.target(oAuthGrant.getTokenEndpointUri());
this.oAuthGrant = oAuthGrant;
}
@@ -138,6 +141,12 @@ public class OAuthFilter implements ClientRequestFilter {
return builder.post(Entity.entity(new Form(oAuthGrant.asMultivaluedMap()), MediaType.APPLICATION_FORM_URLENCODED_TYPE));
}
+ public synchronized void updateGrant(OAuthGrant grant) {
+ this.authServerResponse = null;
+ this.oAuthGrant = grant;
+ this.authTarget = client.target(oAuthGrant.getTokenEndpointUri());
+ }
+
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
requestContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, getAuthHeader());
diff --git a/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java b/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java
index 853692510..79c96575a 100644
--- a/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java
+++ b/container/src/main/java/org/openremote/container/web/WebTargetBuilder.java
@@ -153,8 +153,7 @@ public class WebTargetBuilder {
}
if (oAuthGrant != null) {
- WebTarget authTarget = client.target(oAuthGrant.getTokenEndpointUri());
- OAuthFilter oAuthFilter = new OAuthFilter(authTarget, oAuthGrant);
+ OAuthFilter oAuthFilter = new OAuthFilter(client, oAuthGrant);
target.register(oAuthFilter, Priorities.AUTHENTICATION);
} else if (basicAuthentication != null) {
target.register(basicAuthentication, Priorities.AUTHENTICATION);
diff --git a/manager/Dockerfile b/manager/Dockerfile
index beff9eb6a..dd0b340e0 100644
--- a/manager/Dockerfile
+++ b/manager/Dockerfile
@@ -62,6 +62,7 @@ ENV DB_MAX_POOL_SIZE ${DB_MAX_POOL_SIZE:-20}
ENV DB_CONNECTION_TIMEOUT_SECONDS ${DB_CONNECTION_TIMEOUT_SECONDS:-300}
ENV KEYCLOAK_HOST ${KEYCLOAK_HOST:-keycloak}
ENV KEYCLOAK_PORT ${KEYCLOAK_PORT:-8080}
+ENV KEYCLOAK_GRANT_FILE ${KEYCLOAK_GRANT_FILE:-/deployment/manager/keycloak.json}
ENV APP_DOCROOT ${APP_DOCROOT:-/opt/web}
ENV CUSTOM_APP_DOCROOT ${CUSTOM_APP_DOCROOT:-/deployment/manager/app}
ENV PROVISIONING_DOCROOT ${PROVISIONING_DOCROOT:-/deployment/manager/provisioning}
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 a733b2e5c..721bf2eb3 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerBasicIdentityProvider.java
@@ -31,10 +31,7 @@ import org.openremote.model.security.*;
import org.openremote.model.util.TextUtil;
import java.sql.PreparedStatement;
-import java.util.List;
-import java.util.Objects;
-import java.util.Set;
-import java.util.UUID;
+import java.util.*;
import java.util.logging.Logger;
import static org.openremote.model.Constants.MASTER_REALM;
@@ -165,7 +162,7 @@ public class ManagerBasicIdentityProvider extends BasicIdentityProvider implemen
}
@Override
- public String resetSecret(String realm, String userId) {
+ public String resetSecret(String realm, String userId, String secret) {
throw new UnsupportedOperationException("This provider does not support secret reset");
}
@@ -179,6 +176,10 @@ public class ManagerBasicIdentityProvider extends BasicIdentityProvider implemen
.toArray(Role[]::new);
}
+ public void updateUserAttributes(String realm, String userId, Map<String, List<String>> attributes) {
+ throw new UnsupportedOperationException("This provider does not support updating attributes");
+ }
+
@Override
public void updateClientRoles(String realm, String client, Role[] roles) {
throw new UnsupportedOperationException("This provider does not support updating 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 dcafd8f38..e5ce52524 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
@@ -32,6 +32,7 @@ import org.openremote.model.util.TextUtil;
import javax.persistence.TypedQuery;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import java.util.stream.IntStream;
import static org.openremote.manager.asset.AssetStorageService.buildMatchFilter;
@@ -62,7 +63,9 @@ public interface ManagerIdentityProvider extends IdentityProvider {
void resetPassword(String realm, String userId, Credential credential);
- String resetSecret(String realm, String userId);
+ String resetSecret(String realm, String userId, String secret);
+
+ void updateUserAttributes(String realm, String userId, Map<String, List<String>> attributes);
Role[] getRoles(String realm, String client);
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
index 39503939d..5cee55ff9 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
@@ -19,37 +19,19 @@
*/
package org.openremote.manager.security;
-import org.apache.commons.io.IOUtils;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.security.IdentityService;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.web.ManagerWebService;
import org.openremote.model.Container;
-import org.openremote.model.auth.OAuthGrant;
-import org.openremote.model.auth.OAuthPasswordGrant;
-import org.openremote.model.util.TextUtil;
-import org.openremote.model.value.Values;
import javax.persistence.EntityManager;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.Locale;
import java.util.logging.Logger;
-import static org.openremote.container.security.IdentityProvider.SETUP_ADMIN_PASSWORD;
-import static org.openremote.container.security.IdentityProvider.SETUP_ADMIN_PASSWORD_DEFAULT;
-import static org.openremote.container.security.keycloak.KeycloakIdentityProvider.ADMIN_CLI_CLIENT_ID;
-import static org.openremote.container.util.MapAccess.getString;
-import static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER;
-
public class ManagerIdentityService extends IdentityService {
private static final Logger LOG = Logger.getLogger(ManagerIdentityService.class.getName());
- public static final String KEYCLOAK_GRANT_FILE = "KEYCLOAK_GRANT_FILE";
- public static final String KEYCLOAK_GRANT_FILE_DEFAULT = "/deployment/manager/keycloak.json";
protected ManagerIdentityProvider identityProvider;
protected PersistenceService persistenceService;
@@ -77,39 +59,7 @@ public class ManagerIdentityService extends IdentityService {
switch (identityProviderType.toLowerCase(Locale.ROOT)) {
case "keycloak":
LOG.info("Enabling Keycloak identity provider");
-
- // Try and load grant from file
- String grantFile = getString(container.getConfig(), KEYCLOAK_GRANT_FILE, KEYCLOAK_GRANT_FILE_DEFAULT);
- Path grantPath = TextUtil.isNullOrEmpty(grantFile) ? null : Paths.get(grantFile);
- OAuthGrant grant = null;
-
- if (grantPath != null && Files.isReadable(grantPath)) {
- LOG.info("Loading KEYCLOAK_GRANT_FILE: " + grantFile);
-
- try (InputStream is = Files.newInputStream(grantPath)) {
- String grantJson = IOUtils.toString(is, StandardCharsets.UTF_8);
- grant = Values.parse(grantJson, OAuthGrant.class).orElseGet(() -> {
- LOG.info("Failed to load KEYCLOAK_GRANT_FILE: " + grantFile);
- return null;
- });
- } catch (Exception ex) {
- throw new ExceptionInInitializerError(ex);
- }
- }
-
- if (grant == null) {
- // Fallback to using admin-cli client
- grant = new OAuthPasswordGrant(
- "dummy", // This will be replaced with the correct endpoint URI
- ADMIN_CLI_CLIENT_ID,
- null,
- "openid",
- MASTER_REALM_ADMIN_USER,
- container.getConfig().getOrDefault(SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)
- );
- }
-
- this.identityProvider = new ManagerKeycloakIdentityProvider(grant);
+ this.identityProvider = new ManagerKeycloakIdentityProvider();
break;
case "basic":
LOG.info("Enabling basic identity provider");
@@ -146,7 +96,6 @@ public class ManagerIdentityService extends IdentityService {
return em.merge(userConfiguration);
}
-
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
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 eb57ba4e9..c03ca1e36 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java
@@ -21,6 +21,7 @@ package org.openremote.manager.security;
import io.undertow.util.Headers;
import org.apache.camel.ExchangePattern;
+import org.apache.commons.io.IOUtils;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.admin.client.resource.*;
import org.keycloak.common.enums.SslRequired;
@@ -32,6 +33,7 @@ import org.openremote.container.security.AuthContext;
import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
import org.openremote.container.timer.TimerService;
import org.openremote.container.web.WebService;
+import org.openremote.container.web.WebTargetBuilder;
import org.openremote.manager.apps.ConsoleAppService;
import org.openremote.manager.event.ClientEventService;
import org.openremote.model.Constants;
@@ -44,6 +46,7 @@ import org.openremote.model.query.filter.StringPredicate;
import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.security.*;
import org.openremote.model.util.TextUtil;
+import org.openremote.model.value.Values;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotAllowedException;
@@ -51,6 +54,12 @@ import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -75,6 +84,8 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
public static final String REALM_KEYCLOAK_THEME_SUFFIX = "_REALM_KEYCLOAK_THEME";
public static final String DEFAULT_REALM_KEYCLOAK_THEME = "DEFAULT_REALM_KEYCLOAK_THEME";
public static final String DEFAULT_REALM_KEYCLOAK_THEME_DEFAULT = "openremote";
+ public static final String KEYCLOAK_GRANT_FILE = "KEYCLOAK_GRANT_FILE";
+ public static final String KEYCLOAK_GRANT_FILE_DEFAULT = "manager/build/keycloak.json";
protected PersistenceService persistenceService;
protected TimerService timerService;
@@ -84,14 +95,17 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
protected String keycloakAdminPassword;
protected Container container;
- public ManagerKeycloakIdentityProvider(OAuthGrant grant) {
- super(grant);
- }
-
@Override
public void init(Container container) {
super.init(container);
this.container = container;
+ OAuthGrant grant = loadCredentials();
+
+ // Update the keycloak proxy credentials to use stored credentials
+ if (grant != null) {
+ setActiveCredentials(grant);
+ }
+
this.keycloakAdminPassword = container.getConfig().getOrDefault(SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT);
this.timerService = container.getService(TimerService.class);
this.persistenceService = container.getService(PersistenceService.class);
@@ -126,13 +140,19 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
return getRealms(realmsResource -> {
// Need to load secrets from client resource
return Arrays.stream(users).filter(user -> {
- user.setServiceAccount(true);
- ClientsResource clientsResource = realmsResource.realm(realm).clients();
+ RealmResource realmResource = realmsResource.realm(realm);
+ ClientsResource clientsResource = realmResource.clients();
List<ClientRepresentation> clients = clientsResource.findByClientId(user.getUsername());
+ // Filter out system service accounts
+ UserRepresentation userRepresentation = realmResource.users().get(user.getId()).toRepresentation();
+ if (userRepresentation.getAttributes() != null && userRepresentation.getAttributes().containsKey(User.SYSTEM_ACCOUNT_ATTRIBUTE)) {
+ return false;
+ }
+
if (clients != null && !clients.isEmpty()) {
ClientRepresentation client = clients.get(0);
- CredentialRepresentation credentialRepresentation = realmsResource.realm(realm).clients()
+ CredentialRepresentation credentialRepresentation = realmResource.clients()
.get(client.getId()).getSecret();
if (credentialRepresentation != null) {
user.setSecret(credentialRepresentation.getValue());
@@ -197,7 +217,6 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
if (userRepresentation != null) {
existingUser = convert(userRepresentation, User.class);
- existingUser.setServiceAccount(true);
} else if (clientRepresentation != null) {
String msg = "Attempt to update/creat service user but a regular client with same client ID as this username already exists: User=" + user;
LOG.info(msg);
@@ -274,16 +293,19 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
if (passwordSecret != null) {
if (user.isServiceAccount()) {
- resetSecret(realm, userRepresentation.getId());
+ resetSecret(realm, userRepresentation.getId(), passwordSecret);
} else {
Credential credential = new Credential(passwordSecret, false);
resetPassword(realm, userRepresentation.getId(), credential);
}
}
+ if (user.getAttributes() != null) {
+ updateUserAttributes(realm, userRepresentation.getId(), user.getAttributes());
+ }
+
User updatedUser = convert(userRepresentation, User.class);
if (updatedUser != null) {
- user.setServiceAccount(userRepresentation.getUsername().startsWith(User.SERVICE_ACCOUNT_PREFIX));
updatedUser.setRealm(realm);
}
return updatedUser;
@@ -326,7 +348,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
}
@Override
- public String resetSecret(String realm, String userId) {
+ public String resetSecret(String realm, String userId, String secret) {
return getRealms(realmsResource -> {
UserRepresentation userRepresentation = realmsResource.realm(realm).users().get(userId).toRepresentation();
if (userRepresentation == null) {
@@ -338,13 +360,15 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
if (!clients.isEmpty()) {
ClientRepresentation client = clients.get(0);
+ ClientResource clientResource = realmsResource.realm(realm).clients().get(client.getId());
- CredentialRepresentation credentialRepresentation = realmsResource.realm(realm).clients()
- .get(client.getId())
- .generateNewSecret();
-
- if (credentialRepresentation != null) {
+ if (TextUtil.isNullOrEmpty(secret)) {
+ CredentialRepresentation credentialRepresentation = clientResource.generateNewSecret();
return credentialRepresentation.getValue();
+ } else {
+ client.setSecret(secret);
+ clientResource.update(client);
+ return secret;
}
}
@@ -352,21 +376,38 @@ 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 Role[] getRoles(String realm, String client) {
return getRealms(realmsResource -> {
RealmResource realmResource = realmsResource.realm(realm);
ClientsResource clientsResource = realmResource.clients();
- ClientRepresentation clientRepresentation = getClient(realm, client);
- if (clientRepresentation == null) {
- throw new IllegalStateException("Cannot find specified client: " + client);
+ ClientResource clientResource = null;
+
+ if (client != null) {
+ ClientRepresentation clientRepresentation = getClient(realm, client);
+
+ if (clientRepresentation == null) {
+ throw new IllegalStateException("Cannot find specified client: " + client);
+ }
+ clientResource = clientsResource.get(clientRepresentation.getId());
}
- ClientResource clientResource = clientsResource.get(clientRepresentation.getId());
- List<RoleRepresentation> clientRoles = clientResource.roles().list();
+
+ List<RoleRepresentation> roleRepresentations = clientResource != null ? clientResource.roles().list() : realmResource.roles().list();
List<Role> roles = new ArrayList<>();
- for (RoleRepresentation clientRole : clientRoles) {
- String[] composites = clientRole.isComposite() ? realmResource.rolesById().getClientRoleComposites(clientRole.getId(), clientRepresentation.getId()).stream().map(RoleRepresentation::getId).toArray(String[]::new) : null;
+ for (RoleRepresentation clientRole : roleRepresentations) {
+ String[] composites = clientRole.isComposite() ? realmResource.rolesById().getRoleComposites(clientRole.getId()).stream().map(RoleRepresentation::getId).toArray(String[]::new) : null;
roles.add(new Role(clientRole.getId(), clientRole.getName(), clientRole.isComposite(), null, composites).setDescription(clientRole.getDescription()));
}
@@ -523,33 +564,45 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
}
RoleMappingResource roleMappingResource = realmResource.users().get(user.getId()).roles();
- ClientRepresentation clientRepresentation = getClient(realm, client);
+ ClientRepresentation clientRepresentation = null;
- if (clientRepresentation == null) {
- throw new IllegalStateException("Invalid client: " + client);
+ if (client != null) {
+ clientRepresentation = getClient(realm, client);
+
+ if (clientRepresentation == null) {
+ throw new IllegalStateException("Invalid client: " + client);
+ }
}
// Get all role mappings for user on this client and remove any no longer in the roles
- List<RoleRepresentation> clientMappedRoles = roleMappingResource.clientLevel(clientRepresentation.getId()).listAll();
- List<RoleRepresentation> availableRoles = roleMappingResource.clientLevel(clientRepresentation.getId()).listAvailable();
+ List<RoleRepresentation> mappedRoles = clientRepresentation != null ? roleMappingResource.clientLevel(clientRepresentation.getId()).listAll() : roleMappingResource.realmLevel().listAll();
+ List<RoleRepresentation> availableRoles = clientRepresentation != null ? roleMappingResource.clientLevel(clientRepresentation.getId()).listAvailable() : roleMappingResource.realmLevel().listAvailable();
// Get newly defined roles
List<RoleRepresentation> addRoles = roles == null ? Collections.emptyList() : Arrays.stream(roles)
- .filter(cr -> clientMappedRoles.stream().noneMatch(r -> r.getName().equals(cr)))
+ .filter(cr -> mappedRoles.stream().noneMatch(r -> r.getName().equals(cr)))
.map(cr -> availableRoles.stream().filter(r -> r.getName().equals(cr)).findFirst().orElse(null))
.filter(Objects::nonNull)
.collect(Collectors.toList());
// Remove obsolete roles
- List<RoleRepresentation> removeRoles = roles == null ? clientMappedRoles : clientMappedRoles.stream()
+ List<RoleRepresentation> removeRoles = roles == null ? mappedRoles : mappedRoles.stream()
.filter(r -> Arrays.stream(roles).noneMatch(cr -> cr.equals(r.getName())))
.collect(Collectors.toList());
if (!removeRoles.isEmpty()) {
- roleMappingResource.clientLevel(clientRepresentation.getId()).remove(removeRoles);
+ if (clientRepresentation != null) {
+ roleMappingResource.clientLevel(clientRepresentation.getId()).remove(removeRoles);
+ } else {
+ roleMappingResource.realmLevel().remove(removeRoles);
+ }
}
if (!addRoles.isEmpty()) {
- roleMappingResource.clientLevel(clientRepresentation.getId()).add(addRoles);
+ if (clientRepresentation != null) {
+ roleMappingResource.clientLevel(clientRepresentation.getId()).add(addRoles);
+ } else {
+ roleMappingResource.realmLevel().add(addRoles);
+ }
}
return null;
@@ -656,6 +709,52 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider im
}
}
+ /**
+ * Load keycloak proxy credentials from file system
+ */
+ public OAuthGrant loadCredentials() {
+ // Try and load keycloak proxy credentials from file
+ String grantFile = getString(container.getConfig(), KEYCLOAK_GRANT_FILE, KEYCLOAK_GRANT_FILE_DEFAULT);
+ Path grantPath = TextUtil.isNullOrEmpty(grantFile) ? null : Paths.get(grantFile);
+ OAuthGrant grant = null;
+
+ if (grantPath != null && Files.isReadable(grantPath)) {
+ LOG.info("Loading KEYCLOAK_GRANT_FILE: " + grantFile);
+
+ try (InputStream is = Files.newInputStream(grantPath)) {
+ String grantJson = IOUtils.toString(is, StandardCharsets.UTF_8);
+ grant = Values.parse(grantJson, OAuthGrant.class).orElseGet(() -> {
+ LOG.info("Failed to load KEYCLOAK_GRANT_FILE: " + grantFile);
+ return null;
+ });
+ } catch (Exception ex) {
+ throw new ExceptionInInitializerError(ex);
+ }
+ }
+ return grant;
+ }
+
+ /**
+ * Save Keycloak proxy credentials to the file system
+ */
+ public void saveCredentials(OAuthGrant grant) {
+ String grantFile = getString(container.getConfig(), KEYCLOAK_GRANT_FILE, KEYCLOAK_GRANT_FILE_DEFAULT);
+
+ if (TextUtil.isNullOrEmpty(grantFile)) {
+ return;
+ }
+ Path grantPath = Paths.get(grantFile);
+
+ try {
+ Files.write(grantPath, Values.asJSON(grant).orElse("null").getBytes(),
+ StandardOpenOption.CREATE,
+ StandardOpenOption.WRITE,
+ StandardOpenOption.TRUNCATE_EXISTING);
+ } catch (Exception e) {
+ LOG.info("Failed to write KEYCLOAK_GRANT_FILE: " + grantFile);
+ }
+ }
+
public ClientRepresentation generateOpenRemoteClientRepresentation() {
ClientRepresentation client = new ClientRepresentation();
client.setClientId(KEYCLOAK_CLIENT_ID);
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 11f28628f..15698ba90 100644
--- a/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java
@@ -147,7 +147,7 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource
@Override
public String resetSecret(RequestParams requestParams, String realm, String userId) {
try {
- return identityService.getIdentityProvider().resetSecret(realm, userId);
+ return identityService.getIdentityProvider().resetSecret(realm, userId, null);
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (Exception ex) {
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 10cdb3a4a..1b66f108b 100644
--- a/manager/src/main/java/org/openremote/manager/setup/KeycloakCleanSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/KeycloakCleanSetup.java
@@ -40,6 +40,17 @@ public class KeycloakCleanSetup extends AbstractKeycloakSetup {
public void onStart() throws Exception {
super.onStart();
+ // Try clean with stored credentials first
+ try {
+ doClean();
+ } catch (Exception e) {
+ // Clear out keycloak auth
+ keycloakProvider.setActiveCredentials(keycloakProvider.getDefaultKeycloakGrant(container));
+ doClean();
+ }
+ }
+
+ protected void doClean() throws Exception {
// Delete all realms that are not the master realm
LOG.info("Deleting all non-master realms");
Arrays.stream(keycloakProvider.getTenants()).forEach(tenant -> {
diff --git a/manager/src/main/java/org/openremote/manager/setup/KeycloakInitSetup.java b/manager/src/main/java/org/openremote/manager/setup/KeycloakInitSetup.java
index fd986931a..e3559580e 100644
--- a/manager/src/main/java/org/openremote/manager/setup/KeycloakInitSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/KeycloakInitSetup.java
@@ -19,13 +19,17 @@
*/
package org.openremote.manager.setup;
+import org.openremote.container.util.UniqueIdentifierGenerator;
import org.openremote.model.Container;
+import org.openremote.model.auth.OAuthClientCredentialsGrant;
+import org.openremote.model.auth.OAuthGrant;
import org.openremote.model.security.ClientRole;
import org.openremote.model.security.Tenant;
import org.openremote.model.security.User;
import java.util.logging.Logger;
+import static org.openremote.container.security.keycloak.KeycloakIdentityProvider.MANAGER_CLIENT_ID;
import static org.openremote.model.Constants.*;
public class KeycloakInitSetup extends AbstractKeycloakSetup {
@@ -59,6 +63,24 @@ public class KeycloakInitSetup extends AbstractKeycloakSetup {
// Give admin all roles on application client level
keycloakProvider.updateUserRoles(MASTER_REALM, adminUser.getId(), KEYCLOAK_CLIENT_ID, ClientRole.READ.getValue(), ClientRole.WRITE.getValue());
+ // Create a service client for this manager to communicate with keycloak so it doesn't use the admin user credentials
+ User keycloakProxyUser = new User().setUsername(MANAGER_CLIENT_ID).setServiceAccount(true).setSystemAccount(true);
+ String secret = UniqueIdentifierGenerator.generateId();
+ // Use credentials from file system if they are available
+ OAuthGrant storedGrant = keycloakProvider.loadCredentials();
+ if (storedGrant != null) {
+ keycloakProxyUser.setUsername(storedGrant.getClientId());
+ secret = storedGrant.getClientSecret() != null ? storedGrant.getClientSecret() : secret;
+ }
+
+ keycloakProxyUser = keycloakProvider.createUpdateUser(MASTER_REALM, keycloakProxyUser, secret);
+
+ // Give this user admin realm role (so they can do realm CRUD)
+ keycloakProvider.updateUserRoles(MASTER_REALM, keycloakProxyUser.getId(), null, "admin");
+
+ OAuthClientCredentialsGrant grant = new OAuthClientCredentialsGrant(keycloakProvider.getTokenUri(MASTER_REALM).toString(), keycloakProxyUser.getUsername(), secret, null);
+ keycloakProvider.setActiveCredentials(grant);
+ keycloakProvider.saveCredentials(grant);
}
}
diff --git a/model/src/main/java/org/openremote/model/auth/OAuthGrant.java b/model/src/main/java/org/openremote/model/auth/OAuthGrant.java
index e1178f51f..b2eb09f5e 100644
--- a/model/src/main/java/org/openremote/model/auth/OAuthGrant.java
+++ b/model/src/main/java/org/openremote/model/auth/OAuthGrant.java
@@ -19,6 +19,7 @@
*/
package org.openremote.model.auth;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@@ -28,6 +29,7 @@ import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import java.io.Serializable;
import java.util.Collections;
+import java.util.Objects;
import static org.openremote.model.util.TextUtil.requireNonNullAndNonEmpty;
@@ -44,6 +46,7 @@ public abstract class OAuthGrant implements Serializable {
public static final String VALUE_KEY_CLIENT_SECRET = "client_secret";
public static final String VALUE_KEY_SCOPE = "scope";
protected String tokenEndpointUri;
+ @JsonIgnore
protected boolean basicAuthHeader;
@JsonProperty(VALUE_KEY_GRANT_TYPE)
protected String grantType;
@@ -111,4 +114,29 @@ public abstract class OAuthGrant implements Serializable {
this.basicAuthHeader = basicAuthHeader;
return this;
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ OAuthGrant grant = (OAuthGrant) o;
+ return basicAuthHeader == grant.basicAuthHeader && Objects.equals(tokenEndpointUri, grant.tokenEndpointUri) && Objects.equals(grantType, grant.grantType) && Objects.equals(clientId, grant.clientId) && Objects.equals(clientSecret, grant.clientSecret) && Objects.equals(scope, grant.scope);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(tokenEndpointUri, basicAuthHeader, grantType, clientId, clientSecret, scope);
+ }
+
+ @Override
+ public String toString() {
+ return OAuthGrant.class.getSimpleName() + "{" +
+ "tokenEndpointUri='" + tokenEndpointUri + '\'' +
+ ", basicAuthHeader=" + basicAuthHeader +
+ ", grantType='" + grantType + '\'' +
+ ", clientId='" + clientId + '\'' +
+ ", clientSecret='" + clientSecret + '\'' +
+ ", scope='" + scope + '\'' +
+ '}';
+ }
}
diff --git a/model/src/main/java/org/openremote/model/auth/OAuthPasswordGrant.java b/model/src/main/java/org/openremote/model/auth/OAuthPasswordGrant.java
index 5887375d8..979b7451e 100644
--- a/model/src/main/java/org/openremote/model/auth/OAuthPasswordGrant.java
+++ b/model/src/main/java/org/openremote/model/auth/OAuthPasswordGrant.java
@@ -25,6 +25,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Collections;
+import java.util.Objects;
@JsonTypeName(OAuthPasswordGrant.PASSWORD_GRANT_TYPE)
public class OAuthPasswordGrant extends OAuthClientCredentialsGrant {
@@ -77,4 +78,32 @@ public class OAuthPasswordGrant extends OAuthClientCredentialsGrant {
valueMap.put(VALUE_KEY_PASSWORD, Collections.singletonList(password));
return valueMap;
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ if (!super.equals(o)) return false;
+ OAuthPasswordGrant that = (OAuthPasswordGrant) o;
+ return Objects.equals(username, that.username) && Objects.equals(password, that.password);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(super.hashCode(), username, password);
+ }
+
+ @Override
+ public String toString() {
+ return OAuthPasswordGrant.class.getSimpleName() + "{" +
+ "tokenEndpointUri='" + tokenEndpointUri + '\'' +
+ ", basicAuthHeader=" + basicAuthHeader +
+ ", grantType='" + grantType + '\'' +
+ ", clientId='" + clientId + '\'' +
+ ", clientSecret='" + clientSecret + '\'' +
+ ", scope='" + scope + '\'' +
+ ", username='" + username + '\'' +
+ ", password='" + password + '\'' +
+ '}';
+ }
}
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 9795bea56..0ddd92dcd 100644
--- a/model/src/main/java/org/openremote/model/security/User.java
+++ b/model/src/main/java/org/openremote/model/security/User.java
@@ -33,6 +33,12 @@ import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.openremote.model.Constants.MASTER_REALM;
/**
* This can be used (among other things) to query the USER_ENTITY table in JPA queries.
@@ -41,6 +47,7 @@ import javax.validation.constraints.Size;
@Subselect("select * from PUBLIC.USER_ENTITY") // Map this immutable to an SQL view, don't use/create table
public class User {
public static final String SERVICE_ACCOUNT_PREFIX = "service-account-";
+ public static final String SYSTEM_ACCOUNT_ATTRIBUTE = "systemAccount";
@Formula("(select r.NAME from PUBLIC.REALM r where r.ID = REALM_ID)")
protected String realm;
@@ -70,6 +77,10 @@ public class User {
@Transient
protected String secret; // For service users
+ @Transient
+ @JsonIgnore
+ protected Map<String, List<String>> attributes;
+
public User() {
}
@@ -128,8 +139,11 @@ public class User {
return username != null && username.startsWith(SERVICE_ACCOUNT_PREFIX);
}
- public User setServiceAccount(boolean serviceAccount) {
+ public Map<String, List<String>> getAttributes() {
+ return attributes;
+ }
+ public User setServiceAccount(boolean serviceAccount) {
if (username != null) {
username = serviceAccount ? SERVICE_ACCOUNT_PREFIX + username.replace(SERVICE_ACCOUNT_PREFIX, "") : username.replace(SERVICE_ACCOUNT_PREFIX, "");
} else {
@@ -138,6 +152,26 @@ public class User {
return this;
}
+ /**
+ * Will hide this user from HTTP API
+ */
+ public User setSystemAccount(boolean systemAccount) {
+
+ if (attributes == null) {
+ attributes = new HashMap<>();
+ }
+
+ if (systemAccount) {
+ attributes.put(User.SYSTEM_ACCOUNT_ATTRIBUTE, Collections.singletonList("true"));
+ } else {
+ attributes.remove(User.SYSTEM_ACCOUNT_ATTRIBUTE);
+ if (attributes.isEmpty()) {
+ attributes = null;
+ }
+ }
+ return this;
+ }
+
@Size(min = 0, max = 127, message = "{User.firstName.Size}")
public String getFirstName() {
return firstName;
diff --git a/ui/app/manager/src/pages/page-users.ts b/ui/app/manager/src/pages/page-users.ts
index 714d61238..b763b0f01 100644
--- a/ui/app/manager/src/pages/page-users.ts
+++ b/ui/app/manager/src/pages/page-users.ts
@@ -530,7 +530,7 @@ class PageUsers<S extends AppStateKeyed> extends Page<S> {
<div class="meta-item-container">
<div class="row">
<div class="column">
- <or-mwc-input ?readonly="${readonly}"
+ <or-mwc-input ?readonly="${!!user.id || readonly}"
.label="${i18next.t("username")}"
.type="${InputType.TEXT}" min="1" required
.value="${user.username}"
@@ -556,13 +556,13 @@ class PageUsers<S extends AppStateKeyed> extends Page<S> {
<or-mwc-input ?readonly="${readonly}"
?disabled="${isSameUser}"
.value="${user.roles && user.roles.length > 0 ? user.roles.map(r => r.name) : undefined}"
- .type="${InputType.SELECT}"
- .options="${roleOptions}"
+ .type="${InputType.SELECT}" multiple
+ .options="${roleOptions}"
.label="${i18next.t("role")}"
@or-mwc-input-changed="${(e: OrInputChangedEvent) => {
- const roleName = e.detail.value;
- const role = this._compositeRoles.find(cr => cr.name === roleName);
- user.roles = role ? [role] : undefined;
+ const roleNames = e.detail.value as string[];
+ const roles = this._compositeRoles.filter(cr => roleNames.some(rn => cr.name === rn));
+ user.roles = roles;
}}"></or-mwc-input>
${user.serviceAccount ? html`
<or-mwc-input id="password-${suffix}" readonly
diff --git a/ui/component/or-mwc-components/src/or-mwc-input.ts b/ui/component/or-mwc-components/src/or-mwc-input.ts
index 2d946f5ad..8e362dd46 100644
--- a/ui/component/or-mwc-components/src/or-mwc-input.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-input.ts
@@ -1250,7 +1250,9 @@ export class OrMwcInput extends LitElement {
mdcSelect.selectedIndex = -1; // Without this first option will be shown as selected
}
- (this._mdcComponent as any).foundation.adapter.floatLabel(this.value && (!Array.isArray(this.value) || this.value.length > 0));
+ const selectedText = this.getSelectedTextValue();
+ (this._mdcComponent as any).foundation.adapter.setSelectedText(selectedText);
+ (this._mdcComponent as any).foundation.adapter.floatLabel(!!selectedText);
// This overrides the standard mdc menu body click capture handler as it doesn't work with webcomponents
(mdcSelect as any).menu.menuSurface_.foundation.handleBodyClick = function (evt: MouseEvent) {
@@ -1447,9 +1449,12 @@ export class OrMwcInput extends LitElement {
}
protected getSelectedTextValue(options?: [string, string][] | undefined): string {
- const opts = options || this.resolveOptions(this.options);
const value = this.value;
const values = Array.isArray(value) ? value as string[] : value ? [value as string] : undefined;
- return !opts || !values ? "" : values.map(v => opts.find(([optValue, optDisplay], index) => v === optValue)).map((opt) => opt && opt[1]).join(",");
+ if (!values) {
+ return "";
+ }
+ const opts = options || this.resolveOptions(this.options);
+ return !opts || !values ? "" : values.map(v => opts.find(([optValue, optDisplay], index) => v === optValue)).map((opt) => opt ? opt[1] : "").join(",");
}
}