Пример #1
0
        public async Task <IActionResult> Update(PageModel <UserModel> model)
        {
            UpdateUserResult updateResult = await _userServices.Update(model.ViewModel);

            IList <string> comments = new List <string>();

            model.Page = GetPageOrDefaultValues(model.Page);

            if (updateResult.IsPasswordUpdated)
            {
                comments.Add("Succeeded to update password");
            }
            else
            {
                comments.Add("Password was not updated");
            }

            if (updateResult.AreRolesUpdated)
            {
                comments.Add("Succeeded to update roles");
            }
            else
            {
                comments.Add("Roles were not updated");
            }

            ViewData["Comments"] = comments;

            return(View("Index", await _userServices.GetUsersPage(model.Page.PageNumber, model.Page.PageSize)));
        }
Пример #2
0
        public async void UserServices_User_Roles_Have_Been_Properly_Updated()
        {
            //Arrange
            UserServices userServices      = CreateUserServices();
            string       userId            = "1234";
            UserModel    userModelToUpdate = new UserModel();

            userModelToUpdate.Id    = userId;
            userModelToUpdate.Roles = new List <string>()
            {
                "User"
            };
            userModelToUpdate.NewRoles = new List <string>()
            {
                "Admin", "User"
            };
            UpdateUserResult updateResult = null;
            bool             result       = false;

            //Act

            updateResult = await userServices.Update(userModelToUpdate);

            if (updateResult.AreRolesUpdated == true && updateResult.IsPasswordUpdated == false)
            {
                result = true;
            }

            //Assert
            Assert.True(result);
        }
Пример #3
0
        public ActionResult Update([DataSourceRequest] DataSourceRequest request, UserViewModel model)
        {
            if (this.ModelState.IsValid && model != null)
            {
                UpdateUserResult result = this.UserService.Update(
                    model.Id,
                    model.FirstName,
                    model.LastName,
                    model.UserName,
                    model.Email,
                    int.Parse(model.LocationId));

                if (result.Result.Succeeded)
                {
                    model = this.UserService
                            .GetById(result.User.Id)
                            .To <UserViewModel>()
                            .FirstOrDefault();
                }
                else
                {
                    foreach (var error in result.Result.Errors)
                    {
                        this.ModelState.AddModelError(string.Empty, error);
                    }
                }
            }

            return(this.Json(new[] { model }.ToDataSourceResult(request, this.ModelState)));
        }
Пример #4
0
        public async Task <IHttpActionResult> SavePermissions(string id, [FromBody] Dictionary <string, AccessRight> roles)
        {
            try
            {
                var model = new UpdateUserResult();
                if (ModelState.IsValid)
                {
                    var result = await _authRepository.SaveUserPermissions(id, roles);

                    model.IsSuccess = result.Succeeded;
                    if (!result.Succeeded)
                    {
                        model.Errors.AddRange(result.Errors);
                    }
                    else
                    {
                        await _authRepository.ForceUserToReload(id);
                    }
                }
                else
                {
                    var errors = ModelState.Values.SelectMany(x => x.Errors).Select(e => e.ErrorMessage).ToList();
                    model.Errors.AddRange(errors);
                }
                return(Ok(model));
            }
            catch (Exception ex)
            {
                return(OnError(ex));
            }
        }
Пример #5
0
        public async Task <UpdateUserResult> SaveUser(UpdateUserModel model)
        {
            var result = new UpdateUserResult();

            if (ModelState.IsValid)
            {
                var            isNew = string.IsNullOrWhiteSpace(model.Id);
                IdentityResult saveResult;
                if (!isNew)
                {
                    saveResult = await _authRepository.UpdateUser(model);
                }
                else
                {
                    saveResult = await _authRepository.CreateUser(model);
                }
                result.IsSuccess = saveResult.Succeeded;

                if (!result.IsSuccess)
                {
                    result.Errors.AddRange(saveResult.Errors);
                }
            }
            else
            {
                var errors = ModelState.Values.SelectMany(x => x.Errors).Select(e => e.ErrorMessage).ToList();
                result.Errors.AddRange(errors);
            }
            return(result);
        }
