Beispiel #1
0
        public async Task <UserVm> UpdateUser(int userId, UpdateUserVm model)
        {
            var updateUserDto = new UpdateUserDto
            {
                FirstName = model.FirstName,
                LastName  = model.LastName,
                Id        = userId
            };
            var file = model.Image;

            if (file != null)
            {
                var extension = "." + file.FileName.Split(".").LastOrDefault();
                if (string.IsNullOrEmpty(extension))
                {
                    extension = string.Empty;
                }
                var imagesDirectory = Path.Combine(_appEnvironment.ContentRootPath, _commonSettings.UserImagesFolder);
                if (!Directory.Exists(imagesDirectory))
                {
                    Directory.CreateDirectory(imagesDirectory);
                }
                updateUserDto.ImageLocalUrl = Path.Combine(imagesDirectory, $"{userId}{extension}");
                await using var fileStream  = new FileStream(updateUserDto.ImageLocalUrl, FileMode.Create);
                await file.CopyToAsync(fileStream);

                updateUserDto.ImageCode         = StringExtensions.GenerateUniqueRandomToken();
                updateUserDto.ImageThumbnailUrl = $"{_commonSettings.ApplicationUrl}/api/user/image/{updateUserDto.ImageCode}";
            }

            await _userRepository.UpdateUser(updateUserDto);

            return(await this.GetUserById(userId));
        }
Beispiel #2
0
        public async Task <IActionResult> Update(Guid userID, UpdateUserDto updateUserInfo)
        {
            var user = new User
            {
                ID = userID
            };

            #region [Authorization]
            var result = await this.AuthorizationService.AuthorizeAsync
                         (
                this.User, user, nameof(KindlyPolicies.AllowIfOwner)
                         );

            if (result.Succeeded == false)
            {
                return(this.Unauthorized());
            }
            #endregion

            this.Mapper.Map(updateUserInfo, user);

            await this.Repository.Update(user);

            return(this.Ok());
        }
        public async Task <int> UpdateAsync(UpdateUserDto updateUserDto)
        {
            const string query = @"
                UPDATE [Users]
                SET 
                    [UserName] = @UserName
                    ,[NormalizedUserName] = @NormalizedUserName
                    ,[Email] = @Email
                    ,[NormalizedEmail] = @NormalizedEmail
                    ,[EmailConfirmed] = @EmailConfirmed
                    ,[PasswordHash] = @PasswordHash
                    ,[SecurityStamp] = @SecurityStamp
                    ,[ConcurrencyStamp] = @ConcurrencyStamp
                    ,[PhoneNumber] = @PhoneNumber
                    ,[PhoneNumberConfirmed] = @PhoneNumberConfirmed
                    ,[TwoFactorEnabled] = @TwoFactorEnabled
                    ,[LockoutEnd] = @LockoutEnd
                    ,[LockoutEnabled] = @LockoutEnabled
                    ,[AccessFailedCount] = @AccessFailedCount
                WHERE [Id] = @Id;
            ";

            using (var connection = _dbConnectionFactory.GetDbConnection())
            {
                var updatedRowsNum = await connection.ExecuteAsync(query, updateUserDto);

                return(updatedRowsNum);
            }
        }
        public async Task <IActionResult> UpdateUserAsync(Guid userId, [FromBody] UpdateUserDto user, [FromHeader(Name = "Accept")] string mediaType)
        {
            if (!MediaTypeHeaderValue.TryParse(mediaType, out MediaTypeHeaderValue parsedMediaType))
            {
                return(BadRequest());
            }

            var userDto = await _userService.UpdateUserAsync(userId, user);

            if (userDto == null)
            {
                return(NotFound());
            }

            var includeLinks = parsedMediaType.SubTypeWithoutSuffix.EndsWith("hateoas", StringComparison.InvariantCultureIgnoreCase);

            if (includeLinks)
            {
                IEnumerable <LinkDto> links = new List <LinkDto>();
                links = CreateUserLinks(userId);
                var userWithLinks = _mapper.Map <ResponseUserLinksDto>(userDto);
                userWithLinks.Links = links;

                return(Ok(userWithLinks));
            }

            return(Ok(userDto));
        }
        public async Task <(bool, string)> UpdateAsync([FromForm] UpdateUserDto updateUserDto)
        {
            logger.LogInformation("Updated Successfulluy", updateUserDto);


            return(await userService.UpdateAsync(updateUserDto));
        }
