Search in sources :

Example 1 with AuditEntity

use of io.gravitee.rest.api.model.audit.AuditEntity in project gravitee-management-rest-api by gravitee-io.

the class AuditServiceImpl method getMetadata.

private Map<String, String> getMetadata(List<AuditEntity> content) {
    Map<String, String> metadata = new HashMap<>();
    for (AuditEntity auditEntity : content) {
        // add user's display name
        String metadataKey = "USER:" + auditEntity.getUser() + ":name";
        try {
            UserEntity user = userService.findById(auditEntity.getUser());
            metadata.put(metadataKey, user.getDisplayName());
        } catch (TechnicalManagementException e) {
            LOGGER.error("Error finding metadata {}", auditEntity.getUser());
        } catch (UserNotFoundException unfe) {
            metadata.put(metadataKey, auditEntity.getUser());
        }
        if (Audit.AuditReferenceType.API.name().equals(auditEntity.getReferenceType())) {
            metadataKey = "API:" + auditEntity.getReferenceId() + ":name";
            if (!metadata.containsKey(metadataKey)) {
                try {
                    Optional<Api> optApi = apiRepository.findById(auditEntity.getReferenceId());
                    if (optApi.isPresent()) {
                        metadata.put(metadataKey, optApi.get().getName());
                    }
                } catch (TechnicalException e) {
                    LOGGER.error("Error finding metadata {}", metadataKey);
                    metadata.put(metadataKey, auditEntity.getReferenceId());
                }
            }
        } else if (Audit.AuditReferenceType.APPLICATION.name().equals(auditEntity.getReferenceType())) {
            metadataKey = "APPLICATION:" + auditEntity.getReferenceId() + ":name";
            if (!metadata.containsKey(metadataKey)) {
                try {
                    Optional<Application> optApp = applicationRepository.findById(auditEntity.getReferenceId());
                    if (optApp.isPresent()) {
                        metadata.put(metadataKey, optApp.get().getName());
                    }
                } catch (TechnicalException e) {
                    LOGGER.error("Error finding metadata {}", metadataKey);
                    metadata.put(metadataKey, auditEntity.getReferenceId());
                }
            }
        }
        // add property metadata
        String name;
        if (auditEntity.getProperties() != null) {
            for (Map.Entry<String, String> property : auditEntity.getProperties().entrySet()) {
                metadataKey = new StringJoiner(":").add(property.getKey()).add(property.getValue()).add("name").toString();
                if (!metadata.containsKey(metadataKey)) {
                    name = property.getValue();
                    try {
                        switch(Audit.AuditProperties.valueOf(property.getKey())) {
                            case API:
                                Optional<Api> optApi = apiRepository.findById(property.getValue());
                                if (optApi.isPresent()) {
                                    name = optApi.get().getName();
                                }
                                break;
                            case APPLICATION:
                                Optional<Application> optApp = applicationRepository.findById(property.getValue());
                                if (optApp.isPresent()) {
                                    name = optApp.get().getName();
                                }
                                break;
                            case PAGE:
                                Optional<io.gravitee.repository.management.model.Page> optPage = pageRepository.findById(property.getValue());
                                if (optPage.isPresent()) {
                                    name = optPage.get().getName();
                                }
                                break;
                            case PLAN:
                                Optional<Plan> optPlan = planRepository.findById(property.getValue());
                                if (optPlan.isPresent()) {
                                    name = optPlan.get().getName();
                                }
                                break;
                            case METADATA:
                                MetadataReferenceType refType = (Audit.AuditReferenceType.API.name().equals(auditEntity.getReferenceType())) ? MetadataReferenceType.API : (Audit.AuditReferenceType.APPLICATION.name().equals(auditEntity.getReferenceType())) ? MetadataReferenceType.APPLICATION : MetadataReferenceType.DEFAULT;
                                String refId = refType.equals(MetadataReferenceType.DEFAULT) ? getDefaultReferenceId() : auditEntity.getReferenceId();
                                Optional<Metadata> optMetadata = metadataRepository.findById(property.getValue(), refId, refType);
                                if (optMetadata.isPresent()) {
                                    name = optMetadata.get().getName();
                                }
                                break;
                            case GROUP:
                                Optional<Group> optGroup = groupRepository.findById(property.getValue());
                                if (optGroup.isPresent()) {
                                    name = optGroup.get().getName();
                                }
                                break;
                            case USER:
                                try {
                                    UserEntity user = userService.findById(property.getValue());
                                    name = user.getDisplayName();
                                } catch (UserNotFoundException unfe) {
                                    name = property.getValue();
                                }
                            default:
                                break;
                        }
                    } catch (TechnicalException e) {
                        LOGGER.error("Error finding metadata {}", metadataKey);
                        name = property.getValue();
                    }
                    metadata.put(metadataKey, name);
                }
            }
        }
    }
    return metadata;
}
Also used : UserNotFoundException(io.gravitee.rest.api.service.exceptions.UserNotFoundException) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Page(io.gravitee.common.data.domain.Page) MetadataPage(io.gravitee.common.data.domain.MetadataPage) UuidString(io.gravitee.rest.api.service.common.UuidString) UserEntity(io.gravitee.rest.api.model.UserEntity) AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 2 with AuditEntity

