Example #1
0
        public async Task <IActionResult> ResetPassword([FromQuery] string tokenValue, [FromBody] string newPassword)
        {
            try
            {
                var token = await tokenService.GetPasswordResetTokenAsync(tokenValue);

                var userToUpdate = await userService.GetByIdAsync(token.userId);

                var userPatchInfo = new UserPatchInfo
                {
                    EmailAdress = userToUpdate.EmailAdress,
                    FirstName   = userToUpdate.FirstName == null ? "none" : userToUpdate.FirstName,
                    Id          = userToUpdate.Id,
                    LastName    = userToUpdate.LastName == null ? "none" : userToUpdate.LastName,
                    Login       = userToUpdate.Login,
                    Password    = newPassword
                };
                await userService.UpdateAsync(userPatchInfo, newPassword);

                await new MailingService().SendEmailAsync(userToUpdate.EmailAdress,
                                                          "Изменение пароля",
                                                          "Пароль для сайта https://pr42.ru был успешно изменён! Логин : " + userToUpdate.Login);

                return(Ok());
            }
            catch (AppException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
        /// <summary>
        /// Изменить пользователя
        /// </summary>
        /// <param name="patchInfo">Описание изменений пользователя</param>
        /// <returns>Измененный пользователь</returns>
        public User Patch(UserPatchInfo patchInfo)
        {
            if (patchInfo == null)
            {
                throw new ArgumentNullException(nameof(patchInfo));
            }

            if (!this.primaryKeyIndex.TryGetValue(patchInfo.UserId, out var user))
            {
                throw new UserNotFoundException(patchInfo.UserId);
            }

            if (patchInfo.Login != null)
            {
                user.Login = patchInfo.Login;
            }

            if (patchInfo.Password != null)
            {
                user.PasswordHash = Helper.Hash(patchInfo.Password);
            }

            if (patchInfo.Role != null)
            {
                user.Role = patchInfo.Role;
            }

            return(user);
        }
Example #3
0
 private void UpdateUserInfo(UserPatchInfo userToUpdate, User userFromRepository)
 {
     userFromRepository.FirstName   = userToUpdate.FirstName;
     userFromRepository.LastName    = userToUpdate.LastName;
     userFromRepository.Login       = userToUpdate.Login;
     userFromRepository.EmailAdress = userToUpdate.EmailAdress;
 }
Example #4
0
        public async void Update(UserPatchInfo userToUpdate, string password = null)
        {
            ValidateUser(userToUpdate);
            var userFromRepository = await repository.GetUserAsync(userToUpdate.Id);

            if (userFromRepository == null)
            {
                throw new AppException("User not found");
            }

            CheckInfoNotExist(userToUpdate, userFromRepository);

            UpdateUserInfo(userToUpdate, userFromRepository);

            if (!string.IsNullOrWhiteSpace(password))
            {
                byte[] passwordHash, passwordSalt;
                CreatePasswordHash(password, out passwordHash, out passwordSalt);

                userFromRepository.PasswordHash = passwordHash;
                userFromRepository.PasswordSalt = passwordSalt;
            }

            await repository.UpdateAsync(userFromRepository);
        }
Example #5
0
        private bool FieldsAreFilled(UserPatchInfo userToCheck)
        {
            var type = userToCheck.GetType();

            foreach (var property in type.GetProperties())
            {
                if (property.GetValue(userToCheck) == null)
                {
                    return(false);
                }
            }

            return(true);
        }
Example #6
0
        private async void CheckInfoNotExist(UserPatchInfo newInfo, User repositoryInfo)
        {
            if (newInfo.Login != repositoryInfo.Login)
            {
                if (await repository.FindLoginAsync(newInfo.Login))
                {
                    throw new AppException("Username " + newInfo.Login + " is already taken");
                }
            }

            if (newInfo.EmailAdress != repositoryInfo.EmailAdress)
            {
                if (await repository.FindMailAsync(newInfo.EmailAdress))
                {
                    throw new AppException("Email adress " + newInfo.EmailAdress + " is already taken");
                }
            }
        }
Example #7
0
        private async void CheckInfoNotExist(UserPatchInfo newInfo, User repositoryInfo)
        {
            if (newInfo.Login != repositoryInfo.Login)
            {
                if (await repository.FindLoginAsync(newInfo.Login))
                {
                    throw new AppException("Пользователь " + newInfo.Login + " уже занят");
                }
            }

            if (newInfo.EmailAdress != repositoryInfo.EmailAdress)
            {
                if (await repository.FindMailAsync(newInfo.EmailAdress))
                {
                    throw new AppException("Почтовый адрес " + newInfo.EmailAdress + " уже занят");
                }
            }
        }
Example #8
0
        public Task <User> PatchAsync(UserPatchInfo patchInfo, string userId, CancellationToken cancellationToken)
        {
            if (patchInfo == null)
            {
                throw new ArgumentNullException(nameof(patchInfo));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var user = users.Find(item => item.Id == userId).FirstOrDefault();

            if (user is null)
            {
                throw new UserNotFoundException(userId);
            }

            if (patchInfo.Email != null)
            {
                user.Email = patchInfo.Email;
            }

            if (patchInfo.Phone != null)
            {
                user.Phone = patchInfo.Phone;
            }

            if (patchInfo.FirstName != null)
            {
                user.FirstName = patchInfo.FirstName;
            }

            if (patchInfo.LastName != null)
            {
                user.LastName = patchInfo.LastName;
            }
            users.ReplaceOne(usr => usr.Id == user.Id, user);

            return(Task.FromResult(user));
        }
        public IHttpActionResult Patch(string userId, [FromBody] UserPatchInfo patchInfo)
        {
            if (!ModelState.IsValid)
            {
                return(this.BadRequest(ModelState));
            }
            if (patchInfo == null)
            {
                return(this.BadRequest("Body must be not null"));
            }

            if (!Guid.TryParse(userId, out var userIdGuid))
            {
                return(BadRequest());
            }

            string sessionId = patchInfo.SessionId;

            if (!authenticator.TryGetSession(sessionId, out var sessionState))
            {
                return(Unauthorized());
            }

            var userPatchInfo = UserPatchInfoConverter.Convert(userIdGuid, patchInfo);

            Model.User modelUser = null;

            try
            {
                modelUser = userRepository.Patch(userPatchInfo);
            }
            catch (Model.UserNotFoundException)
            {
                return(NotFound());
            }

            return(Ok(UserConverter.Convert(modelUser)));
        }
Example #10
0
        public User Patch(UserPatchInfo patchInfo)
        {
            if (patchInfo == null)
            {
                throw new ArgumentNullException(nameof(patchInfo));
            }
            var user = Get(patchInfo.UserId);

            if (patchInfo.Login != null)
            {
                user.Login = patchInfo.Login;
            }
            if (patchInfo.Password != null)
            {
                user.PasswordHash = Helper.Hash(patchInfo.Password);
            }
            if (patchInfo.Role != null)
            {
                user.Role = patchInfo.Role;
            }
            users.ReplaceOne(x => x.Id == user.Id, user);
            return(user);
        }
Example #11
0
 private void ValidateUser(UserPatchInfo userToValidate)
 {
     if (!FieldsAreFilled(userToValidate))
     {
         throw new AppException("Not enough information");
     }
     if (!LengthIsCorrect(userToValidate.Login, MinimumLoginLength, MaximumLoginLength))
     {
         throw new AppException("Username length \"" + userToValidate.Login + "\" is incorrect");
     }
     if (!LengthIsCorrect(userToValidate.Password, MinimumPassLength, MaximumPassLength))
     {
         throw new AppException("Password length \"" + userToValidate.Password + "\" is incorrect");
     }
     if (!LengthIsCorrect(userToValidate.FirstName, 0, 20)) // todo
     {
         throw new AppException("Username length \"" + userToValidate.FirstName + "\" is incorrect");
     }
     if (!LengthIsCorrect(userToValidate.LastName, 0, 20)) // todo
     {
         throw new AppException("Username length \"" + userToValidate.LastName + "\" is incorrect");
     }
 }
Example #12
0
 private void ValidateUser(UserPatchInfo userToValidate)
 {
     if (!FieldsAreFilled(userToValidate))
     {
         throw new AppException("Недостаточно информации про пользователя");
     }
     if (!LengthIsCorrect(userToValidate.Login, MinimumLoginLength, MaximumLoginLength))
     {
         throw new AppException($"Длина логина не правильная, должна быть от {MinimumLoginLength}" +
                                $" и до {MaximumLoginLength}");
     }
     if (!LengthIsCorrect(userToValidate.Password, MinimumPassLength, MaximumPassLength))
     {
         throw new AppException($"Длина пароля не правильная, должна быть от {MinimumPassLength}" +
                                $" и до {MaximumPassLength}");
     }
     if (!LengthIsCorrect(userToValidate.EmailAdress, MinimumEmailLength, MaximumEmailLength))
     {
         throw new AppException($"Длина почты не правильная, должна быть от {MinimumEmailLength}" +
                                $" и до {MaximumEmailLength}");
     }
     if (!IsEmailValid(userToValidate.EmailAdress))
     {
         throw new AppException($"Почтовый адрес указан в неправильном формате");
     }
     if (!LengthIsCorrect(userToValidate.FirstName, MinimumFirstNameLength, MaximumFirstNameLength))
     {
         throw new AppException($"Длина имени не правильная, должна быть от {MinimumFirstNameLength}" +
                                $" и до {MaximumFirstNameLength}");
     }
     if (!LengthIsCorrect(userToValidate.LastName, MinimumLastNameLength, MaximumLastNameLength))
     {
         throw new AppException($"Длина имени не правильная, должна быть от {MinimumLastNameLength}" +
                                $" и до {MaximumLastNameLength}");
     }
 }
 public IHttpActionResult Patch(string id, [FromBody] UserPatchInfo value)
 {
     return(this.BadRequest());
 }