Beispiel #6
0
        public async Task <IDataResult <User> > Update(UpdateUserDto userDto)
        {
            BusinessRules.Run(CheckUserExists(userDto.Id));
            User userEntity = _userDal.Get(c => c.Id == userDto.Id);

            if (!string.IsNullOrEmpty(userDto.FirstName))
            {
                CheckEmailNotExists(userDto.Email);
                userEntity.Email = userDto.Email;
            }
            if (!string.IsNullOrEmpty(userDto.Password))
            {
                userDto.Password = BCrypt.Net.BCrypt.HashPassword(userDto.Password);
            }
            if (!string.IsNullOrEmpty(userDto.FirstName))
            {
                userEntity.FirstName = userDto.FirstName;
            }
            if (!string.IsNullOrEmpty(userDto.LastName))
            {
                userEntity.LastName = userDto.LastName;
            }
            var user = await _userDal.Update(userEntity);

            return(new SuccessDataResult <User>(user));
        }
Beispiel #7
0
        public async Task <ServiceResponse <GetUserDto> > UpdateUser(int id, UpdateUserDto updateUserDto)
        {
            ServiceResponse <GetUserDto> response = new ServiceResponse <GetUserDto> ();

            try {
                User user = await _context.Users.FirstOrDefaultAsync(u => u.Id == id);

                if (user == null)
                {
                    response.Success = false;
                    response.Message = $"User with id {id} not found!";
                    return(response);
                }
                var updateUser = _mapper.Map <User> (updateUserDto);
                _context.Entry(updateUser).State = EntityState.Modified;
                await _context.SaveChangesAsync();

                response.Data = _mapper.Map <GetUserDto> (updateUser);
                return(response);
            } catch (System.Exception ex) {
                response.Success = false;
                response.Message = ex.Message;
            }
            return(response);
        }
        public void Execute(int id, UpdateUserDto dto)
        {
            dto.Id = id;

            var user = _context.Users.Find(id);

            if (user == null)
            {
                throw new EntityNotFoundException(id, typeof(User));
            }

            _validator.ValidateAndThrow(dto);

            /*_mapper.Map(dto, user);*/

            user.FirstName    = dto.FirstName;
            user.LastName     = dto.LastName;
            user.Password     = dto.Password;
            user.Email        = dto.Email;
            user.UserUseCases = dto.UserUseCases.Select(u => new UserUseCase
            {
                UseCaseId = u.UseCaseId
            }).ToList();

            _context.SaveChanges();
        }
Beispiel #9
0
        public async Task <ActionResult <GetUserDto> > UpdateAsync(
            [FromBody][Required] UpdateUserDto updateUserDto,
            CancellationToken cancellationToken)
        {
            var currentUser = await _userManager.GetUserAsync(HttpContext.User)
                              .ConfigureAwait(false);

            if (currentUser is null)
            {
                return(NotFound());
            }

            if (updateUserDto.PasswordChange.OldPassword != string.Empty)
            {
                var result = await _userManager.ChangePasswordAsync(
                    currentUser,
                    updateUserDto.PasswordChange.OldPassword,
                    updateUserDto.PasswordChange.NewPassword)
                             .ConfigureAwait(false);

                if (!result.Succeeded)
                {
                    return(BadRequest("Old password is incorrect."));
                }
            }

            var updatedUser = await _user.DoUpdateAsync(currentUser, updateUserDto, cancellationToken)
                              .ConfigureAwait(false);

            var userDto = CreateUserDto(updatedUser !);

            return(Ok(userDto));
        }
Beispiel #10
0
        public async Task <ServiceResponse <GetUserDto> > UpdateUser(UpdateUserDto updateCharacter)
        {
            ServiceResponse <GetUserDto> serviceResponse = new ServiceResponse <GetUserDto>();

            try
            {
                User user = _context.Users.FirstOrDefault(u => u.Id == updateCharacter.Id);
                user.Username     = updateCharacter.Username;
                user.EmailAddress = updateCharacter.EmailAddress;
                user.Role         = updateCharacter.Role;
                if (user.Password != updateCharacter.Password)
                {
                    user.Password              = updateCharacter.Password;
                    user.Salt                  = updateCharacter.Salt;
                    user.LastPasswordChange    = updateCharacter.LastPasswordChange;
                    user.EnforcePasswordChange = false;
                }
                serviceResponse.Data = _mapper.Map <GetUserDto>(user);
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                serviceResponse.Success = false;
                serviceResponse.Message = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
            }
            return(serviceResponse);
        }
