コード例 #1
0
        public ServiceResult <bool> Create(TServiceUser user, string password)
        {
            ThrowIfDisposed();

            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException("password");
            }

            var errors = new List <string>();

            var userValidationResult = _userValidator.Validate(user);

            if (!userValidationResult.Valid)
            {
                errors.AddRange(userValidationResult.Errors);
            }

            var passwordValidation = _passwordValidator.Validate(password);

            if (!passwordValidation.Valid)
            {
                errors.AddRange(passwordValidation.Errors);
            }

            if (!string.IsNullOrWhiteSpace(user.Email) && _userRepository.Exists(u => u.Email.Trim().Equals(user.Email.Trim())))
            {
                errors.Add("Email address is already in use");
            }

            if (!string.IsNullOrWhiteSpace(user.UserName) && _userRepository.Exists(u => u.UserName.Trim().Equals(user.UserName.Trim())))
            {
                errors.Add("Username is already in use");
            }

            if (errors.Any())
            {
                return(ServiceResult <bool> .Error(errors.ToArray()));
            }

            var  repoUser = AutoMapper.Mapper.Map <TServiceUser, TRepositoryUser>(user);
            TKey id       = _userRepository.Create(repoUser);

            repoUser.Id = id;

            UpdatePasswordInternal(repoUser, password);
            return(new ServiceResult <bool> {
                Value = true, Succeeded = true
            });
        }
コード例 #2
0
        public void Test_ValidateWhiteSpace_Not_In_RuleSet()
        {
            var testPassword = new Password
            {
                UserId          = "ABHW089",
                OldPassword     = "******",
                NewPassword     = "******",
                ConfirmPassword = "******",
                NewPasswordHash = "yVHn6 R@",

                IsValid = false
            };

            testPassword.SetHistory(new List <string> {
                "$sG96r#X", "3g9m&9W7"
            });

            validator = new ValidateWhiteSpace();
            validator.Setup(validTestRules);

            var result = validator.Validate(testPassword);

            result.Should().NotBe(null);
            result.IsValid.Should().BeFalse();
            result.Reason.Should().BeNullOrEmpty();
        }
コード例 #3
0
        /// <summary>
        /// 验证用户名与密码,并生成在线票据令牌
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //调用登录服务验证用户名与密码
            bool validated = await _passwordValidator.Validate(context.UserName, context.Password);

            if (!validated)
            {
                context.SetError("invalid_user", "username or password is not valid.");
                return;
            }
            //生成令牌
            ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            List <string> scopes = context.Scope.Where(m => !m.IsMissing()).ToList();

            if (scopes.Any())
            {
                identity.AddClaims(scopes.Select(m => new Claim("urn:oauth:scope", m)));
            }

            AuthenticationProperties properties = new AuthenticationProperties(
                new Dictionary <string, string>()
            {
                { "as:client_id", context.ClientId }
            });
            AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);

            context.Validated(ticket);
        }
コード例 #4
0
        public TUser CreateUserAndActivationRequest(TCreateUserForm form, Uri activateUserUrl)
        {
            var login = form.Login.Trim();

            if (!EmailValidator.Validate(login))
            {
                throw new IncorrectEmailException();
            }

            var password = form.Password;

            if (!passwordValidator.Validate(password))
            {
                throw new WeakPasswordException();
            }

            var existingUser = userStorage.FindUserByLogin(login);

            if (existingUser != null)
            {
                throw new LoginAlreadyExistsException(login);
            }

            var userId = Guid.NewGuid();
            var user   = userProcessor.MakeUser(form, userId);

            SetUserPassword(user, password);
            userStorage.CreateUser(user);
            SendUserActivationRequest(user, activateUserUrl);
            return(userStorage.FindUser(userId));
        }
コード例 #5
0
        public void Test_ValidateHistory_Fail_On_OldPassword()
        {
            var testPassword = new Password
            {
                UserId          = "ABHW089",
                OldPassword     = "******",
                NewPassword     = "******",
                ConfirmPassword = "******",
                NewPasswordHash = "B1ge@rs*",

                IsValid = true
            };

            testPassword.SetHistory(new List <string> {
                "$sG96r#X", "3g9m&9W7"
            });

            validator = new ValidateHistory();
            validator.Setup(validTestRules);

            var result = validator.Validate(testPassword);

            result.Should().NotBe(null);
            result.IsValid.Should().BeFalse();
        }