use of io.gravitee.rest.api.model.audit.AuditEntity 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 3 with AuditEntity

use of io.gravitee.rest.api.model.audit.AuditEntity in project gravitee-management-rest-api by gravitee-io.

the class AuditServiceImpl method search.

@Override
public MetadataPage<AuditEntity> search(AuditQuery query) {
    Builder criteria = new Builder().from(query.getFrom()).to(query.getTo());
    if (query.isCurrentEnvironmentLogsOnly()) {
        criteria.references(Audit.AuditReferenceType.ENVIRONMENT, Collections.singletonList(GraviteeContext.getCurrentEnvironment()));
    } else if (query.isCurrentOrganizationLogsOnly()) {
        criteria.references(Audit.AuditReferenceType.ORGANIZATION, Collections.singletonList(GraviteeContext.getCurrentOrganization()));
    } else if (query.getApiIds() != null && !query.getApiIds().isEmpty()) {
        criteria.references(Audit.AuditReferenceType.API, query.getApiIds());
    } else if (query.getApplicationIds() != null && !query.getApplicationIds().isEmpty()) {
        criteria.references(Audit.AuditReferenceType.APPLICATION, query.getApplicationIds());
    }
    if (query.getEvents() != null && !query.getEvents().isEmpty()) {
        criteria.events(query.getEvents());
    }
    Page<Audit> auditPage = auditRepository.search(criteria.build(), new PageableBuilder().pageNumber(query.getPage() - 1).pageSize(query.getSize()).build());
    List<AuditEntity> content = auditPage.getContent().stream().map(this::convert).collect(Collectors.toList());
    return new MetadataPage<>(content, query.getPage(), query.getSize(), auditPage.getTotalElements(), getMetadata(content));
}
Also used : AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity) MetadataPage(io.gravitee.common.data.domain.MetadataPage) Builder(io.gravitee.repository.management.api.search.AuditCriteria.Builder) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder)

Example 4 with AuditEntity

use of io.gravitee.rest.api.model.audit.AuditEntity in project gravitee-management-rest-api by gravitee-io.

the class AuditServiceImpl method convert.

private AuditEntity convert(Audit audit) {
    AuditEntity auditEntity = new AuditEntity();
    auditEntity.setReferenceType(audit.getReferenceType().name());
    auditEntity.setReferenceId(audit.getReferenceId());
    auditEntity.setEvent(audit.getEvent());
    auditEntity.setProperties(audit.getProperties());
    auditEntity.setUser(audit.getUser());
    auditEntity.setId(audit.getId());
    auditEntity.setPatch(audit.getPatch());
    auditEntity.setCreatedAt(audit.getCreatedAt());
    return auditEntity;
}
Also used : AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity)

Example 5 with AuditEntity

use of io.gravitee.rest.api.model.audit.AuditEntity in project gravitee-management-rest-api by gravitee-io.

the class UserServiceTest method shouldResetPassword_auditEventNotMatch.