Beispiel #11
0
        public async Task <IActionResult> UpdateUserShift([FromBody] UpdateUserDto updatedUser)
        {
            var newUser = new User
            {
                UserId       = updatedUser.UserId,
                AccountId    = updatedUser.AccountId,
                FirstName    = updatedUser.FirstName,
                LastName     = updatedUser.LastName,
                Gender       = updatedUser.Gender,
                DepartmentId = updatedUser.DepartmentId,
                PositionId   = updatedUser.PositionId
            };
            await _userShiftRepo.DeleteAsync(d => d.UserId == updatedUser.UserId);

            await _userRepo.UpdateAsync(newUser);

            if (updatedUser.UserShifts.Count > 0)
            {
                foreach (var userShift in updatedUser.UserShifts)
                {
                    var newUserShift = new UserShift
                    {
                        ShiftId = userShift.ShiftId,
                        UserId  = userShift.UserId,
                        Day     = userShift.Day
                    };
                    await _userShiftRepo.CreateAsync(newUserShift);
                }
            }
            return(Ok(await GetUserList()));
        }
Beispiel #12
0
        public async Task <bool> Update(UpdateUserDto entity)
        {
            var item = await _context.Users.FindAsync(entity.ID);

            item.EmployeeID = entity.EmployeeID;
            item.Username   = entity.Username;
            item.Email      = entity.Email;
            item.ModifyTime = DateTime.Now;
            if (!entity.Password.IsNullOrEmpty())
            {
                byte[] passwordHash, passwordSalt;
                CreatePasswordHash(entity.Password, out passwordHash, out passwordSalt);
                item.PasswordHash = passwordHash;
                item.PasswordSalt = passwordSalt;
            }

            item.ModifyTime = DateTime.Now;

            try
            {
                _context.Users.Update(item);
                await _context.SaveChangesAsync();

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public async Task <IActionResult> Update(UpdateUserDto dto)
        {
            try
            {
                await _service.UpdateAsync(dto);

                Logger.LogDebug("Successfully updated user with id '{0}'.", dto.Id);

                return(Ok());
            }
            catch (NotFoundException e)
            {
                Logger.LogDebug("Could not update user as no user could be found with id '{0}'.", dto.Id);

                return(NotFound(e.Message));
            }
            catch (ValidationException e)
            {
                Logger.LogDebug("A validation occured while updating the user: {0}", e.Message);

                return(BadRequest(e.Message));
            }
            catch (Exception e)
            {
                Logger.LogError(e, "An error occured while updating the user.");

                return(InternalServerError(e.Message));
            }
        }
Beispiel #14
0
        public void Update_existing_user()
        {
            NewUserDto newUserDto = new NewUserDto
            {
                Name     = "Martin",
                Surname  = "Fowler",
                Username = "******",
                Password = "******",
                Email    = "*****@*****.**",
                IsRoot   = false
            };

            UpdateUserDto updatedUserDto = new UpdateUserDto
            {
                Name     = "John",
                Surname  = "Smith",
                Username = "******",
                Password = "******",
                Email    = "*****@*****.**",
                IsRoot   = true
            };
            NewUserIdDto newUserIdDto = _managementController.CreateUser(newUserDto);

            _managementController.UpdateUser(newUserIdDto.Id, updatedUserDto);

            UserInfoDto userInfoDto = _managementController.GetUser(newUserIdDto.Id);

            Assert.AreEqual(updatedUserDto.Name, userInfoDto.Name);
            Assert.AreEqual(updatedUserDto.Surname, userInfoDto.Surname);
            Assert.AreEqual(updatedUserDto.Email, userInfoDto.Email);
            Assert.AreEqual(updatedUserDto.Username, userInfoDto.Username);
            Assert.AreEqual(updatedUserDto.IsRoot, userInfoDto.IsRoot);
        }
 public IActionResult UpdateProfile(UpdateUserDto dto)
 {
     if (!ModelState.IsValid)
     {
         TempData["error"] = "Check your input.";
         return(RedirectToAction("MyProfile", new { dto.Id }));
     }
     try
     {
         updateUser.Execute(dto);
         TempData["success"] = "You successfully updated your profile.";
     }
     catch (EntityCannotBeNullException e)
     {
         TempData["error"] = e.Message;
     }
     catch (EntityAlreadyExistsException e)
     {
         TempData["error"] = e.Message;
     }
     catch (EntityMustHaveConfirmedPassword e)
     {
         TempData["error"] = e.Message;
     }
     catch (Exception e)
     {
         TempData["error"] = e.Message;
     }
     return(RedirectToAction("MyProfile", "Account", new { dto.Id }));
 }
Beispiel #16
0
        public async Task <IActionResult> UpdateUserAsync(UpdateUserDto inputModel)
        {
            var user = await userManager.GetUserAsync(User);

            if (!ModelState.IsValid ||
                !await userManager.CheckPasswordAsync(user, inputModel.CurrentPassword) ||
                inputModel.Password != inputModel.ConfirmPassword)
            {
                return(StatusCode(StatusCodes.Status406NotAcceptable));
            }

            var userWithSameUsername = await userManager.FindByNameAsync(inputModel.Username);

            var userWithSameEmail = await userManager.FindByEmailAsync(inputModel.Email);

            if ((userWithSameUsername != null && userWithSameUsername.Id != user.Id) ||
                (userWithSameEmail != null && userWithSameEmail.Id != user.Id))
            {
                return(StatusCode(StatusCodes.Status409Conflict));
            }

            await userManager.SetUserNameAsync(user, inputModel.Username);

            user.Email = inputModel.Email;
            await userManager.UpdateAsync(user);

            if (inputModel.Password.Length >= 6)
            {
                await userManager.RemovePasswordAsync(user);

                await userManager.AddPasswordAsync(user, inputModel.Password);
            }

            return(StatusCode(StatusCodes.Status201Created));
        }
        public async Task <IActionResult> UpdateUser(UpdateUserDto user)
        {
            var result = await accountService.UpdateUser(AuthenticatedUserEmail, user);

            switch (result)
            {
            case UserModificationResult.NothingToUpdate:
            case UserModificationResult.SuccessNoConfirmationRequired:
                return(Ok(new UpdateUserResultDto {
                    IsConfirmationRequired = false
                }));

            case UserModificationResult.SuccessConfirmationRequired:
                return(Ok(new UpdateUserResultDto {
                    IsConfirmationRequired = true
                }));

            case UserModificationResult.DuplicateValues:
                return(BadRequest <UpdateUserDto>(u => u.Email, LocalizedResources.UserDuplicateValuesError));

            case UserModificationResult.IncorrectPassword:
                return(BadRequest <UpdateUserDto>(u => u.OldPassword, LocalizedResources.UserIncorrectPasswordError));

            default:
                throw new InvalidOperationException(nameof(UserModificationResult));
            }
        }
Beispiel #18
0
        public async Task <IActionResult> Profil(UpdateUserDto model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(User.Identity.Name);

                user.Ad       = model.Ad;
                user.Soyad    = model.Soyad;
                user.FirmaAdi = model.FirmaAdi;

                var result = await _userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    await _userManager.UpdateSecurityStampAsync(user);

                    await _signInManager.SignOutAsync();

                    await _signInManager.SignInAsync(user, true);

                    ViewBag.success = "true";
                }
                else
                {
                    foreach (var item in result.Errors)
                    {
                        ModelState.AddModelError("", item.Description);
                    }
                }
            }
            return(View(model));
        }
        public async Task UpdateUser(UpdateUserDto input)
        {
            var user = await _userRepository.GetByIdAsync(input.Id);

            if (input.Username != null)
            {
                user.Username = input.Username;
            }
            if (input.EmailAddress != null)
            {
                user.EmailAddress = input.EmailAddress;
            }
            if (input.Bio != null)
            {
                user.Bio = input.Bio;
            }
            if (input.Username != null)
            {
                user.Username = input.Username;
            }
            user.Gender = input.Gender;

            if (input.ProfileImage != null)
            {
                var imgPath = await _blobService.InsertFile(input.ProfileImage);

                user.ProfileImagePath = imgPath;
            }
            await _userRepository.UpdateAsync(user);
        }
        public async Task <IActionResult> Update(long id, [FromBody] UpdateUserDto model)
        {
            if (!User.GetSubjectId().Equals(id.ToString(), StringComparison.InvariantCultureIgnoreCase))
            {
                return(Forbid());
            }

            if (model == null)
            {
                return(BadRequest());
            }
            try
            {
                var result = await _accountService.UpdateUserAsync(User, model.MapToUserUpdateModel());

                if (result.Succeeded)
                {
                    return(NoContent());
                }
                return(BadRequest(result.Errors));
            }
            catch (UserNotFoundException)
            {
                return(Forbid());
            }
        }