Пример #6
0
        /// <summary>
        /// Updates the user.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="inputModel">The input model.</param>
        /// <returns>
        /// The manager response where the user is returned.
        /// </returns>
        public virtual ManagerResponse <UpdateUserResult, CommerceUser> UpdateUser([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, ProfileModel inputModel)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(visitorContext, "visitorContext");
            Assert.ArgumentNotNull(inputModel, "inputModel");

            UpdateUserResult result;

            var userName     = visitorContext.UserName;
            var commerceUser = this.GetUser(userName).Result;

            if (commerceUser != null)
            {
                commerceUser.FirstName = inputModel.FirstName;
                commerceUser.LastName  = inputModel.LastName;
                commerceUser.Email     = inputModel.Email;
                commerceUser.SetPropertyValue("Phone", inputModel.TelephoneNumber);

                try
                {
                    var request = new UpdateUserRequest(commerceUser);
                    result = this.CustomerServiceProvider.UpdateUser(request);
                }
                catch (Exception ex)
                {
                    result = new UpdateUserResult {
                        Success = false
                    };
                    result.SystemMessages.Add(new Sitecore.Commerce.Services.SystemMessage {
                        Message = ex.Message + "/" + ex.StackTrace
                    });
                }
            }
            else
            {
                // user is authenticated, but not in the CommerceUsers domain - probably here because we are in edit or preview mode
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.UpdateUserProfileError);
                message = string.Format(CultureInfo.InvariantCulture, message, Context.User.LocalName);
                result  = new UpdateUserResult {
                    Success = false
                };

                result.SystemMessages.Add(new Commerce.Services.SystemMessage {
                    Message = message
                });
            }

            if (!result.Success)
            {
                Helpers.LogSystemMessages(result.SystemMessages, result);
            }

            return(new ManagerResponse <UpdateUserResult, CommerceUser>(result, result.CommerceUser));
        }
Пример #7
0
        public virtual void Initialize(UpdateUserResult result)
        {
            if (result.CommerceUser != null)
            {
                this.Email           = result.CommerceUser.Email;
                this.FirstName       = result.CommerceUser.FirstName;
                this.LastName        = result.CommerceUser.LastName;
                this.TelephoneNumber = result.Properties["Phone"] as string;
            }

            this.SetErrors(result);
        }
Пример #8
0
        public void Initialize(UpdateUserResult result)
        {
            if (result.CommerceUser != null)
            {
                Email           = result.CommerceUser.Email;
                FirstName       = result.CommerceUser.FirstName;
                LastName        = result.CommerceUser.LastName;
                TelephoneNumber = result.Properties["Phone"] as string;
            }

            SetErrors(result);
        }
        public ManagerResponse <UpdateUserResult, CommerceUser> UpdateUser(CommerceUser updatedCommerceUser)
        {
            Assert.ArgumentNotNull(updatedCommerceUser, nameof(updatedCommerceUser));

            var updateUserRequest = new UpdateUserRequest(updatedCommerceUser);

            UpdateUserResult updateUserResult = this.customerServiceProvider.UpdateUser(updateUserRequest);

            if (!updateUserResult.Success)
            {
                Log.Warn("User update failed", this.GetType());
            }

            return(new ManagerResponse <UpdateUserResult, CommerceUser>(updateUserResult, updateUserResult.CommerceUser));
        }