@Test
public void shouldResetPassword_auditEventNotMatch() throws TechnicalException {
    when(environment.getProperty("jwt.secret")).thenReturn(JWT_SECRET);
    when(environment.getProperty("user.creation.token.expire-after", Integer.class, DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER)).thenReturn(1000);
    when(user.getId()).thenReturn(USER_NAME);
    when(user.getSource()).thenReturn("gravitee");
    when(userRepository.findById(USER_NAME)).thenReturn(of(user));
    MetadataPage mdPage = mock(MetadataPage.class);
    AuditEntity entity1 = new AuditEntity();
    entity1.setProperties(Collections.singletonMap("USER", "unknown"));
    when(mdPage.getContent()).thenReturn(Arrays.asList(entity1));
    when(auditService.search(argThat(arg -> arg.getEvents().contains(User.AuditEvent.PASSWORD_RESET.name())))).thenReturn(mdPage);
    userService.resetPassword(USER_NAME);
    verify(user, never()).setPassword(null);
    verify(userRepository, never()).update(user);
    verify(emailService).sendAsyncEmailNotification(any(), any());
}
Also used : AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity) ArgumentMatchers(org.mockito.ArgumentMatchers) Optional.of(java.util.Optional.of) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) MembershipRepository(io.gravitee.repository.management.api.MembershipRepository) SocialIdentityProviderEntity(io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) ArgumentMatcher(org.mockito.ArgumentMatcher) Algorithm(com.auth0.jwt.algorithms.Algorithm) RoleMappingEntity(io.gravitee.rest.api.model.configuration.identity.RoleMappingEntity) Duration(java.time.Duration) GroupMappingEntity(io.gravitee.rest.api.model.configuration.identity.GroupMappingEntity) ExpressionEvaluationException(io.gravitee.el.exceptions.ExpressionEvaluationException) ApplicationListItem(io.gravitee.rest.api.model.application.ApplicationListItem) Instant(java.time.Instant) RESET_PASSWORD(io.gravitee.rest.api.service.common.JWTHelper.ACTION.RESET_PASSWORD) UserServiceImpl(io.gravitee.rest.api.service.impl.UserServiceImpl) AdditionalAnswers.returnsFirstArg(org.mockito.AdditionalAnswers.returnsFirstArg) Key(io.gravitee.rest.api.model.parameters.Key) IOUtils(org.apache.commons.io.IOUtils) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity) SearchEngineService(io.gravitee.rest.api.service.search.SearchEngineService) Optional.empty(java.util.Optional.empty) JWT(com.auth0.jwt.JWT) java.util(java.util) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Charset(java.nio.charset.Charset) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) UserRepository(io.gravitee.repository.management.api.UserRepository) UserStatus(io.gravitee.repository.management.model.UserStatus) io.gravitee.rest.api.model(io.gravitee.rest.api.model) Membership(io.gravitee.repository.management.model.Membership) InjectMocks(org.mockito.InjectMocks) ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) ApplicationType(io.gravitee.repository.management.model.ApplicationType) IOException(java.io.IOException) Test(org.junit.Test) Maps(io.gravitee.common.util.Maps) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) Mockito(org.mockito.Mockito) MetadataPage(io.gravitee.common.data.domain.MetadataPage) ReflectionTestUtils.setField(org.springframework.test.util.ReflectionTestUtils.setField) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) User(io.gravitee.repository.management.model.User) JWTHelper(io.gravitee.rest.api.service.common.JWTHelper) Assert(org.junit.Assert) USER_REGISTRATION(io.gravitee.rest.api.service.common.JWTHelper.ACTION.USER_REGISTRATION) InputStream(java.io.InputStream) MetadataPage(io.gravitee.common.data.domain.MetadataPage) Test(org.junit.Test)

Aggregations

AuditEntity (io.gravitee.rest.api.model.audit.AuditEntity)6 MetadataPage (io.gravitee.common.data.domain.MetadataPage)5 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)4 JWT (com.auth0.jwt.JWT)3 Algorithm (com.auth0.jwt.algorithms.Algorithm)3 Maps (io.gravitee.common.util.Maps)3 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)3 UserRepository (io.gravitee.repository.management.api.UserRepository)3 Membership (io.gravitee.repository.management.model.Membership)3 User (io.gravitee.repository.management.model.User)3 UserStatus (io.gravitee.repository.management.model.UserStatus)3 io.gravitee.rest.api.model (io.gravitee.rest.api.model)3 GroupMappingEntity (io.gravitee.rest.api.model.configuration.identity.GroupMappingEntity)3 RoleMappingEntity (io.gravitee.rest.api.model.configuration.identity.RoleMappingEntity)3 SocialIdentityProviderEntity (io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity)3 Key (io.gravitee.rest.api.model.parameters.Key)3 ParameterReferenceType (io.gravitee.rest.api.model.parameters.ParameterReferenceType)3 RoleScope (io.gravitee.rest.api.model.permissions.RoleScope)3 Page (io.gravitee.common.data.domain.Page)2 ExpressionEvaluationException (io.gravitee.el.exceptions.ExpressionEvaluationException)2