Search in sources :

Example 1 with EmailNotificationBuilder

use of io.gravitee.rest.api.service.builder.EmailNotificationBuilder in project gravitee-management-rest-api by gravitee-io.

the class ApiServiceImpl method updateWorkflowReview.

private ApiEntity updateWorkflowReview(final String apiId, final String userId, final ApiHook hook, final WorkflowState workflowState, final String workflowMessage) {
    Workflow workflow = workflowService.create(WorkflowReferenceType.API, apiId, REVIEW, userId, workflowState, workflowMessage);
    final ApiEntity apiEntity = findById(apiId);
    apiEntity.setWorkflowState(workflowState);
    final UserEntity user = userService.findById(userId);
    notifierService.trigger(hook, apiId, new NotificationParamsBuilder().api(apiEntity).user(user).build());
    // Find all reviewers of the API and send them a notification email
    if (hook.equals(ApiHook.ASK_FOR_REVIEW)) {
        List<String> reviewersEmail = findAllReviewersEmail(apiId);
        this.emailService.sendAsyncEmailNotification(new EmailNotificationBuilder().params(new NotificationParamsBuilder().api(apiEntity).user(user).build()).to(reviewersEmail.toArray(new String[reviewersEmail.size()])).template(EmailNotificationBuilder.EmailTemplate.API_ASK_FOR_REVIEW).build(), GraviteeContext.getCurrentContext());
    }
    Map<Audit.AuditProperties, String> properties = new HashMap<>();
    properties.put(Audit.AuditProperties.USER, userId);
    properties.put(Audit.AuditProperties.API, apiId);
    Workflow.AuditEvent evtType = null;
    switch(workflowState) {
        case REQUEST_FOR_CHANGES:
            evtType = API_REVIEW_REJECTED;
            break;
        case REVIEW_OK:
            evtType = API_REVIEW_ACCEPTED;
            break;
        default:
            evtType = API_REVIEW_ASKED;
            break;
    }
    auditService.createApiAuditLog(apiId, properties, evtType, new Date(), null, workflow);
    return apiEntity;
}
Also used : AuditEvent(io.gravitee.repository.management.model.Workflow.AuditEvent) UuidString(io.gravitee.rest.api.service.common.UuidString) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder) NotificationParamsBuilder(io.gravitee.rest.api.service.notification.NotificationParamsBuilder)

Example 2 with EmailNotificationBuilder

use of io.gravitee.rest.api.service.builder.EmailNotificationBuilder in project gravitee-management-rest-api by gravitee-io.

the class EmailNotifierServiceImpl method trigger.

@Override
public void trigger(final Hook hook, GenericNotificationConfig genericNotificationConfig, final Map<String, Object> params) {
    if (genericNotificationConfig == null || genericNotificationConfig.getConfig() == null || genericNotificationConfig.getConfig().isEmpty()) {
        LOGGER.error("Email Notifier configuration is empty");
        return;
    }
    EmailNotificationBuilder.EmailTemplate emailTemplate = getEmailTemplate(hook);
    if (emailTemplate == null) {
        LOGGER.error("Email template not found for hook {}", hook);
        return;
    }
    String[] mails = getMails(genericNotificationConfig, params).toArray(new String[0]);
    emailService.sendAsyncEmailNotification(new EmailNotificationBuilder().to(mails).template(emailTemplate).params(params).build(), GraviteeContext.getCurrentContext());
}
Also used : EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder)

Example 3 with EmailNotificationBuilder

use of io.gravitee.rest.api.service.builder.EmailNotificationBuilder in project gravitee-management-rest-api by gravitee-io.

the class TicketServiceImpl method create.