Beispiel #21
0
        public void Update_StateUnderTest_ExpectedBehavior()
        {
            var service = this.CreateService();

            service.ObjectMapper = LocalIocManager.Resolve <Abp.ObjectMapping.IObjectMapper>();
            service.AbpSession   = Resolve <IAbpSession>();
            LoginAsTenant("Default", "85261586394");
            service.UnitOfWorkManager = Resolve <IUnitOfWorkManager>();
            service.UnitOfWorkManager.Begin();

            // Arrange
            UpdateUserDto input1 = new UpdateUserDto
            {
                Id             = 3,
                UserName       = "******",
                FirstName_ChT  = "abc",
                FirstName_Eng  = "abcd",
                FullName       = "abcdef",
                HKID           = "A1234567",
                Surname        = "testing",
                Name           = "testing",
                LangPreference = "zht",
                LastName_ChT   = "abcd",
                LastName_Eng   = "abcde",
            };


            // Act
            var result1 = service.Update(
                input1);

            // Assert
            Assert.True(result1.Status == TaskStatus.RanToCompletion && result1.Result != null);  //exception SetNormalizedNname null object
        }
Beispiel #22
0
        public IActionResult Update([FromBody] UpdateUserDto userDto)
        {
            if (_httpContextAccessor.GetCurrentUserId() != userDto.AuthorId)
            {
                return(Unauthorized(new ErrorResponseDto
                {
                    InternalErrorMessage = "Specified userId does not match the authenticated userId.",
                    DisplayErrorMessage = "You are not authorized to update user profile.",
                }));
            }

            var author = _authorService.UpdateProfile(userDto.AuthorId, userDto.Username, userDto.Email, userDto.FirstName, userDto.MiddleName, userDto.LastName);

            if (author == null)
            {
                var errorMessage = "Failed to update user.";
                return(BadRequest(new ErrorResponseDto
                {
                    InternalErrorMessage = errorMessage,
                    DisplayErrorMessage = errorMessage,
                }));
            }

            return(Ok(_mapper.Map <UpdateUserResponseDto>(author)));
        }
