Search in sources :

Example 1 with PersistenceService

use of org.openremote.container.persistence.PersistenceService in project openremote by openremote.

the class AssetProcessingService method init.

@Override
public void init(Container container) throws Exception {
    timerService = container.getService(TimerService.class);
    identityService = container.getService(ManagerIdentityService.class);
    persistenceService = container.getService(PersistenceService.class);
    rulesService = container.getService(RulesService.class);
    agentService = container.getService(AgentService.class);
    assetStorageService = container.getService(AssetStorageService.class);
    assetDatapointService = container.getService(AssetDatapointService.class);
    assetAttributeLinkingService = container.getService(AssetAttributeLinkingService.class);
    messageBrokerService = container.getService(MessageBrokerService.class);
    clientEventService = container.getService(ClientEventService.class);
    clientEventService.addSubscriptionAuthorizer((auth, subscription) -> {
        if (!subscription.isEventType(AttributeEvent.class)) {
            return false;
        }
        // Always must have a filter, as you can't subscribe to ALL asset attribute events
        if (subscription.getFilter() != null && subscription.getFilter() instanceof AttributeEvent.EntityIdFilter) {
            AttributeEvent.EntityIdFilter filter = (AttributeEvent.EntityIdFilter) subscription.getFilter();
            // Superuser can get attribute events for any asset
            if (auth.isSuperUser())
                return true;
            // Regular user must have role
            if (!auth.hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
                return false;
            }
            boolean isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(auth.getUserId());
            // Client can subscribe to several assets
            for (String assetId : filter.getEntityId()) {
                Asset asset = assetStorageService.find(assetId);
                // If the asset doesn't exist, subscription must fail
                if (asset == null)
                    return false;
                if (isRestrictedUser) {
                    // Restricted users can only get attribute events for their linked assets
                    if (!assetStorageService.isUserAsset(auth.getUserId(), assetId))
                        return false;
                // TODO Restricted clients should only receive events for RESTRICTED_READ attributes!
                } else {
                    // Regular users can only get attribute events for assets in their realm
                    if (!asset.getTenantRealm().equals(auth.getAuthenticatedRealm()))
                        return false;
                }
            }
            return true;
        }
        return false;
    });
    processors.add(agentService);
    processors.add(rulesService);
    processors.add(assetDatapointService);
    processors.add(assetAttributeLinkingService);
    container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);
}
Also used : TimerService(org.openremote.container.timer.TimerService) AttributeEvent(org.openremote.model.attribute.AttributeEvent) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) PersistenceService(org.openremote.container.persistence.PersistenceService) AssetDatapointService(org.openremote.manager.datapoint.AssetDatapointService) AgentService(org.openremote.manager.agent.AgentService) RulesService(org.openremote.manager.rules.RulesService) Asset(org.openremote.model.asset.Asset) ClientEventService(org.openremote.manager.event.ClientEventService) MessageBrokerService(org.openremote.container.message.MessageBrokerService)

Example 2 with PersistenceService

use of org.openremote.container.persistence.PersistenceService in project openremote by openremote.

the class AssetStorageService method init.

@Override
public void init(Container container) throws Exception {
    timerService = container.getService(TimerService.class);
    persistenceService = container.getService(PersistenceService.class);
    identityService = container.getService(ManagerIdentityService.class);
    clientEventService = container.getService(ClientEventService.class);
    gatewayService = container.getService(GatewayService.class);
    EventSubscriptionAuthorizer assetEventAuthorizer = AssetStorageService.assetInfoAuthorizer(identityService, this);
    clientEventService.addSubscriptionAuthorizer((realm, auth, subscription) -> {
        if (!subscription.isEventType(AssetEvent.class)) {
            return false;
        }
        return assetEventAuthorizer.authorise(realm, auth, subscription);
    });
    container.getService(ManagerWebService.class).addApiSingleton(new AssetResourceImpl(container.getService(TimerService.class), identityService, this, container.getService(MessageBrokerService.class)));
    container.getService(ManagerWebService.class).addApiSingleton(new ConsoleResourceImpl(container.getService(TimerService.class), identityService, this, clientEventService));
    container.getService(MessageBrokerService.class).getContext().addRoutes(this);
}
Also used : PersistenceService(org.openremote.container.persistence.PersistenceService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) EventSubscriptionAuthorizer(org.openremote.manager.event.EventSubscriptionAuthorizer) ManagerWebService(org.openremote.manager.web.ManagerWebService) ConsoleResourceImpl(org.openremote.manager.asset.console.ConsoleResourceImpl) ClientEventService(org.openremote.manager.event.ClientEventService) TimerService(org.openremote.container.timer.TimerService) GatewayService(org.openremote.manager.gateway.GatewayService)

