public async Task<ActionResult> Edit(AccountModel model)
 {
     B2CGraphClient b2CGraphClient = new B2CGraphClient(_tenant, _clientId, _clientSecret);
     await b2CGraphClient.UpdateUser(model.signInName, model.displayName, model.firstName, model.lastName, model.extension_jdrfConsId);
     ViewBag.Message = "User updated successfully!";
     return View();
 }
        public async Task <string> UpdateFeedPreference(GraphObject graphObject)
        {
            var client   = new B2CGraphClient(clientId, clientSecret, tenant);
            var response = await client.UpdateUser(graphObject.UserId, graphObject.UserJsonData);

            return(response);
        }
Esempio n. 3
0
        internal bool UpdateB2C(Dictionary <string, string> updates, string userId)
        {
            if (String.IsNullOrEmpty(userId))
            {
                return(false);
            }
            AADUser        aad    = new AADUser(tenant, id, secret);
            B2CGraphClient b2c    = new B2CGraphClient(id, secret, tenant);
            string         result = b2c.UpdateUser(userId, JsonConvert.SerializeObject(updates)).Result;

            if (!result.Contains("Error"))
            {
                return(true);
            }
            return(false);
        }
Esempio n. 4
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."
                }));
            }
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "put", Route = null)] HttpRequest req,
            ILogger log)
        {
            try
            {
                string           requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                UserProfileModel data        = JsonConvert.DeserializeObject <UserProfileModel>(requestBody);

                var results = new List <ValidationResult>();

                Validator.TryValidateObject(data, new ValidationContext(data, null, null), results, true);

                if (results.Count > 0)
                {
                    var rvalidationResponse = results.Select(p => new ResponseContentModel {
                        version = "1.0.0", userMessage = p.ErrorMessage
                    });
                    return(new BadRequestObjectResult(rvalidationResponse));
                }

                log.LogInformation(requestBody);

                if (data != null)
                {
                    if (String.IsNullOrEmpty(data.ObjectId))
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            version = "1.0.0",
                            userMessage = "Object id can't be null"
                        }));
                    }



                    if (String.IsNullOrEmpty(data.DisplayName))
                    {
                        data.DisplayName = data.FirstName + " " + data.LastName;
                    }

                    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 getUserApiResponse = await client.GetUserByObjectId(data.ObjectId);

                    if (!String.IsNullOrEmpty(getUserApiResponse))
                    {
                        var user = JsonConvert.DeserializeObject <UserValueModel>(getUserApiResponse);
                        if (user == null || String.IsNullOrEmpty(user.objectId))
                        {
                            return(new BadRequestObjectResult(new ResponseContentModel
                            {
                                userMessage = "No such a user exist. Please check the Object Id",
                            }));
                        }
                    }
                    else
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "No such a user exist. Please check the Object Id",
                        }));
                    }

                    var status = await client.UpdateUser(data.ObjectId, JsonConvert.SerializeObject(new { givenName = data.FirstName, surname = data.LastName, displayName = data.DisplayName }));

                    if (status)
                    {
                        return((ActionResult) new OkObjectResult(status));
                    }
                    else
                    {
                        return(new BadRequestObjectResult(new ResponseContentModel
                        {
                            userMessage = "Sorry, something happened unexpectedly. Couldn't update the user. Please try again later."
                        }));
                    }
                }
                else
                {
                    return(new BadRequestObjectResult(new ResponseContentModel
                    {
                        userMessage = "Please provide valid input"
                    }));
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());

                return(new BadRequestObjectResult(new ResponseContentModel
                {
                    userMessage = "Sorry, something happened unexpectedly. Couldn't update the user. Please try again later.",
                    developerMessage = "See logging provider failure dependencies for exception information."
                }));
            }
        }