Search in sources :

Example 1 with ThunderException

use of com.sanctionco.thunder.ThunderException in project thunder by RohanNagar.

the class VerificationResource method sendEmail.

/**
 * Sends an email message to the given email address. The email message will contain
 * a custom URL that can be called to verify the email address. This method will update the user
 * in the database to include the generated verification token.
 *
 * @param uriInfo the HTTP metadata of the incoming request
 * @param response the async response object used to notify that the operation has completed
 * @param auth the auth principal required to access the resource
 * @param email the message recipient's email address
 * @param password the user's password
 *
 * @see VerificationResource#verifyEmail(AsyncResponse, String, String, ResponseType)
 */
@POST
@Metered(name = "send-email-requests")
@SwaggerAnnotations.Methods.Email
public void sendEmail(@Context UriInfo uriInfo, @Suspended AsyncResponse response, @Parameter(hidden = true) @Auth Principal auth, @Parameter(hidden = true) @QueryParam("email") String email, @Parameter(hidden = true) @HeaderParam("password") String password) {
    requestOptions.setTimeout(response, sendEmailTimeoutCounter);
    try {
        requestValidator.validate(password, email, false);
    } catch (RequestValidationException e) {
        response.resume(e.response(email));
        return;
    }
    LOG.info("Attempting to send verification email to user {}", email);
    usersDao.findByEmail(email).thenApply(user -> {
        // Check that the supplied password is correct for the user's account
        requestValidator.verifyPasswordHeader(password, user.getPassword());
        // Generate the unique verification token
        String token = generateVerificationToken();
        // Update the user's verification token
        return new User(new Email(user.getEmail().getAddress(), false, token), user.getPassword(), user.getProperties());
    }).thenCompose(user -> usersDao.update(user.getEmail().getAddress(), user)).thenCompose(result -> {
        // Build the verification URL
        String verificationUrl = uriInfo.getBaseUriBuilder().path("/verify").queryParam("email", result.getEmail().getAddress()).queryParam("token", result.getEmail().getVerificationToken()).queryParam("response_type", "html").build().toString();
        LOG.info("Built verification URL {}", verificationUrl);
        // Send the email to the user's email address
        return emailService.sendVerificationEmail(result.getEmail(), verificationUrl).thenApply(success -> {
            if (!success) {
                LOG.error("Error sending email to address {}", result.getEmail().getAddress());
                throw new ThunderException("An error occurred while attempting to send email.");
            }
            return result;
        });
    }).whenComplete((result, throwable) -> {
        if (Objects.isNull(throwable)) {
            LOG.info("Successfully sent verification email to user {}.", email);
            response.resume(Response.ok(result).build());
        } else {
            LOG.error("Error sending email to {}. Caused by: {}", email, throwable.getMessage());
            response.resume(ThunderException.responseFromThrowable(throwable, email));
        }
    });
}
Also used : Email(com.sanctionco.thunder.models.Email) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) Auth(io.dropwizard.auth.Auth) ResponseType(com.sanctionco.thunder.models.ResponseType) SwaggerAnnotations(com.sanctionco.thunder.openapi.SwaggerAnnotations) Inject(javax.inject.Inject) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Counter(com.codahale.metrics.Counter) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) RequestValidationException(com.sanctionco.thunder.validation.RequestValidationException) MetricRegistry(com.codahale.metrics.MetricRegistry) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) Logger(org.slf4j.Logger) Metered(com.codahale.metrics.annotation.Metered) AsyncResponse(javax.ws.rs.container.AsyncResponse) UUID(java.util.UUID) Suspended(javax.ws.rs.container.Suspended) EmailService(com.sanctionco.thunder.email.EmailService) Parameter(io.swagger.v3.oas.annotations.Parameter) Objects(java.util.Objects) Principal(java.security.Principal) User(com.sanctionco.thunder.models.User) Response(javax.ws.rs.core.Response) MetricNameUtil(com.sanctionco.thunder.util.MetricNameUtil) ThunderException(com.sanctionco.thunder.ThunderException) UriInfo(javax.ws.rs.core.UriInfo) UsersDao(com.sanctionco.thunder.dao.UsersDao) RequestValidator(com.sanctionco.thunder.validation.RequestValidator) User(com.sanctionco.thunder.models.User) Email(com.sanctionco.thunder.models.Email) ThunderException(com.sanctionco.thunder.ThunderException) RequestValidationException(com.sanctionco.thunder.validation.RequestValidationException) Metered(com.codahale.metrics.annotation.Metered) POST(javax.ws.rs.POST)

Aggregations

Counter (com.codahale.metrics.Counter)1 MetricRegistry (com.codahale.metrics.MetricRegistry)1 Metered (com.codahale.metrics.annotation.Metered)1 ThunderException (com.sanctionco.thunder.ThunderException)1 UsersDao (com.sanctionco.thunder.dao.UsersDao)1 EmailService (com.sanctionco.thunder.email.EmailService)1 Email (com.sanctionco.thunder.models.Email)1 ResponseType (com.sanctionco.thunder.models.ResponseType)1 User (com.sanctionco.thunder.models.User)1 SwaggerAnnotations (com.sanctionco.thunder.openapi.SwaggerAnnotations)1 MetricNameUtil (com.sanctionco.thunder.util.MetricNameUtil)1 RequestValidationException (com.sanctionco.thunder.validation.RequestValidationException)1 RequestValidator (com.sanctionco.thunder.validation.RequestValidator)1 Auth (io.dropwizard.auth.Auth)1 Parameter (io.swagger.v3.oas.annotations.Parameter)1 URI (java.net.URI)1 Principal (java.security.Principal)1 Objects (java.util.Objects)1 UUID (java.util.UUID)1 Inject (javax.inject.Inject)1