Search in sources :

Example 1 with TenantPredicate

use of org.openremote.model.query.filter.TenantPredicate in project openremote by openremote.

the class AssetResourceImpl method createUserAssetLinks.

@Override
public void createUserAssetLinks(RequestParams requestParams, List<UserAssetLink> userAssetLinks) {
    // Restricted users cannot create or delete links
    if (isRestrictedUser()) {
        throw new WebApplicationException(FORBIDDEN);
    }
    // Check all links are for the same user and realm
    String realm = userAssetLinks.get(0).getId().getRealm();
    String userId = userAssetLinks.get(0).getId().getUserId();
    String[] assetIds = new String[userAssetLinks.size()];
    IntStream.range(0, userAssetLinks.size()).forEach(i -> {
        UserAssetLink userAssetLink = userAssetLinks.get(i);
        assetIds[i] = userAssetLink.getId().getAssetId();
        if (!userAssetLink.getId().getRealm().equals(realm) || !userAssetLink.getId().getUserId().equals(userId)) {
            throw new BadRequestException("All user asset links must be for the same user");
        }
    });
    if (!isSuperUser() && !realm.equals(getAuthenticatedRealm())) {
        throw new WebApplicationException(FORBIDDEN);
    }
    if (!identityService.getIdentityProvider().isUserInTenant(userId, realm)) {
        throw new WebApplicationException(FORBIDDEN);
    }
    List<Asset<?>> assets = assetStorageService.findAll(new AssetQuery().select(new AssetQuery.Select().excludeAttributes()).tenant(new TenantPredicate(realm)).ids(assetIds));
    if (assets.size() != userAssetLinks.size()) {
        throw new BadRequestException("One or more asset IDs are invalid");
    }
    try {
        assetStorageService.storeUserAssetLinks(userAssetLinks);
    } catch (Exception e) {
        throw new WebApplicationException(BAD_REQUEST);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) AssetQuery(org.openremote.model.query.AssetQuery) BadRequestException(javax.ws.rs.BadRequestException) Asset(org.openremote.model.asset.Asset) TenantPredicate(org.openremote.model.query.filter.TenantPredicate) UserAssetLink(org.openremote.model.asset.UserAssetLink) BadRequestException(javax.ws.rs.BadRequestException) OptimisticLockException(javax.persistence.OptimisticLockException) ConstraintViolationException(javax.validation.ConstraintViolationException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 2 with TenantPredicate

use of org.openremote.model.query.filter.TenantPredicate in project openremote by openremote.

the class AssetResourceImpl method getCurrentUserAssets.

@Override
public Asset<?>[] getCurrentUserAssets(RequestParams requestParams) {
    try {
        if (isSuperUser()) {
            return new Asset<?>[0];
        }
        AssetQuery assetQuery = new AssetQuery();
        if (!isRestrictedUser()) {
            assetQuery.tenant(new TenantPredicate(getAuthenticatedRealm())).recursive(true);
        } else {
            assetQuery.userIds(getUserId());
        }
        List<Asset<?>> assets = assetStorageService.findAll(assetQuery);
        // Compress response (the request attribute enables the interceptor)
        request.setAttribute(HttpHeaders.CONTENT_ENCODING, "gzip");
        return assets.toArray(new Asset[0]);
    } catch (IllegalStateException ex) {
        throw new WebApplicationException(ex, BAD_REQUEST);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) AssetQuery(org.openremote.model.query.AssetQuery) Asset(org.openremote.model.asset.Asset) TenantPredicate(org.openremote.model.query.filter.TenantPredicate)

Example 3 with TenantPredicate

use of org.openremote.model.query.filter.TenantPredicate in project openremote by openremote.

the class UserResourceImpl method query.

@Override
public User[] query(RequestParams requestParams, UserQuery query) {
    AuthContext authContext = getAuthContext();
    boolean isAdmin = authContext.hasResourceRole(ClientRole.READ_ADMIN.getValue(), authContext.getClientId());
    boolean isRestricted = !isAdmin && authContext.hasResourceRole(ClientRole.READ_USERS.getValue(), authContext.getClientId());
    if (!isAdmin && !isRestricted) {
        throw new ForbiddenException("Insufficient permissions to read users");
    }
    if (query == null) {
        query = new UserQuery();
    }
    if (isRestricted) {
        if (query.select == null) {
            query.select = new UserQuery.Select();
        }
        query.select.basic(true);
    }
    if (!authContext.isSuperUser()) {
        // Force realm to match users
        query.tenant(new TenantPredicate(authContext.getAuthenticatedRealm()));
        // Hide system service accounts from non super users
        if (query.select == null) {
            query.select = new UserQuery.Select();
        }
        query.select.excludeSystemUsers = true;
    }
    try {
        return identityService.getIdentityProvider().queryUsers(query);
    } catch (ClientErrorException ex) {
        throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
    } catch (Exception ex) {
        throw new WebApplicationException(ex);
    }
}
Also used : UserQuery(org.openremote.model.query.UserQuery) AuthContext(org.openremote.container.security.AuthContext) TenantPredicate(org.openremote.model.query.filter.TenantPredicate)

Example 4 with TenantPredicate

use of org.openremote.model.query.filter.TenantPredicate in project openremote by openremote.

the class GatewayClientService method onCentralManagerMessage.

protected void onCentralManagerMessage(GatewayConnection connection, String message) {
    String messageId = null;
    SharedEvent event = null;
    if (message.startsWith(EventRequestResponseWrapper.MESSAGE_PREFIX)) {
        EventRequestResponseWrapper<?> wrapper = messageFromString(message, EventRequestResponseWrapper.MESSAGE_PREFIX, EventRequestResponseWrapper.class);
        messageId = wrapper.getMessageId();
        event = wrapper.getEvent();
    }
    if (message.startsWith(SharedEvent.MESSAGE_PREFIX)) {
        event = messageFromString(message, SharedEvent.MESSAGE_PREFIX, SharedEvent.class);
    }
    if (event != null) {
        if (event instanceof GatewayDisconnectEvent) {
            if (((GatewayDisconnectEvent) event).getReason() == GatewayDisconnectEvent.Reason.PERMANENT_ERROR) {
                LOG.info("Central manager requested disconnect due to permanent error (likely this version of the edge gateway software is not compatible with that manager version)");
                destroyGatewayClient(connection, clientRealmMap.get(connection.getLocalRealm()));
                clientRealmMap.put(connection.getLocalRealm(), null);
            }
        } else if (event instanceof AttributeEvent) {
            assetProcessingService.sendAttributeEvent((AttributeEvent) event, AttributeEvent.Source.INTERNAL);
        } else if (event instanceof AssetEvent) {
            AssetEvent assetEvent = (AssetEvent) event;
            if (assetEvent.getCause() == AssetEvent.Cause.CREATE || assetEvent.getCause() == AssetEvent.Cause.UPDATE) {
                Asset asset = assetEvent.getAsset();
                asset.setRealm(connection.getLocalRealm());
                LOG.finer("Request from central manager to create/update an asset: Realm=" + connection.getLocalRealm() + ", Asset<?> ID=" + asset.getId());
                try {
                    asset = assetStorageService.merge(asset, true);
                } catch (Exception e) {
                    LOG.log(Level.INFO, "Request from central manager to create/update an asset failed: Realm=" + connection.getLocalRealm() + ", Asset<?> ID=" + asset.getId(), e);
                }
            }
        } else if (event instanceof DeleteAssetsRequestEvent) {
            DeleteAssetsRequestEvent deleteRequest = (DeleteAssetsRequestEvent) event;
            LOG.finer("Request from central manager to delete asset(s): Realm=" + connection.getLocalRealm() + ", Asset<?> IDs=" + Arrays.toString(deleteRequest.getAssetIds().toArray()));
            boolean success = false;
            try {
                success = assetStorageService.delete(deleteRequest.getAssetIds());
            } catch (Exception e) {
                LOG.log(Level.INFO, "Request from central manager to create/update an asset failed: Realm=" + connection.getLocalRealm() + ", Asset<?> IDs=" + Arrays.toString(deleteRequest.getAssetIds().toArray()), e);
            } finally {
                sendCentralManagerMessage(connection.getLocalRealm(), messageToString(EventRequestResponseWrapper.MESSAGE_PREFIX, new EventRequestResponseWrapper<>(messageId, new DeleteAssetsResponseEvent(success, deleteRequest.getAssetIds()))));
            }
        } else if (event instanceof ReadAssetsEvent) {
            ReadAssetsEvent readAssets = (ReadAssetsEvent) event;
            AssetQuery query = readAssets.getAssetQuery();
            // Force realm to be the one that this client is associated with
            query.tenant(new TenantPredicate(connection.getLocalRealm()));
            List<Asset<?>> assets = assetStorageService.findAll(readAssets.getAssetQuery());
            sendCentralManagerMessage(connection.getLocalRealm(), messageToString(EventRequestResponseWrapper.MESSAGE_PREFIX, new EventRequestResponseWrapper<>(messageId, new AssetsEvent(assets))));
        }
    }
}
Also used : GatewayDisconnectEvent(org.openremote.model.gateway.GatewayDisconnectEvent) AssetQuery(org.openremote.model.query.AssetQuery) TenantPredicate(org.openremote.model.query.filter.TenantPredicate) AttributeEvent(org.openremote.model.attribute.AttributeEvent) SharedEvent(org.openremote.model.event.shared.SharedEvent) EventRequestResponseWrapper(org.openremote.model.event.shared.EventRequestResponseWrapper)

Example 5 with TenantPredicate

use of org.openremote.model.query.filter.TenantPredicate in project openremote by openremote.

the class AssetsFacade method getResults.

@Override
public Stream<Asset<?>> getResults(AssetQuery assetQuery) {
    if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
        // Realm is restricted to rules
        assetQuery.tenant = new TenantPredicate(rulesEngineId.getRealm().orElseThrow(() -> new IllegalArgumentException("Realm missing: " + rulesEngineId)));
    } else if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
        // Realm is restricted to assets'
        assetQuery.tenant = new TenantPredicate(rulesEngineId.getRealm().orElseThrow(() -> new IllegalArgumentException("Realm missing: " + rulesEngineId)));
        Asset<?> restrictedAsset = assetStorageService.find(rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ID missing: " + rulesEngineId)), true);
        if (restrictedAsset == null) {
            throw new IllegalStateException("Asset is no longer available: " + rulesEngineId);
        }
        assetQuery.paths(new PathPredicate(restrictedAsset.getPath()));
    }
    AssetQuery.Select oldValue = assetQuery.select;
    assetQuery.select = new AssetQuery.Select().excludeAttributes();
    try {
        return assetStorageService.findAll(assetQuery).stream();
    } finally {
        assetQuery.select = oldValue;
    }
}
Also used : AssetRuleset(org.openremote.model.rules.AssetRuleset) PathPredicate(org.openremote.model.query.filter.PathPredicate) AssetQuery(org.openremote.model.query.AssetQuery) Asset(org.openremote.model.asset.Asset) TenantPredicate(org.openremote.model.query.filter.TenantPredicate)

Aggregations

TenantPredicate (org.openremote.model.query.filter.TenantPredicate)7 AssetQuery (org.openremote.model.query.AssetQuery)5 Asset (org.openremote.model.asset.Asset)3 WebApplicationException (javax.ws.rs.WebApplicationException)2 PathPredicate (org.openremote.model.query.filter.PathPredicate)2 ArrayList (java.util.ArrayList)1 OptimisticLockException (javax.persistence.OptimisticLockException)1 ConstraintViolationException (javax.validation.ConstraintViolationException)1 BadRequestException (javax.ws.rs.BadRequestException)1 AuthContext (org.openremote.container.security.AuthContext)1 UserAssetLink (org.openremote.model.asset.UserAssetLink)1 ConsoleAsset (org.openremote.model.asset.impl.ConsoleAsset)1 GroupAsset (org.openremote.model.asset.impl.GroupAsset)1 AttributeEvent (org.openremote.model.attribute.AttributeEvent)1 EventRequestResponseWrapper (org.openremote.model.event.shared.EventRequestResponseWrapper)1 SharedEvent (org.openremote.model.event.shared.SharedEvent)1 GatewayDisconnectEvent (org.openremote.model.gateway.GatewayDisconnectEvent)1 UserQuery (org.openremote.model.query.UserQuery)1 AttributePredicate (org.openremote.model.query.filter.AttributePredicate)1 ParentPredicate (org.openremote.model.query.filter.ParentPredicate)1