Beispiel #23
0
        public IActionResult Patch(string id, [FromBody] UpdateUserDto model)
        {
            if (model == null)
            {
                return(BadRequest("No data"));
            }
            if (string.IsNullOrEmpty(model.FirstName))
            {
                return(BadRequest("No first name"));
            }
            if (string.IsNullOrEmpty(model.LastName))
            {
                return(BadRequest("No last name"));
            }
            if (string.IsNullOrEmpty(model.UserName))
            {
                return(BadRequest("No user name"));
            }

            var user = new Users
            {
                FirstName = _encryptor.Encrypt(model.FirstName),
                LastName  = _encryptor.Encrypt(model.LastName),
                Role      = model.Role,
                UserName  = model.UserName,
            };

            var entity = _crud.UpdateItem(id, user);

            entity.Password  = null;
            entity.FirstName = _encryptor.Decrypt(entity.FirstName);
            entity.LastName  = _encryptor.Decrypt(entity.LastName);
            return(Ok(new { user = entity }));
        }
        public async Task <IActionResult> UpdateUser([FromBody] UpdateUserDto updateUser, [FromRoute] Guid id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var userId = User.Claims.FirstOrDefault(p => p.Type == ClaimTypes.NameIdentifier)?.Value;

            if (id.ToString() != userId)
            {
                return(BadRequest());
            }
            var isUser = _userManager.Users.Any(u => u.Id == id.ToString());

            if (!isUser)
            {
                return(NotFound());
            }
            var updatedUser = await _userService.UpdateUserAsync(id, updateUser).ConfigureAwait(false);

            var saved = await _userService.SaveAsync().ConfigureAwait(false);

            if (!saved)
            {
                return(BadRequest());
            }
            var profileUser = new ProfileDto(updatedUser);

            return(Ok(profileUser));
        }