Example 3 with PersistenceService

use of org.openremote.container.persistence.PersistenceService in project openremote by openremote.

the class ManagerIdentityProvider method getUsersFromDb.

static User[] getUsersFromDb(PersistenceService persistenceService, UserQuery query) {
    StringBuilder sb = new StringBuilder();
    List<Object> parameters = new ArrayList<>();
    final UserQuery userQuery = query != null ? query : new UserQuery();
    // BUILD SELECT
    sb.append("SELECT u");
    // 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");
    }
    // BUILD WHERE
    sb.append(" WHERE 1=1");
    if (userQuery.tenantPredicate != null && !TextUtil.isNullOrEmpty(userQuery.tenantPredicate.realm)) {
        sb.append(" AND u.realm = ?").append(parameters.size() + 1);
        parameters.add(userQuery.tenantPredicate.realm);
    }
    if (userQuery.assetPredicate != null) {
        sb.append(" AND ua.id.assetId = ?").append(parameters.size() + 1);
        parameters.add(userQuery.assetPredicate.id);
    }
    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(")");
    }
    if (userQuery.usernames != null && userQuery.usernames.length > 0) {
        sb.append(" and (");
        boolean isFirst = true;
        for (StringPredicate pred : userQuery.usernames) {
            if (!isFirst) {
                sb.append(" or ");
            }
            isFirst = false;
            final int pos = parameters.size() + 1;
            // No case support for username
            sb.append("upper(u.username)");
            sb.append(buildMatchFilter(pred, pos));
            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");
    }
    // BUILD ORDER BY
    if (userQuery.orderBy != null) {
        if (userQuery.orderBy.property != null) {
            sb.append(" ORDER BY");
            switch(userQuery.orderBy.property) {
                case CREATED_ON:
                    sb.append(" u.createdOn");
                    break;
                case FIRST_NAME:
                    sb.append(" u.firstName");
                    break;
                case LAST_NAME:
                    sb.append(" u.lastName");
                    break;
                case USERNAME:
                    // Remove service user prefix
                    sb.append(" replace(u.username, '").append(User.SERVICE_ACCOUNT_PREFIX).append("', '')");
                    break;
                case EMAIL:
                    sb.append(" u.email");
                    break;
                default:
                    throw new UnsupportedOperationException("Unsupported order by value: " + userQuery.orderBy.property);
            }
            if (userQuery.orderBy.descending) {
                sb.append(" DESC");
            }
        }
    }
    List<User> users = persistenceService.doReturningTransaction(entityManager -> {
        TypedQuery<User> sqlQuery = entityManager.createQuery(sb.toString(), User.class);
        IntStream.range(0, parameters.size()).forEach(i -> sqlQuery.setParameter(i + 1, parameters.get(i)));
        if (userQuery.limit != null && userQuery.limit > 0) {
            sqlQuery.setMaxResults(userQuery.limit);
        }
        if (userQuery.offset != null && userQuery.offset > 0) {
            sqlQuery.setFirstResult(query.offset);
        }
        return sqlQuery.getResultList();
    });
    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);
    }
    return users.toArray(new User[0]);
}
Also used : IdentityProvider(org.openremote.container.security.IdentityProvider) AssetStorageService(org.openremote.manager.asset.AssetStorageService) org.openremote.model.security(org.openremote.model.security) IntStream(java.util.stream.IntStream) java.util(java.util) AssetStorageService.buildMatchFilter(org.openremote.manager.asset.AssetStorageService.buildMatchFilter) AuthContext(org.openremote.container.security.AuthContext) MASTER_REALM(org.openremote.model.Constants.MASTER_REALM) TypedQuery(javax.persistence.TypedQuery) Collectors(java.util.stream.Collectors) TenantFilter(org.openremote.model.event.shared.TenantFilter) StringPredicate(org.openremote.model.query.filter.StringPredicate) UserQuery(org.openremote.model.query.UserQuery) PersistenceService(org.openremote.container.persistence.PersistenceService) TextUtil(org.openremote.model.util.TextUtil) StringPredicate(org.openremote.model.query.filter.StringPredicate) UserQuery(org.openremote.model.query.UserQuery)

