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;
}
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());
}
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);
}
}
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));
}
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);
}
}
Aggregations