use of com.redhat.cloud.notifications.models.EmailSubscriptionProperties in project notifications-backend by RedHatInsights.
the class InternalResource method updateDefaultBehaviorGroupActions.
@PUT
@Path("/behaviorGroups/default/{behaviorGroupId}/actions")
@Consumes(APPLICATION_JSON)
@Produces(TEXT_PLAIN)
@Operation(summary = "Update the list of actions of a default behavior group.")
@APIResponse(responseCode = "200", content = @Content(schema = @Schema(type = SchemaType.STRING)))
@Transactional
@RolesAllowed(ConsoleIdentityProvider.RBAC_INTERNAL_ADMIN)
public Response updateDefaultBehaviorGroupActions(@PathParam("behaviorGroupId") UUID behaviorGroupId, List<RequestDefaultBehaviorGroupPropertyList> propertiesList) {
if (propertiesList == null) {
throw new BadRequestException("The request body must contain a list of EmailSubscriptionProperties");
}
if (propertiesList.size() != propertiesList.stream().distinct().count()) {
throw new BadRequestException("The list of EmailSubscriptionProperties should not contain duplicates");
}
List<Endpoint> endpoints = propertiesList.stream().map(p -> {
EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
properties.setOnlyAdmins(p.isOnlyAdmins());
properties.setIgnorePreferences(p.isIgnorePreferences());
return endpointRepository.getOrCreateEmailSubscriptionEndpoint(null, properties);
}).collect(Collectors.toList());
Response.Status status = behaviorGroupRepository.updateDefaultBehaviorGroupActions(behaviorGroupId, endpoints.stream().distinct().map(Endpoint::getId).collect(Collectors.toList()));
return Response.status(status).build();
}
use of com.redhat.cloud.notifications.models.EmailSubscriptionProperties in project notifications-backend by RedHatInsights.
the class EndpointResource method getOrCreateEmailSubscriptionEndpoint.
@POST
@Path("/system/email_subscription")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@RolesAllowed(ConsoleIdentityProvider.RBAC_READ_INTEGRATIONS_ENDPOINTS)
@Transactional
public Endpoint getOrCreateEmailSubscriptionEndpoint(@Context SecurityContext sec, @NotNull @Valid RequestEmailSubscriptionProperties requestProps) {
RhIdPrincipal principal = (RhIdPrincipal) sec.getUserPrincipal();
if (requestProps.getGroupId() != null && requestProps.isOnlyAdmins()) {
throw new BadRequestException(String.format("Cannot use RBAC groups and only admins in the same endpoint"));
}
if (requestProps.getGroupId() != null) {
boolean isValid = rbacGroupValidator.validate(requestProps.getGroupId(), principal.getIdentity().rawIdentity);
if (!isValid) {
throw new BadRequestException(String.format("Invalid RBAC group identified with id %s", requestProps.getGroupId()));
}
}
// Prevent from creating not public facing properties
EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
properties.setOnlyAdmins(requestProps.isOnlyAdmins());
properties.setGroupId(requestProps.getGroupId());
return endpointRepository.getOrCreateEmailSubscriptionEndpoint(principal.getAccount(), properties);
}
use of com.redhat.cloud.notifications.models.EmailSubscriptionProperties in project notifications-backend by RedHatInsights.
the class EndpointRepository method getOrCreateEmailSubscriptionEndpoint.
@Transactional
public Endpoint getOrCreateEmailSubscriptionEndpoint(String accountId, EmailSubscriptionProperties properties) {
List<Endpoint> emailEndpoints = getEndpointsPerCompositeType(accountId, null, Set.of(new CompositeEndpointType(EndpointType.EMAIL_SUBSCRIPTION)), null, null);
loadProperties(emailEndpoints);
Optional<Endpoint> endpointOptional = emailEndpoints.stream().filter(endpoint -> properties.hasSameProperties(endpoint.getProperties(EmailSubscriptionProperties.class))).findFirst();
if (endpointOptional.isPresent()) {
return endpointOptional.get();
}
Endpoint endpoint = new Endpoint();
endpoint.setProperties(properties);
endpoint.setAccountId(accountId);
endpoint.setEnabled(true);
endpoint.setDescription("System email endpoint");
endpoint.setName("Email endpoint");
endpoint.setType(EndpointType.EMAIL_SUBSCRIPTION);
return createEndpoint(endpoint);
}
use of com.redhat.cloud.notifications.models.EmailSubscriptionProperties in project notifications-backend by RedHatInsights.
the class EndpointRepository method getOrCreateDefaultEmailSubscription.
/**
* The purpose of this method is to find or create an EMAIL_SUBSCRIPTION endpoint with empty properties. This
* endpoint is used to aggregate and store in the DB the email actions outcome, which will be used later by the
* event log. The recipients of the current email action have already been resolved before this step, possibly from
* multiple endpoints and recipients settings. The properties created below have no impact on the resolution of the
* action recipients.
*/
public Endpoint getOrCreateDefaultEmailSubscription(String accountId) {
String query = "FROM Endpoint WHERE accountId = :accountId AND compositeType.type = :endpointType";
List<Endpoint> emailEndpoints = statelessSessionFactory.getCurrentSession().createQuery(query, Endpoint.class).setParameter("accountId", accountId).setParameter("endpointType", EMAIL_SUBSCRIPTION).getResultList();
loadProperties(emailEndpoints);
EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
Optional<Endpoint> endpointOptional = emailEndpoints.stream().filter(endpoint -> properties.hasSameProperties(endpoint.getProperties(EmailSubscriptionProperties.class))).findFirst();
if (endpointOptional.isPresent()) {
return endpointOptional.get();
}
Endpoint endpoint = new Endpoint();
endpoint.setProperties(properties);
endpoint.setAccountId(accountId);
endpoint.setEnabled(true);
endpoint.setDescription("System email endpoint");
endpoint.setName("Email endpoint");
endpoint.setType(EMAIL_SUBSCRIPTION);
endpoint.prePersist();
properties.setEndpoint(endpoint);
statelessSessionFactory.getCurrentSession().insert(endpoint);
statelessSessionFactory.getCurrentSession().insert(endpoint.getProperties());
return endpoint;
}
use of com.redhat.cloud.notifications.models.EmailSubscriptionProperties in project notifications-backend by RedHatInsights.
the class EmailTest method testEmailSubscriptionInstantWrongPayload.
@Test
@Disabled
void testEmailSubscriptionInstantWrongPayload() {
mockGetUsers(8);
final String tenant = "instant-email-tenant-wrong-payload";
final String[] usernames = { "username-1", "username-2", "username-4" };
String bundle = "rhel";
String application = "policies";
for (String username : usernames) {
subscribe(tenant, username, bundle, application);
}
final List<String> bodyRequests = new ArrayList<>();
ExpectationResponseCallback verifyEmptyRequest = req -> {
assertEquals(BOP_TOKEN, req.getHeader(EmailSender.BOP_APITOKEN_HEADER).get(0));
assertEquals(BOP_CLIENT_ID, req.getHeader(EmailSender.BOP_CLIENT_ID_HEADER).get(0));
assertEquals(BOP_ENV, req.getHeader(EmailSender.BOP_ENV_HEADER).get(0));
bodyRequests.add(req.getBodyAsString());
return response().withStatusCode(200);
};
HttpRequest postReq = getMockHttpRequest(verifyEmptyRequest);
Action emailActionMessage = new Action();
emailActionMessage.setBundle(bundle);
emailActionMessage.setApplication(application);
emailActionMessage.setTimestamp(LocalDateTime.of(2020, 10, 3, 15, 22, 13, 25));
emailActionMessage.setEventType(TestHelpers.eventType);
emailActionMessage.setRecipients(List.of());
emailActionMessage.setContext(new Context.ContextBuilder().withAdditionalProperty("inventory_id-wrong", "host-01").withAdditionalProperty("system_check_in-wrong", "2020-08-03T15:22:42.199046").withAdditionalProperty("display_name-wrong", "My test machine").withAdditionalProperty("tags-what?", List.of()).build());
emailActionMessage.setEvents(List.of(new com.redhat.cloud.notifications.ingress.Event.EventBuilder().withMetadata(new Metadata.MetadataBuilder().build()).withPayload(new Payload.PayloadBuilder().withAdditionalProperty("foo", "bar").build()).build()));
emailActionMessage.setAccountId(tenant);
Event event = new Event();
event.setAction(emailActionMessage);
EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
Endpoint ep = new Endpoint();
ep.setType(EndpointType.EMAIL_SUBSCRIPTION);
ep.setName("positive feeling");
ep.setDescription("needle in the haystack");
ep.setEnabled(true);
ep.setProperties(properties);
try {
List<NotificationHistory> historyEntries = statelessSessionFactory.withSession(statelessSession -> {
return emailProcessor.process(event, List.of(ep));
});
// The processor returns a null history value but Multi does not support null values so the resulting Multi is empty.
assertTrue(historyEntries.isEmpty());
// No email, invalid payload
assertEquals(0, bodyRequests.size());
} catch (Exception e) {
e.printStackTrace();
fail(e);
} finally {
// Remove expectations
MockServerLifecycleManager.getClient().clear(postReq);
}
clearSubscriptions();
}
Aggregations