@Override
public TicketEntity create(final String userId, final NewTicketEntity ticketEntity, final String referenceId, final ParameterReferenceType referenceType) {
    try {
        if (!isEnabled(referenceId, referenceType)) {
            throw new SupportUnavailableException();
        }
        LOGGER.info("Creating a support ticket: {}", ticketEntity);
        final Map<String, Object> parameters = new HashMap<>();
        final UserEntity user = userService.findById(userId);
        if (user.getEmail() == null) {
            throw new EmailRequiredException(userId);
        }
        parameters.put("user", user);
        final String emailTo;
        final ApiModelEntity api;
        final ApplicationEntity applicationEntity;
        if (ticketEntity.getApi() == null || ticketEntity.getApi().isEmpty()) {
            api = null;
            final MetadataEntity emailMetadata = metadataService.findDefaultByKey(DefaultMetadataUpgrader.METADATA_EMAIL_SUPPORT_KEY);
            if (emailMetadata == null) {
                throw new IllegalStateException("The support email metadata has not been found");
            }
            emailTo = emailMetadata.getValue();
        } else {
            api = apiService.findByIdForTemplates(ticketEntity.getApi(), true);
            final String apiMetadataEmailSupport = api.getMetadata().get(DefaultMetadataUpgrader.METADATA_EMAIL_SUPPORT_KEY);
            if (apiMetadataEmailSupport == null) {
                throw new IllegalStateException("The support email API metadata has not been found");
            }
            emailTo = apiMetadataEmailSupport;
            parameters.put("api", api);
        }
        if (DefaultMetadataUpgrader.DEFAULT_METADATA_EMAIL_SUPPORT.equals(emailTo)) {
            throw new IllegalStateException("The support email API metadata has not been changed");
        }
        if (ticketEntity.getApplication() != null && !ticketEntity.getApplication().isEmpty()) {
            applicationEntity = applicationService.findById(ticketEntity.getApplication());
            parameters.put("application", applicationEntity);
        } else {
            applicationEntity = null;
        }
        parameters.put("content", ticketEntity.getContent().replaceAll("(\r\n|\n)", "<br />"));
        parameters.put("ticketSubject", ticketEntity.getSubject());
        final String fromName = user.getFirstname() == null ? user.getEmail() : user.getFirstname() + ' ' + user.getLastname();
        emailService.sendEmailNotification(new EmailNotificationBuilder().replyTo(user.getEmail()).fromName(fromName).to(emailTo).copyToSender(ticketEntity.isCopyToSender()).template(TEMPLATES_FOR_ACTION_SUPPORT_TICKET).params(parameters).build());
        sendUserNotification(user, api, applicationEntity);
        Ticket ticket = convert(ticketEntity);
        ticket.setId(UuidString.generateRandom());
        ticket.setCreatedAt(new Date());
        ticket.setFromUser(userId);
        Ticket createdTicket = ticketRepository.create(ticket);
        return convert(createdTicket);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to create a ticket {}", ticketEntity, ex);
        throw new TechnicalManagementException("An error occurs while trying to create a ticket " + ticketEntity, ex);
    }
}
Also used : Ticket(io.gravitee.repository.management.model.Ticket) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) HashMap(java.util.HashMap) EmailRequiredException(io.gravitee.rest.api.service.exceptions.EmailRequiredException) UuidString(io.gravitee.rest.api.service.common.UuidString) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder) Date(java.util.Date) SupportUnavailableException(io.gravitee.rest.api.service.exceptions.SupportUnavailableException) TechnicalManagementException(io.gravitee.rest.api.service.exceptions.TechnicalManagementException)

Example 4 with EmailNotificationBuilder

use of io.gravitee.rest.api.service.builder.EmailNotificationBuilder in project gravitee-management-rest-api by gravitee-io.

the class ScheduledSubscriptionPreExpirationNotificationServiceTest method shouldSendEmail.

@Test
public void shouldSendEmail() {
    int day = 30;
    String subscriberEmail = "subscriber@gravitee.io";
    ApiEntity api = mock(ApiEntity.class);
    // here api.getReferenceId() = environmentId
    when(api.getReferenceId()).thenReturn(UUID.randomUUID().toString());
    PlanEntity plan = mock(PlanEntity.class);
    ApplicationEntity application = mock(ApplicationEntity.class);
    ApiKeyEntity apiKey = mock(ApiKeyEntity.class);
    service.sendEmail(subscriberEmail, day, api, plan, application, apiKey);
    EmailNotification emailNotification = new EmailNotificationBuilder().to(subscriberEmail).template(EmailNotificationBuilder.EmailTemplate.TEMPLATES_FOR_ACTION_SUBSCRIPTION_PRE_EXPIRATION).param("expirationDelay", day).param("api", api).param("plan", plan).param("application", application).param("apiKey", apiKey).build();
    verify(emailService, times(1)).sendAsyncEmailNotification(eq(emailNotification), any(GraviteeContext.ReferenceContext.class));
}
Also used : ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder) Test(org.junit.Test)

Example 5 with EmailNotificationBuilder

use of io.gravitee.rest.api.service.builder.EmailNotificationBuilder 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)

Aggregations

EmailNotificationBuilder (io.gravitee.rest.api.service.builder.EmailNotificationBuilder)9 UuidString (io.gravitee.rest.api.service.common.UuidString)5 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)3 NotificationParamsBuilder (io.gravitee.rest.api.service.notification.NotificationParamsBuilder)3 Ticket (io.gravitee.repository.management.model.Ticket)2 User (io.gravitee.repository.management.model.User)2 ApiEntity (io.gravitee.rest.api.model.api.ApiEntity)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 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)1 UserRepository (io.gravitee.repository.management.api.UserRepository)1