Search in sources :

Example 1 with Query

use of io.gravitee.rest.api.service.search.query.Query in project gravitee-management-rest-api by gravitee-io.

the class UserServiceImpl method resetPassword.

private void resetPassword(final String id, final String resetPageUrl) {
    try {
        LOGGER.debug("Resetting password of user id {}", id);
        Optional<User> optionalUser = userRepository.findById(id);
        if (!optionalUser.isPresent()) {
            throw new UserNotFoundException(id);
        }
        final User user = optionalUser.get();
        if (!isInternalUser(user)) {
            throw new UserNotInternallyManagedException(id);
        }
        // do not perform this check if the request comes from an authenticated user (ie. admin or someone with right permission)
        if (!isAuthenticated() || !canResetPassword()) {
            AuditQuery query = new AuditQuery();
            query.setEvents(Arrays.asList(User.AuditEvent.PASSWORD_RESET.name()));
            query.setFrom(Instant.now().minus(1, ChronoUnit.HOURS).toEpochMilli());
            query.setPage(1);
            query.setSize(100);
            MetadataPage<AuditEntity> events = auditService.search(query);
            if (events != null) {
                if (events.getContent().size() == 100) {
                    LOGGER.warn("More than 100 reset password received in less than 1 hour", user.getId());
                }
                Optional<AuditEntity> optReset = events.getContent().stream().filter(evt -> user.getId().equals(evt.getProperties().get(USER.name()))).findFirst();
                if (optReset.isPresent()) {
                    LOGGER.warn("Multiple reset password received for user '{}' in less than 1 hour", user.getId());
                    throw new PasswordAlreadyResetException();
                }
            }
        }
        final Map<String, Object> params = getTokenRegistrationParams(convert(user, false), RESET_PASSWORD_PATH, RESET_PASSWORD, resetPageUrl);
        notifierService.trigger(PortalHook.PASSWORD_RESET, params);
        auditService.createOrganizationAuditLog(Collections.singletonMap(USER, user.getId()), User.AuditEvent.PASSWORD_RESET, new Date(), null, null);
        emailService.sendAsyncEmailNotification(new EmailNotificationBuilder().to(user.getEmail()).template(EmailNotificationBuilder.EmailTemplate.TEMPLATES_FOR_ACTION_USER_PASSWORD_RESET).params(params).build(), GraviteeContext.getCurrentContext());
    } catch (TechnicalException ex) {
        final String message = "An error occurs while trying to reset password for user " + id;
        LOGGER.error(message, ex);
        throw new TechnicalManagementException(message, ex);
    }
}
Also used : BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) Page(io.gravitee.common.data.domain.Page) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) MembershipRepository(io.gravitee.repository.management.api.MembershipRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) SocialIdentityProviderEntity(io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) StringUtils(org.apache.commons.lang3.StringUtils) UPDATE(io.gravitee.rest.api.model.permissions.RolePermissionAction.UPDATE) IdentityProviderService(io.gravitee.rest.api.service.configuration.identity.IdentityProviderService) TemplateEngine(io.gravitee.el.TemplateEngine) Algorithm(com.auth0.jwt.algorithms.Algorithm) AuditQuery(io.gravitee.rest.api.model.audit.AuditQuery) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) RoleMappingEntity(io.gravitee.rest.api.model.configuration.identity.RoleMappingEntity) Duration(java.time.Duration) PortalHook(io.gravitee.rest.api.service.notification.PortalHook) GroupMappingEntity(io.gravitee.rest.api.model.configuration.identity.GroupMappingEntity) Collectors.toSet(java.util.stream.Collectors.toSet) ApplicationSettings(io.gravitee.rest.api.model.application.ApplicationSettings) RolePermissionAction(io.gravitee.rest.api.model.permissions.RolePermissionAction) JsonPathFunction(io.gravitee.el.spel.function.json.JsonPathFunction) Instant(java.time.Instant) SimpleApplicationSettings(io.gravitee.rest.api.model.application.SimpleApplicationSettings) Collectors(java.util.stream.Collectors) Key(io.gravitee.rest.api.model.parameters.Key) NotificationParamsBuilder(io.gravitee.rest.api.service.notification.NotificationParamsBuilder) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder) UrlSanitizerUtils(io.gravitee.rest.api.service.sanitizer.UrlSanitizerUtils) DatatypeConverter(javax.xml.bind.DatatypeConverter) AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity) RolePermission(io.gravitee.rest.api.model.permissions.RolePermission) SearchEngineService(io.gravitee.rest.api.service.search.SearchEngineService) JWT(com.auth0.jwt.JWT) io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Pageable(io.gravitee.rest.api.model.common.Pageable) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER) InitializingBean(org.springframework.beans.factory.InitializingBean) Value(org.springframework.beans.factory.annotation.Value) JWTVerifier(com.auth0.jwt.JWTVerifier) ReadContext(com.jayway.jsonpath.ReadContext) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) UserRepository(io.gravitee.repository.management.api.UserRepository) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) UserStatus(io.gravitee.repository.management.model.UserStatus) io.gravitee.rest.api.model(io.gravitee.rest.api.model) Membership(io.gravitee.repository.management.model.Membership) Query(io.gravitee.rest.api.service.search.query.Query) UuidString(io.gravitee.rest.api.service.common.UuidString) Logger(org.slf4j.Logger) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) JsonPath(com.jayway.jsonpath.JsonPath) Maps(io.gravitee.common.util.Maps) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) MetadataPage(io.gravitee.common.data.domain.MetadataPage) Collectors.toList(java.util.stream.Collectors.toList) Component(org.springframework.stereotype.Component) USER(io.gravitee.repository.management.model.Audit.AuditProperties.USER) ChronoUnit(java.time.temporal.ChronoUnit) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) UserCriteria(io.gravitee.repository.management.api.search.UserCriteria) User(io.gravitee.repository.management.model.User) ACTION(io.gravitee.rest.api.service.common.JWTHelper.ACTION) QueryBuilder(io.gravitee.rest.api.service.search.query.QueryBuilder) SearchResult(io.gravitee.rest.api.service.impl.search.SearchResult) User(io.gravitee.repository.management.model.User) AuditQuery(io.gravitee.rest.api.model.audit.AuditQuery) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) UuidString(io.gravitee.rest.api.service.common.UuidString) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder) AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity)