コード例 #6
0
        private void ValidateUser(UserProxy user)
        {
            if (user == null)
            {
                ThrowHttp.BadRequest(ErrorMessage.USER_REQUIRED);
            }

            var emailError = _emailValidator.Validate(user.Email);

            if (emailError != null)
            {
                ThrowHttp.BadRequest(emailError);
            }

            var passwordError = _passwordValidator.Validate(user.Password);

            if (passwordError != null)
            {
                ThrowHttp.BadRequest(passwordError);
            }

            if (string.IsNullOrWhiteSpace(user.FirstName))
            {
                ThrowHttp.BadRequest(ErrorMessage.FIRST_NAME_REQUIRED);
            }

            if (string.IsNullOrWhiteSpace(user.LastName))
            {
                ThrowHttp.BadRequest(ErrorMessage.LAST_NAME_REQUIRED);
            }
        }
コード例 #7
0
        public void Validate_WrongPassword_ReturnFalse()
        {
            // Arrange
            var hash     = new byte[] { 0, 72, 123, 11 };
            var salt     = new byte[] { 11, 12, 13, 14 };
            var password = new Password(hash, salt);

            var enteredPasswordHash = new byte[] { 11, 11, 11, 11 };

            _passwordHashServiceMock
            .Setup(s => s.Hash(It.IsAny <string>(), It.IsAny <byte[]>()))
            .Returns(enteredPasswordHash);

            // Act
            var result = _passwordValidator.Validate("some password", password);

            // Assert
            Assert.False(result);
        }
        public (bool, string) VerifyPassword(string password)
        {
            (bool isValid, string message)validationResult = _validator.Validate(password);

            if (validationResult.isValid)
            {
                _repository.Create(password);
            }

            return(validationResult);
        }
コード例 #9
0
        public void Test_ValidateHistory_Success()
        {
            validator = new ValidateHistory();
            validator.Setup(validTestRules);

            var result = validator.Validate(validTestPassword);

            validator.Type.Should().Be(ValidatorTypes.History);
            result.Should().NotBe(null);
            result.IsValid.Should().BeTrue();
        }
コード例 #10
0
        private string changePassword(IUser user, string oldPassword, string newPassword)
        {
            Notification notification = _validator.Validate(newPassword);

            if (!notification.IsValid())
            {
                throw new Exception(notification.AllMessages.FirstOrDefault().ToString());
            }

            if (user.Password.IsEmpty())
            {
                return(_passwordHelperService.CreatePassword(newPassword));
            }

            if (_passwordHelperService.ComparePassword(oldPassword, user.Password))
            {
                return(_passwordHelperService.CreatePassword(newPassword));
            }

            throw new Exception("Password provided did not match the current password");
        }
コード例 #11
0
        public void Test_ValidateHistory_Null_Parameter()
        {
            validator = new ValidateHistory();
            validator.Setup(validTestRules);

            var result = new Action(() =>
            {
                validator.Validate(null);
            });

            result.ShouldThrow <ArgumentNullException>();
        }
コード例 #12
0
        public Tuple <bool, string> ValidatePassword(string password, IPasswordValidator passwordValidator)
        {
            passwordValidator = passwordValidator ??
                                throw new ArgumentNullException($"{nameof(passwordValidator)} cannot be null.");

            var result = passwordValidator.Validate(password);

            if (result.Item1)
            {
                this._repository.Create(password);
            }

            return(result);
        }
        public Tuple <string, bool> Verify(string password)
        {
            try
            {
                validator.Validate(password);
                repository.Create(password);
            }
            catch (ArgumentException e)
            {
                return(new Tuple <string, bool>(e.Message, false));
            }

            return(new Tuple <string, bool>("Password is Ok. User was created", true));
        }
コード例 #14
0
        public IActionResult Validate([FromBody] PasswordValidateRequestDto requestDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (string.IsNullOrWhiteSpace(requestDto.Password))
            {
                return(BadRequest());
            }

            return(Ok(_passwordValidator.Validate(requestDto.Password)));
        }
コード例 #15
0
        public async Task <int> RegisterConsumerUser(string userName, string password, string confirmPassword)
        {
            Ensure.ArgumentNotNull(userName, nameof(userName));
            Ensure.ArgumentNotNull(password, nameof(password));
            Ensure.ArgumentNotNull(confirmPassword, nameof(confirmPassword));

            if (!_passwordValidator.Validate(password))
            {
                throw new ApiException("Password does not meet complexity requirements.");
            }

            int userId = await _repository.CreateConsumerUser(userName, _passwordHasher.Hash(password));

            return(userId);
        }
コード例 #16
0
        async Task <bool> Password(string input)
        {
            if (!_passwordValidator.Validate(input, out string err))
            {
                await Connection.SendErrorAsync(err);

                return(false);
            }

            _password = new SecureString();
            foreach (var c in input)
            {
                _password.AppendChar(c);
            }
            _password.MakeReadOnly();

            return(true);
        }
