Search in sources :

Example 6 with EmailNotificationBuilder

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

the class MembershipServiceImpl method buildEmailNotification.

private EmailNotification buildEmailNotification(UserEntity user, MembershipReferenceType referenceType, String referenceId) {
    EmailNotificationBuilder.EmailTemplate template = null;
    Map<String, Object> params = null;
    GroupEntity groupEntity;
    NotificationParamsBuilder paramsBuilder = new NotificationParamsBuilder();
    switch(referenceType) {
        case APPLICATION:
            ApplicationEntity applicationEntity = applicationService.findById(referenceId);
            template = EmailNotificationBuilder.EmailTemplate.TEMPLATES_FOR_ACTION_APPLICATION_MEMBER_SUBSCRIPTION;
            params = paramsBuilder.application(applicationEntity).user(user).build();
            break;
        case API:
            ApiEntity apiEntity = apiService.findById(referenceId);
            template = EmailNotificationBuilder.EmailTemplate.TEMPLATES_FOR_ACTION_API_MEMBER_SUBSCRIPTION;
            params = paramsBuilder.api(apiEntity).user(user).build();
            break;
        case GROUP:
            groupEntity = groupService.findById(referenceId);
            template = EmailNotificationBuilder.EmailTemplate.TEMPLATES_FOR_ACTION_GROUP_MEMBER_SUBSCRIPTION;
            params = paramsBuilder.group(groupEntity).user(user).build();
            break;
        default:
            break;
    }
    if (template == null) {
        return null;
    }
    return new EmailNotificationBuilder().to(user.getEmail()).template(template).params(params).build();
}
Also used : ApiEntity(io.gravitee.rest.api.model.api.ApiEntity) 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 7 with EmailNotificationBuilder

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

the class TicketServiceTest method shouldCreateWithApi.

@Test
public void shouldCreateWithApi() throws TechnicalException {
    when(mockParameterService.findAsBoolean(Key.CONSOLE_SUPPORT_ENABLED, REFERENCE_ID, REFERENCE_TYPE)).thenReturn(Boolean.TRUE);
    when(newTicketEntity.getApi()).thenReturn(API_ID);
    when(newTicketEntity.getApplication()).thenReturn(APPLICATION_ID);
    when(newTicketEntity.getSubject()).thenReturn(EMAIL_SUBJECT);
    when(newTicketEntity.isCopyToSender()).thenReturn(EMAIL_COPY_TO_SENDER);
    when(newTicketEntity.getContent()).thenReturn(EMAIL_CONTENT);
    when(userService.findById(USERNAME)).thenReturn(user);
    when(user.getEmail()).thenReturn(USER_EMAIL);
    when(user.getFirstname()).thenReturn(USER_FIRSTNAME);
    when(user.getLastname()).thenReturn(USER_LASTNAME);
    when(apiService.findByIdForTemplates(API_ID, true)).thenReturn(api);
    when(applicationService.findById(APPLICATION_ID)).thenReturn(application);
    Ticket ticketToCreate = new Ticket();
    ticketToCreate.setId("generatedId");
    ticketToCreate.setApi(API_ID);
    ticketToCreate.setApplication(APPLICATION_ID);
    ticketToCreate.setSubject(EMAIL_SUBJECT);
    ticketToCreate.setContent(EMAIL_CONTENT);
    ticketToCreate.setCreatedAt(new Date());
    ticketToCreate.setFromUser(USERNAME);
    when(ticketRepository.create(any(Ticket.class))).thenReturn(ticketToCreate);
    final Map<String, String> metadata = new HashMap<>();
    metadata.put(DefaultMetadataUpgrader.METADATA_EMAIL_SUPPORT_KEY, EMAIL_SUPPORT);
    when(api.getMetadata()).thenReturn(metadata);
    TicketEntity createdTicket = ticketService.create(USERNAME, newTicketEntity, REFERENCE_ID, REFERENCE_TYPE);
    verify(emailService).sendEmailNotification(new EmailNotificationBuilder().replyTo(USER_EMAIL).fromName(USER_FIRSTNAME + ' ' + USER_LASTNAME).to(EMAIL_SUPPORT).copyToSender(EMAIL_COPY_TO_SENDER).template(TEMPLATES_FOR_ACTION_SUPPORT_TICKET).params(ImmutableMap.of("user", user, "api", api, "content", "Email<br />Content", "application", application, "ticketSubject", EMAIL_SUBJECT)).build());
    verify(mockNotifierService, times(1)).trigger(eq(PortalHook.NEW_SUPPORT_TICKET), anyMap());
    assertEquals("Invalid saved ticket id", createdTicket.getId(), ticketToCreate.getId());
    assertEquals("Invalid saved ticket api", createdTicket.getApi(), ticketToCreate.getApi());
    assertEquals("Invalid saved ticket application", createdTicket.getApplication(), ticketToCreate.getApplication());
    assertEquals("Invalid saved ticket subject", createdTicket.getSubject(), ticketToCreate.getSubject());
    assertEquals("Invalid saved ticket content", createdTicket.getContent(), ticketToCreate.getContent());
    assertEquals("Invalid saved ticket from user", createdTicket.getFromUser(), ticketToCreate.getFromUser());
    assertEquals("Invalid saved ticket created at", createdTicket.getCreatedAt(), ticketToCreate.getCreatedAt());
}
Also used : Ticket(io.gravitee.repository.management.model.Ticket) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder) Test(org.junit.Test)