Example 2 with Query

use of io.gravitee.rest.api.service.search.query.Query in project gravitee-management-rest-api by gravitee-io.

the class ApiServiceImpl method findApisByUser.

private List<Api> findApisByUser(String userId, ApiQuery apiQuery, boolean portal) {
    // get all public apis
    List<Api> publicApis;
    if (portal) {
        publicApis = apiRepository.search(queryToCriteria(apiQuery).visibility(PUBLIC).build());
    } else {
        publicApis = emptyList();
    }
    List<Api> userApis = emptyList();
    List<Api> groupApis = emptyList();
    List<Api> subscribedApis = emptyList();
    // for others API, user must be authenticated
    if (userId != null) {
        // get user apis
        final String[] userApiIds = membershipService.getMembershipsByMemberAndReference(MembershipMemberType.USER, userId, MembershipReferenceType.API).stream().map(MembershipEntity::getReferenceId).filter(apiId -> {
            if (apiQuery != null && !CollectionUtils.isEmpty(apiQuery.getIds())) {
                // We already have api ids to focus on.
                return apiQuery.getIds().contains(apiId);
            } else {
                return true;
            }
        }).toArray(String[]::new);
        if (userApiIds.length > 0) {
            userApis = apiRepository.search(queryToCriteria(apiQuery).ids(userApiIds).build());
        }
        // get user groups apis
        final String[] groupIds = membershipService.getMembershipsByMemberAndReference(MembershipMemberType.USER, userId, MembershipReferenceType.GROUP).stream().filter(m -> {
            final RoleEntity roleInGroup = roleService.findById(m.getRoleId());
            if (!portal) {
                return (m.getRoleId() != null && roleInGroup.getScope().equals(RoleScope.API) && canManageApi(roleInGroup.getPermissions()));
            }
            return m.getRoleId() != null && roleInGroup.getScope().equals(RoleScope.API);
        }).map(MembershipEntity::getReferenceId).toArray(String[]::new);
        if (groupIds.length > 0 && groupIds[0] != null) {
            groupApis = apiRepository.search(queryToCriteria(apiQuery).groups(groupIds).build());
        }
        // get user subscribed apis, useful when an API becomes private and an app owner is not anymore in members.
        if (portal) {
            final Set<String> applications = applicationService.findByUser(userId).stream().map(ApplicationListItem::getId).collect(toSet());
            if (!applications.isEmpty()) {
                final SubscriptionQuery query = new SubscriptionQuery();
                query.setApplications(applications);
                final Collection<SubscriptionEntity> subscriptions = subscriptionService.search(query);
                if (subscriptions != null && !subscriptions.isEmpty()) {
                    subscribedApis = apiRepository.search(queryToCriteria(apiQuery).ids(subscriptions.stream().map(SubscriptionEntity::getApi).distinct().toArray(String[]::new)).build());
                }
            }
        }
    }
    List<Api> allApis = new ArrayList<>();
    allApis.addAll(publicApis);
    allApis.addAll(userApis);
    allApis.addAll(groupApis);
    allApis.addAll(subscribedApis);
    return allApis.stream().distinct().collect(toList());
}
Also used : ApiHook(io.gravitee.rest.api.service.notification.ApiHook) EndpointDiscoveryService(io.gravitee.definition.model.services.discovery.EndpointDiscoveryService) Optional.of(java.util.Optional.of) Page(io.gravitee.common.data.domain.Page) Sortable(io.gravitee.rest.api.model.common.Sortable) HookScope(io.gravitee.rest.api.service.notification.HookScope) Autowired(org.springframework.beans.factory.annotation.Autowired) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) StringUtils(org.apache.commons.lang3.StringUtils) ApiCriteria(io.gravitee.repository.management.api.search.ApiCriteria) Matcher(java.util.regex.Matcher) AuditEvent(io.gravitee.repository.management.model.Api.AuditEvent) PageQuery(io.gravitee.rest.api.model.documentation.PageQuery) JsonNode(com.fasterxml.jackson.databind.JsonNode) EntrypointReferenceType(io.gravitee.rest.api.model.EntrypointReferenceType) ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) RolePermissionAction(io.gravitee.rest.api.model.permissions.RolePermissionAction) IOUtils(org.apache.commons.io.IOUtils) Stream(java.util.stream.Stream) CollectionUtils(org.springframework.util.CollectionUtils) HealthCheckService(io.gravitee.definition.model.services.healthcheck.HealthCheckService) DatatypeConverter(javax.xml.bind.DatatypeConverter) java.util(java.util) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) Value(org.springframework.beans.factory.annotation.Value) Strings(com.google.common.base.Strings) ApiPrimaryOwnerMode(io.gravitee.rest.api.model.settings.ApiPrimaryOwnerMode) DRAFT(io.gravitee.rest.api.model.WorkflowState.DRAFT) NotificationTemplateService(io.gravitee.rest.api.service.notification.NotificationTemplateService) DefaultMetadataUpgrader(io.gravitee.rest.api.service.impl.upgrade.DefaultMetadataUpgrader) SWAGGER(io.gravitee.rest.api.model.PageType.SWAGGER) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) PUBLIC(io.gravitee.repository.management.model.Visibility.PUBLIC) PageableImpl(io.gravitee.rest.api.model.common.PageableImpl) Query(io.gravitee.rest.api.service.search.query.Query) UuidString(io.gravitee.rest.api.service.common.UuidString) IOException(java.io.IOException) io.gravitee.definition.model(io.gravitee.definition.model) io.gravitee.rest.api.model.api(io.gravitee.rest.api.model.api) CronTrigger(org.springframework.scheduling.support.CronTrigger) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType) GenericNotificationConfigEntity(io.gravitee.rest.api.model.notification.GenericNotificationConfigEntity) io.gravitee.repository.management.model(io.gravitee.repository.management.model) StringReader(java.io.StringReader) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) SearchResult(io.gravitee.rest.api.service.impl.search.SearchResult) REVIEW(io.gravitee.rest.api.model.WorkflowType.REVIEW) Plan(io.gravitee.definition.model.Plan) API(io.gravitee.rest.api.model.WorkflowReferenceType.API) Properties(io.gravitee.definition.model.Properties) URL(java.net.URL) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ApiRepository(io.gravitee.repository.management.api.ApiRepository) Lifecycle(io.gravitee.common.component.Lifecycle) PatternSyntaxException(java.util.regex.PatternSyntaxException) ApiQualityRuleRepository(io.gravitee.repository.management.api.ApiQualityRuleRepository) Predicate(java.util.function.Predicate) ApiLifecycleState(io.gravitee.repository.management.model.ApiLifecycleState) MetadataFormat(io.gravitee.rest.api.model.MetadataFormat) Collectors(java.util.stream.Collectors) ApiFieldExclusionFilter(io.gravitee.repository.management.api.search.ApiFieldExclusionFilter) Key(io.gravitee.rest.api.model.parameters.Key) Api(io.gravitee.repository.management.model.Api) NotificationParamsBuilder(io.gravitee.rest.api.service.notification.NotificationParamsBuilder) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder) APIV1toAPIV2Converter(io.gravitee.rest.api.service.migration.APIV1toAPIV2Converter) SubscriptionQuery(io.gravitee.rest.api.model.subscription.SubscriptionQuery) Pattern(java.util.regex.Pattern) ApiHeaderEntity(io.gravitee.rest.api.model.api.header.ApiHeaderEntity) NotNull(org.jetbrains.annotations.NotNull) SystemRole(io.gravitee.rest.api.model.permissions.SystemRole) SearchEngineService(io.gravitee.rest.api.service.search.SearchEngineService) io.gravitee.rest.api.service(io.gravitee.rest.api.service) TagReferenceType(io.gravitee.rest.api.model.TagReferenceType) Pageable(io.gravitee.rest.api.model.common.Pageable) ImportConfiguration(io.gravitee.rest.api.service.spring.ImportConfiguration) ApiPermission(io.gravitee.rest.api.model.permissions.ApiPermission) Visibility(io.gravitee.repository.management.model.Visibility) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) EventType(io.gravitee.rest.api.model.EventType) io.gravitee.rest.api.model(io.gravitee.rest.api.model) Comparator.comparing(java.util.Comparator.comparing) PUBLISH_API(io.gravitee.rest.api.model.EventType.PUBLISH_API) ApiSynchronizationProcessor(io.gravitee.rest.api.service.processor.ApiSynchronizationProcessor) Step(io.gravitee.definition.model.flow.Step) AlertReferenceType(io.gravitee.rest.api.model.alert.AlertReferenceType) Logger(org.slf4j.Logger) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) MalformedURLException(java.net.MalformedURLException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) FileInputStream(java.io.FileInputStream) AlertTriggerEntity(io.gravitee.rest.api.model.alert.AlertTriggerEntity) Component(org.springframework.stereotype.Component) INLINE(io.gravitee.rest.api.model.ImportSwaggerDescriptorEntity.Type.INLINE) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) AuditEvent(io.gravitee.repository.management.model.Workflow.AuditEvent) QueryBuilder(io.gravitee.rest.api.service.search.query.QueryBuilder) Collections(java.util.Collections) Api(io.gravitee.repository.management.model.Api) UuidString(io.gravitee.rest.api.service.common.UuidString) SubscriptionQuery(io.gravitee.rest.api.model.subscription.SubscriptionQuery)

Aggregations

Page (io.gravitee.common.data.domain.Page)2 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)2 io.gravitee.rest.api.model (io.gravitee.rest.api.model)2 JWT (com.auth0.jwt.JWT)1 JWTVerifier (com.auth0.jwt.JWTVerifier)1 Algorithm (com.auth0.jwt.algorithms.Algorithm)1 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 Strings (com.google.common.base.Strings)1 JsonPath (com.jayway.jsonpath.JsonPath)1 ReadContext (com.jayway.jsonpath.ReadContext)1 Lifecycle (io.gravitee.common.component.Lifecycle)1 MetadataPage (io.gravitee.common.data.domain.MetadataPage)1 Maps (io.gravitee.common.util.Maps)1 io.gravitee.definition.model (io.gravitee.definition.model)1 Plan (io.gravitee.definition.model.Plan)1