Esempio n. 1
0
        public async Task <IActionResult> UpdateUser([ModelBinder(typeof(JsonModelBinder <UserDto>))] Delta <UserDto> userDelta)
        {
            if (!ModelState.IsValid)
            {
                return(await Error());
            }

            var currentUser = _userApiService.GetUserEntityById(userDelta.Dto.Id);

            if (currentUser == null)
            {
                return(await Error(HttpStatusCode.NotFound, "user", "not found"));
            }

            userDelta.Merge(currentUser);

            //password
            if (!string.IsNullOrWhiteSpace(userDelta.Dto.Password))
            {
                await AddPassword(userDelta.Dto.Password, currentUser);
            }

            //roles
            if (userDelta.Dto.RoleIds.Count > 0)
            {
                AddValidRoles(userDelta, currentUser);
            }

            //stores
            if (userDelta.Dto.StoreIds.Count > 0)
            {
                await AddValidStores(userDelta, currentUser);
            }

            await UserService.UpdateUserAsync(currentUser);

            await InsertFirstAndLastNameGenericAttributes(userDelta.Dto.FirstName, userDelta.Dto.LastName, currentUser);

            // Preparing the result dto of the new user
            var updatedUser = currentUser.ToDto();

            var firstNameGenericAttribute =
                (await _genericAttributeService.GetAttributesForEntityAsync(currentUser.Id, typeof(User).Name))
                .FirstOrDefault(x => x.Key == "FirstName");

            if (firstNameGenericAttribute != null)
            {
                updatedUser.FirstName = firstNameGenericAttribute.Value;
            }

            var lastNameGenericAttribute =
                (await _genericAttributeService.GetAttributesForEntityAsync(currentUser.Id, typeof(User).Name))
                .FirstOrDefault(x => x.Key == "LastName");

            if (lastNameGenericAttribute != null)
            {
                updatedUser.LastName = lastNameGenericAttribute.Value;
            }

            updatedUser.UserPassword = _userApiService.GetUserPassword(updatedUser.Id);

            //activity log
            await UserActivityService.InsertActivityAsync("EditUser", $"Edited a user (ID = {currentUser.Id})", currentUser);

            var usersRootObject = new UsersRootObject();

            usersRootObject.Users.Add(updatedUser);

            var json = JsonFieldsSerializer.Serialize(usersRootObject, String.Empty);

            return(new RawJsonActionResult(json));
        }