Search in sources :

Example 1 with AuditQuery

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

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

the class ApiAuditResource method getApiAudits.

@GET
@ApiOperation(value = "Retrieve audit logs for the API", notes = "User must have the API_AUDIT[READ] permission to use this service")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permissions({ @Permission(value = RolePermission.API_AUDIT, acls = RolePermissionAction.READ) })
public MetadataPage<AuditEntity> getApiAudits(@BeanParam AuditParam param) {
    AuditQuery query = new AuditQuery();
    query.setFrom(param.getFrom());
    query.setTo(param.getTo());
    query.setPage(param.getPage());
    query.setSize(param.getSize());
    query.setApiIds(Collections.singletonList(api));
    query.setApplicationIds(Collections.emptyList());
    query.setCurrentEnvironmentLogsOnly(false);
    query.setCurrentOrganizationLogsOnly(false);
    if (param.getEvent() != null) {
        query.setEvents(Collections.singletonList(param.getEvent()));
    }
    return auditService.search(query);
}
Also used : AuditQuery(io.gravitee.rest.api.model.audit.AuditQuery) ApiOperation(io.swagger.annotations.ApiOperation) Permissions(io.gravitee.rest.api.management.rest.security.Permissions)

Example 3 with AuditQuery

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

the class AuditResource method getAudits.

@GET
@ApiOperation(value = "Retrieve audit logs for the platform", notes = "User must have the MANAGEMENT_AUDIT[READ] permission to use this service")
@ApiResponses({ @ApiResponse(code = 200, message = "List of audits"), @ApiResponse(code = 500, message = "Internal server error") })
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permissions({ @Permission(value = RolePermission.ENVIRONMENT_AUDIT, acls = RolePermissionAction.READ) })
public MetadataPage<AuditEntity> getAudits(@BeanParam AuditParam param) {
    AuditQuery query = new AuditQuery();
    query.setFrom(param.getFrom());
    query.setTo(param.getTo());
    query.setPage(param.getPage());
    query.setSize(param.getSize());
    if (param.isEnvironmentLogsOnly()) {
        query.setCurrentEnvironmentLogsOnly(true);
    } else if (param.isOrganizationLogsOnly()) {
        query.setCurrentOrganizationLogsOnly(true);
    } else {
        if (param.getApiId() != null) {
            query.setApiIds(Collections.singletonList(param.getApiId()));
        }
        if (param.getApplicationId() != null) {
            query.setApplicationIds(Collections.singletonList(param.getApplicationId()));
        }
    }
    if (param.getEvent() != null) {
        query.setEvents(Collections.singletonList(param.getEvent()));
    }
    return auditService.search(query);
}
Also used : AuditQuery(io.gravitee.rest.api.model.audit.AuditQuery) ApiOperation(io.swagger.annotations.ApiOperation) Permissions(io.gravitee.rest.api.management.rest.security.Permissions) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

AuditQuery (io.gravitee.rest.api.model.audit.AuditQuery)3 Permissions (io.gravitee.rest.api.management.rest.security.Permissions)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 JsonPath (com.jayway.jsonpath.JsonPath)1 ReadContext (com.jayway.jsonpath.ReadContext)1 MetadataPage (io.gravitee.common.data.domain.MetadataPage)1 Page (io.gravitee.common.data.domain.Page)1 Maps (io.gravitee.common.util.Maps)1 TemplateEngine (io.gravitee.el.TemplateEngine)1 JsonPathFunction (io.gravitee.el.spel.function.json.JsonPathFunction)1 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)1 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)1 UserRepository (io.gravitee.repository.management.api.UserRepository)1 UserCriteria (io.gravitee.repository.management.api.search.UserCriteria)1 PageableBuilder (io.gravitee.repository.management.api.search.builder.PageableBuilder)1 USER (io.gravitee.repository.management.model.Audit.AuditProperties.USER)1 Membership (io.gravitee.repository.management.model.Membership)1