Example 4 with PersistenceService

use of org.openremote.container.persistence.PersistenceService in project openremote by openremote.

the class ProvisioningService method init.

@Override
public void init(Container container) throws Exception {
    persistenceService = container.getService(PersistenceService.class);
    identityService = container.getService(ManagerIdentityService.class);
    TimerService timerService = container.getService(TimerService.class);
    container.getService(ManagerWebService.class).addApiSingleton(new ProvisioningResourceImpl(this, timerService, identityService));
}
Also used : PersistenceService(org.openremote.container.persistence.PersistenceService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) ManagerWebService(org.openremote.manager.web.ManagerWebService) TimerService(org.openremote.container.timer.TimerService)

Example 5 with PersistenceService

use of org.openremote.container.persistence.PersistenceService in project openremote by openremote.

the class SyslogService method init.

@Override
public void init(Container container) throws Exception {
    executorService = container.getExecutorService();
    if (container.hasService(ClientEventService.class) && container.hasService(PersistenceService.class)) {
        LOG.info("Syslog service enabled");
        clientEventService = container.getService(ClientEventService.class);
        persistenceService = container.getService(PersistenceService.class);
    } else {
        LOG.info("Syslog service disabled, missing required services");
    }
    if (clientEventService != null) {
        clientEventService.addSubscriptionAuthorizer((realm, auth, subscription) -> subscription.isEventType(SyslogEvent.class) && auth != null && (auth.isSuperUser() || auth.hasResourceRole(Constants.READ_LOGS_ROLE, auth.getClientId())));
    }
    if (container.hasService(ManagerWebService.class)) {
        container.getService(ManagerWebService.class).addApiSingleton(new SyslogResourceImpl(this));
    }
    // Default config: Store all INFO messages for five days
    config = new SyslogConfig(SyslogLevel.INFO, SyslogCategory.values(), 60 * 24 * 5);
}
Also used : PersistenceService(org.openremote.container.persistence.PersistenceService) SyslogEvent(org.openremote.model.syslog.SyslogEvent) ManagerWebService(org.openremote.manager.web.ManagerWebService) ClientEventService(org.openremote.manager.event.ClientEventService) SyslogConfig(org.openremote.model.syslog.SyslogConfig)

Aggregations

PersistenceService (org.openremote.container.persistence.PersistenceService)6 TimerService (org.openremote.container.timer.TimerService)4 ClientEventService (org.openremote.manager.event.ClientEventService)4 ManagerIdentityService (org.openremote.manager.security.ManagerIdentityService)4 ManagerWebService (org.openremote.manager.web.ManagerWebService)4 AssetStorageService (org.openremote.manager.asset.AssetStorageService)2 AssetDatapointService (org.openremote.manager.datapoint.AssetDatapointService)2 GatewayService (org.openremote.manager.gateway.GatewayService)2 java.util (java.util)1 Collectors (java.util.stream.Collectors)1 IntStream (java.util.stream.IntStream)1 TypedQuery (javax.persistence.TypedQuery)1 MessageBrokerService (org.openremote.container.message.MessageBrokerService)1 AuthContext (org.openremote.container.security.AuthContext)1 IdentityProvider (org.openremote.container.security.IdentityProvider)1 AgentService (org.openremote.manager.agent.AgentService)1 AssetProcessingService (org.openremote.manager.asset.AssetProcessingService)1 AssetStorageService.buildMatchFilter (org.openremote.manager.asset.AssetStorageService.buildMatchFilter)1 ConsoleResourceImpl (org.openremote.manager.asset.console.ConsoleResourceImpl)1 AssetPredictedDatapointService (org.openremote.manager.datapoint.AssetPredictedDatapointService)1