Пример #10
0
        public ManagerResponse <UpdateUserResult, CommerceUser> UpdateUser(string userName, ProfileModel inputModel)
        {
            Assert.ArgumentNotNull(inputModel, nameof(inputModel));

            UpdateUserResult result;

            var commerceUser = GetUser(userName).Result;

            if (commerceUser != null)
            {
                commerceUser.FirstName = inputModel.FirstName;
                commerceUser.LastName  = inputModel.LastName;
                commerceUser.Email     = inputModel.Email;
                commerceUser.SetPropertyValue("Phone", inputModel.TelephoneNumber);

                try
                {
                    var request = new UpdateUserRequest(commerceUser);
                    result = CustomerServiceProvider.UpdateUser(request);
                }
                catch (Exception ex)
                {
                    result = new UpdateUserResult {
                        Success = false
                    };
                    result.SystemMessages.Add(new SystemMessage {
                        Message = ex.Message + "/" + ex.StackTrace
                    });
                }
            }
            else
            {
                // user is authenticated, but not in the CommerceUsers domain - probably here because we are in edit or preview mode
                var message = DictionaryPhraseRepository.Current.Get("/System Messages/Account Manager/Update User Profile Error", "Cannot update profile details for user {0}.");
                message = string.Format(message, Context.User.LocalName);
                result  = new UpdateUserResult {
                    Success = false
                };
                result.SystemMessages.Add(new SystemMessage {
                    Message = message
                });
            }

            result.WriteToSitecoreLog();
            return(new ManagerResponse <UpdateUserResult, CommerceUser>(result, result.CommerceUser));
        }
Пример #11
0
        public UpdateUserResult Update(string id, string firstName, string lastName, string userName, string email, int locationId)
        {
            var result = new UpdateUserResult();

            var user = this.GetById(id).FirstOrDefault();

            user.FirstName  = firstName;
            user.LastName   = lastName;
            user.UserName   = userName;
            user.Email      = email;
            user.LocationId = locationId;

            result.Result = this.manager.Update(user);
            result.User   = user;

            return(result);
        }
        public async Task <UpdateUserResult> ChangePassword(User changePasswordUser)
        {
            var userExistanceCheck = await CheckUserExistance(changePasswordUser);

            if (userExistanceCheck.result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return((UpdateUserResult)userExistanceCheck.result);
            }

            var passwordUpdated = await _storageService.ChangePassword(changePasswordUser);

            var updatePasswordResponse = new UpdateUserResult
            {
                StatusCode = passwordUpdated ? System.Net.HttpStatusCode.OK : System.Net.HttpStatusCode.InternalServerError,
                Success    = passwordUpdated ? true : false,
                Messages   = passwordUpdated ? new[] { $"The uesr {changePasswordUser.Email} password is changed successfully" } : new[] { $"The uesr {changePasswordUser.Email} password is not updated, Internel server error." }
            };

            return(updatePasswordResponse);
        }
        public async Task <UpdateUserResult> UpdateUser(User updateUser)
        {
            var userExistanceCheck = await CheckUserExistance(updateUser);

            if (userExistanceCheck.result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return((UpdateUserResult)userExistanceCheck.result);
            }

            var userUpdated = await _storageService.UpdateUser(updateUser);

            var updateUserResponse = new UpdateUserResult
            {
                StatusCode = userUpdated ? System.Net.HttpStatusCode.OK : System.Net.HttpStatusCode.InternalServerError,
                Success    = userUpdated ? true : false,
                Messages   = userUpdated ? new[] { $"The uesr {updateUser.Email} is updated" } : new[] { $"The uesr {updateUser.Email} is not updated, Internel server error." }
            };

            return(updateUserResponse);
        }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ProfileBaseJsonResult"/> class.
 /// </summary>
 /// <param name="result">The result.</param>
 public ProfileBaseJsonResult(UpdateUserResult result)
     : base(result)
 {
 }
