public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            try
            {
                log.LogInformation("Request started");

                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                var    data        = JsonConvert.DeserializeObject <SignupInvitationModel>(requestBody);
                log.LogInformation(requestBody);

                if (String.IsNullOrEmpty(data.CustomerId) || String.IsNullOrEmpty(data.Email) || String.IsNullOrEmpty(data.GivenName) ||
                    String.IsNullOrEmpty(data.LastName))
                {
                    return(new BadRequestObjectResult(new ResponseContentModel
                    {
                        userMessage = "Please check the input",
                    }));
                }

                using (var httpClient = new HttpClient())
                {
                    var getApiUrl = _appSettings.NcsDssGetCustomerApiUrl;
                    var dssApiUrl = String.Format(getApiUrl, data.CustomerId);

                    log.LogInformation(getApiUrl);

                    using (var request = new HttpRequestMessage(new HttpMethod("GET"), dssApiUrl))
                    {
                        request.Headers.TryAddWithoutValidation("api-key", _appSettings.NcsDssApiKey);
                        request.Headers.TryAddWithoutValidation("version", _appSettings.NcsDssCustomersApiVersion);
                        request.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", _appSettings.OcpApimSubscriptionKey);
                        request.Headers.TryAddWithoutValidation("TouchpointId", _appSettings.TouchpointId.ToString());

                        var response = await httpClient.SendAsync(request);

                        log.LogInformation(response.StatusCode.GetDisplayName() + " - " + response.StatusCode.ToString());

                        if (response.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            var content = await response.Content.ReadAsStringAsync();

                            var customer = JsonConvert.DeserializeObject <CustomerModel>(content);

                            if (customer == null)
                            {
                                return(new BadRequestObjectResult(new ResponseContentModel
                                {
                                    userMessage = "We have not been able to find your account"
                                }));
                            }
                            else
                            {
                                if (data.GivenName.ToLower() == customer.GivenName.ToLower() && data.LastName.ToLower() == customer.FamilyName.ToLower())
                                {
                                    data.CustomerId = customer.CustomerId.ToString();
                                }
                                else
                                {
                                    return(new BadRequestObjectResult(new ResponseContentModel
                                    {
                                        userMessage = "We have not been able to find your account"
                                    }));
                                }

                                var accountActivationEmailExpiryInSeconds = Convert.ToInt32(_appSettings.AccountActivationEmailExpiryInSeconds);//Environment.GetEnvironmentVariable("AccountActivationEmailExpiryInSeconds", EnvironmentVariableTarget.Process));

                                string token          = TokenBuilder.BuildIdToken(data.Email.ToString(), data.GivenName.ToString(), data.LastName.ToString(), data.CustomerId.ToString(), DateTime.UtcNow.AddSeconds(accountActivationEmailExpiryInSeconds), req.Scheme, req.Host.Value, req.PathBase.Value, "aidedsignup", _appSettings.ClientSigningKey, _appSettings.RelyingPartyAppClientId.ToString());
                                string b2cURL         = _appSettings.B2CAuthorizationUrl;                // Environment.GetEnvironmentVariable("B2CAuthorizationUrl", EnvironmentVariableTarget.Process);
                                string b2cTenant      = _appSettings.B2CTenant;                          //Environment.GetEnvironmentVariable("B2CTenant", EnvironmentVariableTarget.Process);
                                string b2cPolicyId    = _appSettings.B2CSignUpPolicy;                    //Environment.GetEnvironmentVariable("B2CSignUpPolicy", EnvironmentVariableTarget.Process);
                                string b2cClientId    = _appSettings.RelyingPartyAppClientId.ToString(); //Environment.GetEnvironmentVariable("RelyingPartyAppClientId", EnvironmentVariableTarget.Process);
                                string b2cRedirectUri = _appSettings.B2CRedirectUri.ToString();          //Environment.GetEnvironmentVariable("B2CRedirectUri", EnvironmentVariableTarget.Process);
                                string url            = UrlBuilder.BuildUrl(token, b2cURL, b2cTenant, b2cPolicyId, b2cClientId, b2cRedirectUri);

                                string htmlTemplate = _appSettings.NotifyAidedSignupEmailTemplateId.ToString(); //Environment.GetEnvironmentVariable("NotifyAidedSignupEmailTemplateId", EnvironmentVariableTarget.Process);

                                EmailModel model = new EmailModel
                                {
                                    EmailTemplate   = htmlTemplate,
                                    To              = data.Email.ToString(),
                                    Personalisation = new Dictionary <string, dynamic>
                                    {
                                        { "name", data.GivenName.ToString() },
                                        { "link", url }
                                    }
                                };

                                var result = EmailService.Send(_appSettings.NotifyApiKey, model);
                                return(result
                                    ? (ActionResult) new OkObjectResult(true)
                                    : new BadRequestObjectResult(new ResponseContentModel
                                {
                                    userMessage = "Couldn't send email to user."
                                }));
                            }
                        }
                        else
                        {
                            log.LogInformation(dssApiUrl);
                            return(new BadRequestObjectResult(new ResponseContentModel
                            {
                                userMessage = "Failed to fetch customer details, please contact support",
                                developerMessage = "Apikey: " + _appSettings.NcsDssApiKey + " TouchPointId" + _appSettings.TouchpointId.ToString() + " NcsDssSearchApiVersion:" + _appSettings.NcsDssCustomersApiVersion
                                                   + " OcpApimSubscriptionKey:" + _appSettings.OcpApimSubscriptionKey
                            }));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());
                log.LogInformation(ex.ToString());
                return(new BadRequestObjectResult(new ResponseContentModel
                {
                    userMessage = "Sorry, Something happened unexpectedly. Please try after sometime.",
                    developerMessage = "See logging provider failure dependencies for exception information."
                }));
            }
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            try
            {
                log.LogInformation("Request started");

                string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data        = JsonConvert.DeserializeObject(requestBody);
                log.LogInformation(requestBody);
                var accountActivationEmailExpiryInSeconds = _appSettings.AccountActivationEmailExpiryInSeconds;// Convert.ToInt32(Environment.GetEnvironmentVariable("AccountActivationEmailExpiryInSeconds", EnvironmentVariableTarget.Process));


                string token = TokenBuilder.BuildIdToken(data.email.ToString(), DateTime.UtcNow.AddSeconds(accountActivationEmailExpiryInSeconds), req.Scheme, req.Host.Value, req.PathBase.Value, data.ObjectId.ToString(), data.givenName.ToString(), "passwordreset", _appSettings.ClientSigningKey, _appSettings.RelyingPartyAppClientId.ToString());

                string b2cURL         = _appSettings.B2CAuthorizationUrl;                // Environment.GetEnvironmentVariable("B2CAuthorizationUrl", EnvironmentVariableTarget.Process);
                string b2cTenant      = _appSettings.B2CTenant;                          //Environment.GetEnvironmentVariable("B2CTenant", EnvironmentVariableTarget.Process);
                string b2cPolicyId    = _appSettings.B2CPasswordResetConfirmPolicy;      //Environment.GetEnvironmentVariable("B2CSignUpPolicy", EnvironmentVariableTarget.Process);
                string b2cClientId    = _appSettings.RelyingPartyAppClientId.ToString(); //Environment.GetEnvironmentVariable("RelyingPartyAppClientId", EnvironmentVariableTarget.Process);
                string b2cRedirectUri = _appSettings.B2CRedirectUri.ToString();          //Environment.GetEnvironmentVariable("B2CRedirectUri", EnvironmentVariableTarget.Process);

                string url = UrlBuilder.BuildUrl(token, b2cURL, b2cTenant, b2cPolicyId, b2cClientId, b2cRedirectUri);

                string htmlTemplate = _appSettings.NotifyPasswordResetConfirmationEmailTemplateId.ToString();// Environment.GetEnvironmentVariable("NotifyPasswordResetConfirmationEmailTemplateId", EnvironmentVariableTarget.Process);


                EmailModel model = new EmailModel
                {
                    EmailTemplate   = htmlTemplate,
                    To              = data.email.ToString(),
                    Personalisation = new Dictionary <string, dynamic>
                    {
                        { "name", data.givenName.ToString() },
                        { "link", url }
                    }
                };

                var result = EmailService.Send(_appSettings.NotifyApiKey, model);
                return(result
                    ? (ActionResult) new OkObjectResult(true)
                    : new BadRequestObjectResult(new ResponseContentModel
                {
                    userMessage = "Something happened unexpectedly.",
                    version = "1.0.0",
                    status = 400,
                    code = "API12345",
                    requestId = "50f0bd91-2ff4-4b8f-828f-00f170519ddb",
                    developerMessage = "Email sent failed.",
                    moreInfo = "https://restapi/error/API12345/moreinfo"
                }));
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());

                return(new BadRequestObjectResult(new ResponseContentModel
                {
                    userMessage = ex.ToString(),
                    version = "1.0.0",
                    status = 400,
                    code = "API12345",
                    requestId = "50f0bd91-2ff4-4b8f-828f-00f170519ddb",
                    developerMessage = "See logging provider failure dependencies for exception information.",
                    moreInfo = "https://restapi/error/API12345/moreinfo"
                }));
            }
        }