コード例 #17
0
 public async Task <IActionResult> ValidatePassword([FromBody] User userDto)
 {
     try
     {
         var user   = _mapper.Map <Core.Data.Entities.User>(userDto);
         var result = _passwordValidator.Validate(user, userDto.Password);
         if (result != null)
         {
             return(Ok(result));
         }
         return(NotFound());
     }
     catch (Exception ex)
     {
         _logger.LogError($"Error occured while validating password, email: {userDto.Email}", ex);
         return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
     }
 }
コード例 #18
0
        public TUser ChangePassword(Guid changePasswordRequestId, string password)
        {
            var changePasswordRequest = changePasswordRequestDataStorage.FindChangePasswordRequest(changePasswordRequestId);

            if (changePasswordRequest == null)
            {
                throw new ChangePasswordRequestNotFoundException(changePasswordRequestId);
            }
            if (changePasswordRequest.IsUsed)
            {
                throw new ChangePasswordRequestAlreadyCompleteException(changePasswordRequestId);
            }
            if (changePasswordRequest.Expired)
            {
                throw new ChangePasswordRequestExpriredException(changePasswordRequestId);
            }

            if (!passwordValidator.Validate(password))
            {
                throw new WeakPasswordException();
            }

            var user = userStorage.FindUser(changePasswordRequest.UserId);

            if (user == null)
            {
                throw new UserNotFoundException(changePasswordRequest.UserId);
            }

            changePasswordRequest.PasswordChangeDateTime = DateTimeOffset.UtcNow;
            changePasswordRequestDataStorage.UpdateChangePasswordRequest(changePasswordRequest);

            SetUserPassword(user, password);

            if (!user.IsActive)
            {
                user.DateTimeActivated = DateTimeOffset.UtcNow;
            }

            userStorage.UpdateUser(user);
            return(userStorage.FindUser(user.UserId));
        }
コード例 #19
0
        public async Task <UserLoginResponse?> Login(UserLoginRequest request)
        {
            var user = await _dbContext.Users.SingleOrDefaultAsync(u => u.Email == request.Email);

            if (user == null)
            {
                return(null);
            }

            var passwordValid = _passwordValidator.Validate(request.Password, user.Password);

            if (!passwordValid)
            {
                return(null);
            }

            var loggedInUser = new LoggedInUserDto(user.Id, user.GetMainPhoto()?.Url);

            return(new UserLoginResponse(loggedInUser, _tokenService.Generate(user)));
        }
コード例 #20
0
        public void Register(string name, string login, string password, string passwordConfirm, double balance)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }
            _loginValidator.Validate(login);
            _passwordValidator.Validate(password);
            if (passwordConfirm != password)
            {
                throw new ArgumentException("Password confirmation wrong", nameof(passwordConfirm));
            }

            var user = Users.FindByLogin(login);

            if (user != null)
            {
                throw new DuplicateLoginException();
            }

            Users.Add(name, login, password, balance);
        }
コード例 #21
0
        public async Task <IActionResult> RegisterAsync([FromBody] RegisterUserModel model)
        {
            var user = Mapper.Map <UserDto>(model);

            try
            {
                var errors = Mapper.Map <Errors>(passwordValidator.Validate(model.Password));

                if (!errors.Any())
                {
                    var createdUser = await userService.CreateAsync(user, model.Password);

                    var userModel = Mapper.Map <User>(createdUser);
                    return(Created(String.Empty, userModel));
                }

                return(BadRequest(errors));
            }
            catch (UserException ex)
            {
                return(BadRequest(new Errors(ex.Message)));
            }
        }
コード例 #22
0
        public bool Login(string email, string password)
        {
            if (!_emailValidator.Validate(email))
            {
                throw new InvalidEmailException(email);
            }
            if (!_passwordValidator.Validate(password))
            {
                throw new InvalidPasswordException();
            }
            var user = _userRepository.FindUser(email);

            if (user == null)
            {
                throw new UserNotFoundException(email);
            }
            var comparePass = user.Password.Equals(password);

            if (!comparePass)
            {
                throw new NotPasswordMatchException();
            }
            return(true);
        }
コード例 #23
0
 protected ValidateUser ValidatePassword()
 {
     _passwordValidator.Validate(User);
     IsValid = _passwordValidator.IsValid();
     return(this);
 }
コード例 #24
0
 public static int ValidPasswordCount(this string[] input, IPasswordValidator validator)
 {
     return(input
            .Where(x => validator.Validate(x))
            .Count());
 }