Пример #15
0
        /// <summary>
        /// Updates the user.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="inputModel">The input model.</param>
        /// <returns>
        /// The manager response where the user is returned.
        /// </returns>
        public virtual ManagerResponse<UpdateUserResult, CommerceUser> UpdateUser([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, ProfileModel inputModel)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(visitorContext, "visitorContext");
            Assert.ArgumentNotNull(inputModel, "inputModel");

            UpdateUserResult result;

            var userName = visitorContext.UserName;
            var commerceUser = this.GetUser(userName).Result;
            if (commerceUser != null)
            {
                commerceUser.FirstName = inputModel.FirstName;
                commerceUser.LastName = inputModel.LastName;
                commerceUser.Email = inputModel.Email;
                commerceUser.SetPropertyValue("Phone", inputModel.TelephoneNumber);

                try
                {
                    var request = new UpdateUserRequest(commerceUser);
                    result = this.CustomerServiceProvider.UpdateUser(request);
                }
                catch (Exception ex)
                {
                    result = new UpdateUserResult { Success = false };
                    result.SystemMessages.Add(new Sitecore.Commerce.Services.SystemMessage() { Message = ex.Message + "/" + ex.StackTrace });
                }
            }
            else
            {
                // user is authenticated, but not in the CommerceUsers domain - probably here because we are in edit or preview mode
                var message = StorefrontManager.GetSystemMessage("UpdateUserProfileError");
                message = string.Format(CultureInfo.InvariantCulture, message, Context.User.LocalName);
                result = new UpdateUserResult { Success = false };
                result.SystemMessages.Add(new Commerce.Services.SystemMessage { Message = message });
            }

            Helpers.LogSystemMessages(result.SystemMessages, result);
            return new ManagerResponse<UpdateUserResult, CommerceUser>(result, result.CommerceUser);
        }
Пример #16
0
 public ProfileApiModel(UpdateUserResult result)
     : base(result)
 {
 }
Пример #17
0
        public async Task SyncUserAsync(Guid userId, Guid scimAppSettingsId)
        {
            ScimUserSyncState?syncState = await _authDbContext
                                          .ScimUserSyncStates
                                          .SingleOrDefaultAsync(s => s.SCIMAppSettings.Id == scimAppSettingsId && s.User.Id == userId);

            AppUser user = await _authDbContext
                           .Users
                           .SingleAsync(u => u.Id == userId);

            Gatekeeper.SCIM.Client.Schema.Core20.User scimUser = new Gatekeeper.SCIM.Client.Schema.Core20.User
            {
                ExternalId = user.Id.ToString(),
                UserName   = user.UserName,
                Emails     = new List <Gatekeeper.SCIM.Client.Schema.Core20.User.EmailAttribute>()
                {
                    new  Gatekeeper.SCIM.Client.Schema.Core20.User.EmailAttribute
                    {
                        Value   = user.Email,
                        Primary = true
                    },
                },
                DisplayName = user.UserName,
                Active      = true,
            };

            Gatekeeper.SCIM.Client.Client scimClient = await GetScimClient(scimAppSettingsId);

            if (syncState == null)
            {
                CreateAction <Gatekeeper.SCIM.Client.Schema.Core20.User> createUserAction = new CreateAction <Gatekeeper.SCIM.Client.Schema.Core20.User>(scimUser);
                CreateResult <Gatekeeper.SCIM.Client.Schema.Core20.User> createUserResult = await scimClient.PerformAction <CreateResult <Gatekeeper.SCIM.Client.Schema.Core20.User> >(createUserAction);

                if (createUserResult.ResultStatus == StateEnum.Success &&
                    createUserResult.Resource != null &&
                    createUserResult.Resource.Id != null
                    )
                {
                    syncState = new ScimUserSyncState
                    {
                        User = user,
                        SCIMAppSettingsId = scimAppSettingsId,
                        ServiceId         = createUserResult.Resource.Id,
                    };
                    _authDbContext.Add(syncState);
                    await _authDbContext.SaveChangesAsync();
                }
                else
                {
                    throw new Exception("SCIM initial sync failed");
                }
            }
            else
            {
                scimUser.Id = syncState.ServiceId;
                UpdateUserAction updateUserAction = new UpdateUserAction(scimUser);
                UpdateUserResult updateUserResult = await scimClient.PerformAction <UpdateUserResult>(updateUserAction);

                if (updateUserResult.ResultStatus != StateEnum.Success)
                {
                    throw new Exception("SCIM update failed");
                }
            }
        }