示例#3
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            try
            {
                log.LogInformation("Request started");
                string           requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                ChangeEmailModel data        = JsonConvert.DeserializeObject <ChangeEmailModel>(requestBody);
                log.LogInformation(requestBody);

                string         tenant       = _appSettings.B2CTenantId;                       // Environment.GetEnvironmentVariable("B2CTenantId", EnvironmentVariableTarget.Process);
                string         clientId     = _appSettings.B2CGraphAccessClientId.ToString(); // Environment.GetEnvironmentVariable("B2CGraphAccessClientId", EnvironmentVariableTarget.Process);
                string         clientSecret = _appSettings.B2CGraphAccessClientSecret;        // Environment.GetEnvironmentVariable("B2CGraphAccessClientSecret", EnvironmentVariableTarget.Process);
                B2CGraphClient client       = new B2CGraphClient(clientId, clientSecret, tenant);

                var newUser = await client.GetAllUsersAsync("$filter=signInNames/any(x:x/value eq '" + HttpUtility.UrlEncode(data.NewEmail) + "')");

                UserDetailsModel newUserDetails = JsonConvert.DeserializeObject <UserDetailsModel>(newUser);

                if (newUserDetails.value.Count > 0)
                {
                    return(new BadRequestObjectResult(new ResponseContentModel
                    {
                        userMessage = "Sorry, This email already exists",
                    }));
                }

                var currentUser = await client.GetUserByObjectId(data.ObjectId);

                if (!String.IsNullOrEmpty(currentUser))
                {
                    UserValueModel user = JsonConvert.DeserializeObject <UserValueModel>(currentUser);
                    log.LogInformation(currentUser);

                    if (user == null)
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Sorry, This user doesn't exists.",
                        }));
                    }

                    bool updateResult = false;

                    if (!data.IsResend)
                    {
                        var    extensionAppId = _appSettings.ExtensionAppId;// Environment.GetEnvironmentVariable("ExtensionAppId", EnvironmentVariableTarget.Process);
                        string json           = "{\"extension_" + extensionAppId + "_IsEmailChangeRequested\":\"true\",\"extension_" + extensionAppId + "_NewEmail\":\"" + data.NewEmail + "\"}";
                        try
                        {
                            updateResult = await client.UpdateUser(data.ObjectId, json);
                        }
                        catch (Exception)
                        {
                            return(new BadRequestObjectResult(new ResponseContentModel
                            {
                                userMessage = "Sorry, something happened unexpectedly while updating AD user.",
                            }));
                        }
                    }

                    if (updateResult || data.IsResend)
                    {
                        var accountActivationEmailExpiryInSeconds = _appSettings.AccountActivationEmailExpiryInSeconds;// Convert.ToInt32(Environment.GetEnvironmentVariable("AccountActivationEmailExpiryInSeconds", EnvironmentVariableTarget.Process));


                        string token = TokenBuilder.BuildIdToken(user.signInNames.FirstOrDefault().value, data.NewEmail, DateTime.UtcNow.AddSeconds(accountActivationEmailExpiryInSeconds), req.Scheme, req.Host.Value, req.PathBase.Value, data.ObjectId, "changeemail", _appSettings.ClientSigningKey, _appSettings.RelyingPartyAppClientId.ToString());

                        string b2cURL         = _appSettings.B2CAuthorizationUrl;                // Environment.GetEnvironmentVariable("B2CAuthorizationUrl", EnvironmentVariableTarget.Process);
                        string b2cTenant      = _appSettings.B2CTenant;                          // Environment.GetEnvironmentVariable("B2CTenant", EnvironmentVariableTarget.Process);
                        string b2cPolicyId    = _appSettings.B2CChangeEmailPolicy;               // Environment.GetEnvironmentVariable("B2CChangeEmailPolicy", EnvironmentVariableTarget.Process);
                        string b2cClientId    = _appSettings.RelyingPartyAppClientId.ToString(); // Environment.GetEnvironmentVariable("RelyingPartyAppClientId", EnvironmentVariableTarget.Process);
                        string b2cRedirectUri = _appSettings.B2CRedirectUri.ToString();          // Environment.GetEnvironmentVariable("B2CRedirectUri", EnvironmentVariableTarget.Process);
                        string url            = UrlBuilder.BuildUrl(token, b2cURL, b2cTenant, b2cPolicyId, b2cClientId, b2cRedirectUri);

                        string htmlTemplateOldEmail = _appSettings.NotifyEmailChangeConfirmationEmailOldEmailTemplateId.ToString(); // Environment.GetEnvironmentVariable("NotifyEmailChangeConfirmationEmailOldEmailTemplateId", EnvironmentVariableTarget.Process);
                        string htmlTemplateNewEmail = _appSettings.NotifyEmailChangeConfirmationEmailNewEmailTemplateId.ToString(); //Environment.GetEnvironmentVariable("NotifyEmailChangeConfirmationEmailNewEmailTemplateId", EnvironmentVariableTarget.Process);

                        bool       result2 = false;
                        EmailModel model   = new EmailModel
                        {
                            EmailTemplate   = htmlTemplateNewEmail,
                            To              = data.NewEmail.ToString(),
                            Personalisation = new Dictionary <string, dynamic>
                            {
                                { "name", user.givenName },
                                { "link", url }
                            }
                        };

                        var result1 = EmailService.Send(_appSettings.NotifyApiKey, model);

                        if (!data.IsResend)
                        {
                            model = new EmailModel
                            {
                                EmailTemplate   = htmlTemplateOldEmail,
                                To              = user.signInNames.FirstOrDefault().value,
                                Personalisation = new Dictionary <string, dynamic>
                                {
                                    { "name", user.givenName }
                                }
                            };

                            result2 = EmailService.Send(_appSettings.NotifyApiKey, model);
                        }
                        else
                        {
                            result2 = true;
                        }

                        if (result1 && result2 & data.SendTokenBackRequired)
                        {
                            return((ActionResult) new OkObjectResult(new { id_token_hint = token }));
                        }

                        return(result1 && result2
                            ? (ActionResult) new OkObjectResult(true)
                            : new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Failed to sent email, please contact support."
                        }));
                    }
                    else
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Sorry, Something happened unexpectedly. Please try after sometime."
                        }));
                    }
                }
                else
                {
                    return(new BadRequestObjectResult(new ResponseContentModel
                    {
                        userMessage = "Sorry, This user doesn't exists.",
                    }));
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());

                return(new BadRequestObjectResult(new ResponseContentModel
                {
                    userMessage = "Sorry, Something happened unexpectedly. Please try after sometime.",
                    developerMessage = "See logging provider failure dependencies for exception information."
                }));
            }
        }