Beispiel #25
0
        /// <summary>
        /// 修改指定字段,邮件和组别
        /// </summary>
        /// <param name="id"></param>
        /// <param name="updateUserDto"></param>
        /// <returns></returns>
        public void UpdateUserInfo(int id, UpdateUserDto updateUserDto)
        {
            //此方法适用于更新字段少时
            //_freeSql.Update<LinUser>(id).Set(a => new LinUser()
            //{
            //    Email = updateUserDto.Email,
            //    GroupId = updateUserDto.GroupId
            //}).ExecuteAffrows();

            //需要多查一次
            LinUser linUser = _userRepository.Where(r => r.Id == id).ToOne();

            if (linUser == null)
            {
                throw new LinCmsException("用户不存在", ErrorCode.NotFound);
            }
            //赋值过程可使用AutoMapper简化
            //只更新 Email、GroupId
            // UPDATE `lin_user` SET `email` = ?p_0, `group_id` = ?p_1
            // WHERE(`id` = 1) AND(`is_deleted` = 0)
            //linUser.Email = updateUserDto.Email;
            //linUser.GroupId = updateUserDto.GroupId;

            _mapper.Map(updateUserDto, linUser);

            _userRepository.Update(linUser);
        }
        public IActionResult UpdateUser(long id, [FromBody] UpdateUserDto body)
        {
            // validate
            var ok = body.Validate();

            if (ok != null)
            {
                return(BadRequest(ok));
            }

            // Authorize user
            long tokenId = int.Parse(User.Claims.First(x => x.Type == "uid").Value);

            if (id != tokenId)
            {
                return new ObjectResult(new ForbiddenDto())
                       {
                           StatusCode = 403
                       }
            }
            ;

            // Update user
            var user = body.ToDomain();

            user.Id = id;
            _service.UpdateUser(user);

            return(Ok(new EmptyOkDto()));
        }
    }
        public void Execute(UpdateUserDto request)
        {
            var user = context.Users.Include(u => u.UserUseCases).Where(x => x.Id == request.Id).First();

            if (user == null)
            {
                throw new EntityNotFoundException(request.Id, typeof(User));
            }

            foreach (var idUse in request.RemoveUserUseCases)
            {
                var usecase = context.UserUseCases.Where(u => u.UserId == request.Id && u.UseCaseId == idUse).First();
                context.UserUseCases.Remove(usecase);
            }

            foreach (var idUse in request.UserUseCases)
            {
                context.UserUseCases.Add(new UserUseCase
                {
                    UserId = request.Id, UseCaseId = idUse
                });
            }

            context.SaveChanges();
        }
        public async Task <IActionResult> UpdateProfile(int id, UpdateUserDto userDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var profile = await _context.Users.Include(x => x.Role).Include(x => x.DoctorAppointments).FirstOrDefaultAsync(x => x.Id == id);

            if (profile == null)
            {
                return(NotFound());
            }
            var authorizationResult = _authorizationService.AuthorizeAsync(User, profile, new ProfileRequirement()).Result;

            if (!authorizationResult.Succeeded)
            {
                return(Forbid());
            }
            profile.Address     = userDto.Address;
            profile.DateOfBirth = userDto.DateOfBirth;
            profile.Name        = userDto.Name;

            await _context.SaveChangesAsync();

            return(Ok());
        }
        public async Task <IActionResult> UpdateUser(int userId, UpdateUserDto updatedUser)
        {
            try
            {
                _logger.LogRequest("Updating user {userId}. Request body: {@updatedUser}", userId, updatedUser);

                var currentUserId = User.GetUserId();
                if (currentUserId != userId && !User.IsInRole(UserRole.Administrator))
                {
                    _logger.LogWarning("User {currentUserId} is not authorized to access the endpoint", currentUserId);
                    return(Unauthorized());
                }

                if (userId != updatedUser.Id)
                {
                    _logger.LogWarning("User Id doesn't match.");
                    return(BadRequest("User Id doesn't match."));
                }

                var user = _mapper.Map <User>(updatedUser);

                await _userService.UpdateUser(user);

                _logger.LogResponse("User {userId} updated", userId);

                return(Ok());
            }
            catch (DuplicateUserNameException ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Beispiel #30
0
        public void Execute(UpdateUserDto request)
        {
            var user = Context.Users.Find(request.Id);

            if (user == null || user.IsDeleted == true)
            {
                throw new EntityNotFoundException("User");
            }

            if (request.FirstName == null || request.LastName == null || request.RoleId == 0 || request.Email == null)
            {
                throw new EntityCannotBeNullException("Fields");
            }

            if (request.Email.ToLower() != user.Email.ToLower() && Context.Users.Any(u => u.Email.ToLower() == request.Email.ToLower()))
            {
                throw new EntityAlreadyExistsException("Email");
            }

            if (request.RoleId == 2)
            {
                user.FirstName = request.FirstName;
                user.LastName  = request.LastName;
                user.RoleId    = request.RoleId;
                user.Email     = request.Email;
            }
            else
            {
                user.FirstName = request.FirstName;
                user.LastName  = request.LastName;
                user.Email     = request.Email;
            }

            Context.SaveChanges();
        }