Search in sources :

Example 6 with UPDATE

use of io.gravitee.rest.api.model.permissions.RolePermissionAction.UPDATE in project gravitee-management-rest-api by gravitee-io.

the class UserServiceImpl method update.

@Override
public UserEntity update(String id, UpdateUserEntity updateUserEntity, String newsletterEmail) {
    try {
        LOGGER.debug("Updating {}", updateUserEntity);
        Optional<User> checkUser = userRepository.findById(id);
        if (!checkUser.isPresent()) {
            throw new UserNotFoundException(id);
        }
        User user = checkUser.get();
        User previousUser = new User(user);
        // Set date fields
        user.setUpdatedAt(new Date());
        // Set variant fields
        if (updateUserEntity.getPicture() != null) {
            user.setPicture(updateUserEntity.getPicture());
        }
        if (updateUserEntity.getFirstname() != null) {
            user.setFirstname(updateUserEntity.getFirstname());
        }
        if (updateUserEntity.getLastname() != null) {
            user.setLastname(updateUserEntity.getLastname());
        }
        if (updateUserEntity.getEmail() != null && !updateUserEntity.getEmail().equals(user.getEmail())) {
            if (isInternalUser(user)) {
                // sourceId can be updated only for user registered into the Gravitee Repository
                // in that case, check if the email is available before update sourceId
                final Optional<User> optionalUser = userRepository.findBySource(user.getSource(), updateUserEntity.getEmail(), user.getOrganizationId());
                if (optionalUser.isPresent()) {
                    throw new UserAlreadyExistsException(user.getSource(), updateUserEntity.getEmail(), user.getOrganizationId());
                }
                user.setSourceId(updateUserEntity.getEmail());
            }
            user.setEmail(updateUserEntity.getEmail());
        }
        if (updateUserEntity.getStatus() != null) {
            user.setStatus(UserStatus.valueOf(updateUserEntity.getStatus()));
        }
        if (updateUserEntity.isNewsletter() != null) {
            user.setNewsletterSubscribed(updateUserEntity.isNewsletter());
            if (updateUserEntity.isNewsletter() && newsletterEmail != null) {
                newsletterService.subscribe(newsletterEmail);
            }
        }
        User updatedUser = userRepository.update(user);
        auditService.createOrganizationAuditLog(Collections.singletonMap(USER, user.getId()), User.AuditEvent.USER_UPDATED, user.getUpdatedAt(), previousUser, user);
        List<UserMetadataEntity> updatedMetadata = new ArrayList<>();
        if (updateUserEntity.getCustomFields() != null && !updateUserEntity.getCustomFields().isEmpty()) {
            List<UserMetadataEntity> metadata = userMetadataService.findAllByUserId(user.getId());
            for (Map.Entry<String, Object> entry : updateUserEntity.getCustomFields().entrySet()) {
                Optional<UserMetadataEntity> existingMeta = metadata.stream().filter(meta -> meta.getKey().equals(entry.getKey())).findFirst();
                if (existingMeta.isPresent()) {
                    UserMetadataEntity meta = existingMeta.get();
                    UpdateUserMetadataEntity metadataEntity = new UpdateUserMetadataEntity();
                    metadataEntity.setName(meta.getName());
                    metadataEntity.setKey(meta.getKey());
                    metadataEntity.setValue(String.valueOf(entry.getValue()));
                    metadataEntity.setUserId(meta.getUserId());
                    metadataEntity.setFormat(meta.getFormat());
                    updatedMetadata.add(userMetadataService.update(metadataEntity));
                } else {
                    // some additional fields may have been added after the user registration
                    NewUserMetadataEntity metadataEntity = new NewUserMetadataEntity();
                    metadataEntity.setName(entry.getKey());
                    metadataEntity.setValue(String.valueOf(entry.getValue()));
                    metadataEntity.setUserId(user.getId());
                    metadataEntity.setFormat(MetadataFormat.STRING);
                    updatedMetadata.add(userMetadataService.create(metadataEntity));
                }
            }
        }
        return convert(updatedUser, true, updatedMetadata);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to update {}", updateUserEntity, ex);
        throw new TechnicalManagementException("An error occurs while trying update " + updateUserEntity, 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) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) UuidString(io.gravitee.rest.api.service.common.UuidString)

Aggregations

Page (io.gravitee.common.data.domain.Page)6 UPDATE (io.gravitee.rest.api.model.permissions.RolePermissionAction.UPDATE)6 EnvironmentEntity (io.gravitee.rest.api.model.EnvironmentEntity)5 ApiEntity (io.gravitee.rest.api.model.api.ApiEntity)5 RolePermission (io.gravitee.rest.api.model.permissions.RolePermission)5 CREATE (io.gravitee.rest.api.model.permissions.RolePermissionAction.CREATE)5 PromotionService (io.gravitee.rest.api.service.promotion.PromotionService)5 java.util (java.util)5 Collections.singletonList (java.util.Collections.singletonList)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 TaskEntity (io.gravitee.rest.api.model.TaskEntity)4 PromotionEntity (io.gravitee.rest.api.model.promotion.PromotionEntity)4 PromotionEntityAuthor (io.gravitee.rest.api.model.promotion.PromotionEntityAuthor)4 PromotionEntityStatus (io.gravitee.rest.api.model.promotion.PromotionEntityStatus)4 ApiService (io.gravitee.rest.api.service.ApiService)4 EnvironmentService (io.gravitee.rest.api.service.EnvironmentService)4 PermissionService (io.gravitee.rest.api.service.PermissionService)4 PromotionTasksService (io.gravitee.rest.api.service.promotion.PromotionTasksService)4 Collections.emptyList (java.util.Collections.emptyList)4