Search in sources :

Example 1 with EmailRequiredException

use of io.gravitee.rest.api.service.exceptions.EmailRequiredException in project gravitee-management-rest-api by gravitee-io.

the class OAuth2AuthenticationResourceTest method shouldNotConnectUserWhenMissingMailInUserInfo.

@Test
public void shouldNotConnectUserWhenMissingMailInUserInfo() throws Exception {
    // -- MOCK
    // mock environment
    mockWrongEnvironment();
    // mock oauth2 exchange authorisation code for access token
    mockExchangeAuthorizationCodeForAccessToken();
    // mock oauth2 user info call
    mockUserInfo(okJson(IOUtils.toString(read("/oauth2/json/user_info_response_body.json"), Charset.defaultCharset())));
    // mock processUser to throw EmailRequiredException
    when(userService.createOrUpdateUserFromSocialIdentityProvider(any(), any())).thenThrow(new EmailRequiredException("email"));
    // -- CALL
    AbstractAuthenticationResource.Payload payload = createPayload("the_client_id", "http://localhost/callback", "CoDe", "StAtE");
    Response response = orgTarget().request().post(json(payload));
    // -- VERIFY
    verify(userService, times(1)).createOrUpdateUserFromSocialIdentityProvider(any(), any());
    assertEquals(HttpStatusCode.BAD_REQUEST_400, response.getStatus());
    verify(userService, times(0)).connect(anyString());
    // verify jwt token not present
    assertFalse(response.getCookies().containsKey(HttpHeaders.AUTHORIZATION));
}
Also used : Response(javax.ws.rs.core.Response) EmailRequiredException(io.gravitee.rest.api.service.exceptions.EmailRequiredException) Test(org.junit.Test) AbstractResourceTest(io.gravitee.rest.api.management.rest.resource.AbstractResourceTest)

Example 2 with EmailRequiredException

use of io.gravitee.rest.api.service.exceptions.EmailRequiredException 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 3 with EmailRequiredException

use of io.gravitee.rest.api.service.exceptions.EmailRequiredException in project gravitee-management-rest-api by gravitee-io.

the class OAuth2AuthenticationResourceTest method shouldNotConnectUserWhenMissingMailInUserInfo.

@Test
public void shouldNotConnectUserWhenMissingMailInUserInfo() throws Exception {
    // -- MOCK
    // mock environment
    mockWrongEnvironment();
    // mock oauth2 exchange authorisation code for access token
    mockExchangeAuthorizationCodeForAccessToken();
    // mock oauth2 user info call
    mockUserInfo(okJson(IOUtils.toString(read("/oauth2/json/user_info_response_body.json"), Charset.defaultCharset())));
    when(userService.createOrUpdateUserFromSocialIdentityProvider(refEq(identityProvider), anyString())).thenThrow(new EmailRequiredException(USER_NAME));
    // -- CALL
    final MultivaluedMap<String, String> payload = createPayload("the_client_id", "http://localhost/callback", "CoDe");
    Response response = target().request().post(form(payload));
    // -- VERIFY
    verify(userService, times(1)).createOrUpdateUserFromSocialIdentityProvider(eq(identityProvider), anyString());
    verify(userService, times(0)).connect(anyString());
    assertEquals(HttpStatusCode.BAD_REQUEST_400, response.getStatus());
    // verify jwt token not present
    assertFalse(response.getCookies().containsKey(HttpHeaders.AUTHORIZATION));
}
Also used : EmailRequiredException(io.gravitee.rest.api.service.exceptions.EmailRequiredException) AbstractResourceTest(io.gravitee.rest.api.portal.rest.resource.AbstractResourceTest) Test(org.junit.Test)

Aggregations

EmailRequiredException (io.gravitee.rest.api.service.exceptions.EmailRequiredException)3 Test (org.junit.Test)2 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)1 Ticket (io.gravitee.repository.management.model.Ticket)1 AbstractResourceTest (io.gravitee.rest.api.management.rest.resource.AbstractResourceTest)1 AbstractResourceTest (io.gravitee.rest.api.portal.rest.resource.AbstractResourceTest)1 EmailNotificationBuilder (io.gravitee.rest.api.service.builder.EmailNotificationBuilder)1 UuidString (io.gravitee.rest.api.service.common.UuidString)1 SupportUnavailableException (io.gravitee.rest.api.service.exceptions.SupportUnavailableException)1 TechnicalManagementException (io.gravitee.rest.api.service.exceptions.TechnicalManagementException)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 Response (javax.ws.rs.core.Response)1