Esempio n. 1
0
        public async Task <IActionResult> RegisterForNewsletter(NewsLetterRegistration registration)
        {
            // Attempt to validate the captcha code as an anti-spam mechanism.
            bool captchaPassedValidation;

            try
            {
                captchaPassedValidation = await _captcha.Validate(registration.Captcha);
            }
            catch (Exception ex)
            {
                // Error: Unknown error.
                _logger.LogError(ex, "An unknown exception occurred");

                return(BadRequest(APIError.UnknownError()));
            }

            // If the captcha failed validation, return bad request.
            if (!captchaPassedValidation)
            {
                return(BadRequest(APIError.RecaptchaFailure()));
            }

            MarketingUser marketingUser;

            try
            {
                // Register the user's email address in the database.
                marketingUser = await _newsletter.RegisterUser(registration.Name, registration.Email);
            }
            catch (MarketingUserAlreadySubscribedException ex)
            {
                // Error: User is already subscribed in the database.
                _logger.LogWarning(ex, "Failed to register marketing user. Email is already registered: {}", registration.Email);

                return(BadRequest(APIError.MarketingUserAlreadySubscribed()));
            }
            catch (Exception ex)
            {
                // Error: Unknown error.
                _logger.LogError(ex, "Exception occurred when attempting to register a marketing user.");

                return(BadRequest(APIError.UnknownError()));
            }

            try
            {
                // Send confirmation email to the user with unsubscribe link
                await _email.SendMarketWelcome(marketingUser);
            }
            catch (Exception ex)
            {
                // Error: Unknown error.
                _logger.LogError(ex, "An unknown error occurred when attempting to send marketing-welcome email.");

                return(BadRequest(APIError.UnknownError()));
            }

            return(Ok());
        }