Example 8 with EmailNotificationBuilder

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

the class UserServiceImpl method createAndSendEmail.

/**
 * Allows to create an user and send an email notification to finalize its creation.
 */
private UserEntity createAndSendEmail(final NewExternalUserEntity newExternalUserEntity, final ACTION action, final String confirmationPageUrl, final boolean autoRegistrationEnabled) {
    if (!EmailValidator.isValid(newExternalUserEntity.getEmail())) {
        throw new EmailFormatInvalidException(newExternalUserEntity.getEmail());
    }
    String organizationId = GraviteeContext.getCurrentOrganization();
    if (isBlank(newExternalUserEntity.getSource())) {
        newExternalUserEntity.setSource(IDP_SOURCE_GRAVITEE);
    } else {
        if (!IDP_SOURCE_GRAVITEE.equals(newExternalUserEntity.getSource())) {
            // check if IDP exists
            identityProviderService.findById(newExternalUserEntity.getSource());
        }
    }
    if (isBlank(newExternalUserEntity.getSourceId())) {
        newExternalUserEntity.setSourceId(newExternalUserEntity.getEmail());
    }
    final Optional<User> optionalUser;
    try {
        optionalUser = userRepository.findBySource(newExternalUserEntity.getSource(), newExternalUserEntity.getSourceId(), organizationId);
        if (optionalUser.isPresent()) {
            throw new UserAlreadyExistsException(newExternalUserEntity.getSource(), newExternalUserEntity.getSourceId(), organizationId);
        }
    } catch (final TechnicalException e) {
        LOGGER.error("An error occurs while trying to create user {} / {}", newExternalUserEntity.getSource(), newExternalUserEntity.getSourceId(), e);
        throw new TechnicalManagementException(e.getMessage(), e);
    }
    final UserEntity userEntity = create(newExternalUserEntity, true, autoRegistrationEnabled);
    if (IDP_SOURCE_GRAVITEE.equals(newExternalUserEntity.getSource())) {
        final Map<String, Object> params = getTokenRegistrationParams(userEntity, REGISTRATION_PATH, action, confirmationPageUrl);
        emailService.sendAsyncEmailNotification(new EmailNotificationBuilder().to(userEntity.getEmail()).template(EmailNotificationBuilder.EmailTemplate.TEMPLATES_FOR_ACTION_USER_REGISTRATION).params(params).param("registrationAction", USER_REGISTRATION.equals(action) ? "registration" : "creation").build(), GraviteeContext.getCurrentContext());
        if (autoRegistrationEnabled) {
            notifierService.trigger(ACTION.USER_REGISTRATION.equals(action) ? PortalHook.USER_REGISTERED : PortalHook.USER_CREATED, params);
        } else {
            notifierService.trigger(PortalHook.USER_REGISTRATION_REQUEST, params);
        }
    }
    if (newExternalUserEntity.getNewsletter() != null && newExternalUserEntity.getNewsletter()) {
        newsletterService.subscribe(newExternalUserEntity.getEmail());
    }
    return userEntity;
}
Also used : User(io.gravitee.repository.management.model.User) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) UuidString(io.gravitee.rest.api.service.common.UuidString) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder)

Example 9 with EmailNotificationBuilder

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

the class MessageServiceImpl method send.

private int send(Api api, MessageEntity message, Set<String> recipientsId) {
    switch(message.getChannel()) {
        case MAIL:
            Set<String> mails = getRecipientsEmails(recipientsId);
            if (!mails.isEmpty()) {
                emailService.sendAsyncEmailNotification(new EmailNotificationBuilder().to(EmailService.DEFAULT_MAIL_TO).bcc(mails.toArray(new String[0])).template(EmailNotificationBuilder.EmailTemplate.TEMPLATES_FOR_ACTION_GENERIC_MESSAGE).param("message", message.getText()).param("messageSubject", message.getTitle()).build(), GraviteeContext.getCurrentContext());
            }
            return mails.size();
        case PORTAL:
            Hook hook = api == null ? PortalHook.MESSAGE : ApiHook.MESSAGE;
            portalNotificationService.create(hook, new ArrayList<>(recipientsId), getPortalParams(api, message));
            return recipientsId.size();
        case HTTP:
            if (!httpEnabled) {
                throw new NotifierDisabledException();
            }
            String url = recipientsId.iterator().next();
            environment.getProperty("notifiers.webhook.whitelist");
            if (httpWhitelist != null && !httpWhitelist.isEmpty()) {
                // Check the provided url is allowed.
                if (httpWhitelist.stream().noneMatch(whitelistUrl -> whitelistUrl.endsWith("/") ? url.startsWith(whitelistUrl) : (url.equals(whitelistUrl) || url.startsWith(whitelistUrl + '/')))) {
                    throw new MessageUrlForbiddenException();
                }
            }
            httpClientService.request(HttpMethod.POST, url, message.getParams(), getPostMessage(api, message), Boolean.valueOf(message.isUseSystemProxy()));
            return 1;
        default:
            return 0;
    }
}
Also used : ApiHook(io.gravitee.rest.api.service.notification.ApiHook) Hook(io.gravitee.rest.api.service.notification.Hook) PortalHook(io.gravitee.rest.api.service.notification.PortalHook) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder)

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