/// <inheritdoc />
        public CreateUserValidator(
            IUnitOfWork ufw,
            IValidationLocalizer localizer,
            IIdentityAppSettings settings,
            IConfiguration?configuration)
        {
            _ufw = ufw;

            RuleFor(_ => _.Description)
            .Length(0, 250)
            .WithMessage(localizer.Message(ValidationConstants.Max250LengthMessageTemplate))
            .WithName(localizer.Name(FieldNameConstants.Description));

            RuleFor(_ => _.UserName)
            .Length(0, 50)
            .WithMessage(localizer.Message(ValidationConstants.Max50LengthMessageTemplate))
            .NotEmpty()
            .WithMessage(localizer.Message(ValidationConstants.NotEmptyMessageTemplate))
            .Must(Validation.UserNameIsValid)
            .WithMessage(localizer.Message(ValidationConstants.OnlyLatinAndSpecSymbolsTemplate))
            .WithName(localizer.Name(FieldNameConstants.UserName));

            RuleFor(_ => _.UserName)
            .Must(UniqueName)
            .WithMessage(localizer.Message(ValidationConstants.EntityMustBeUniqueTemplate))
            .WithName(localizer.Name(FieldNameConstants.UserName));

            RuleFor(_ => _.RoleId)
            .NotEmpty()
            .WithMessage(localizer.Message(ValidationConstants.NotEmptyMessageTemplate))
            .Must(RoleExists)
            .WithMessage(localizer.Message(ValidationConstants.RoleNotFoundTemplate))
            .WithName(localizer.Name(FieldNameConstants.Role));

            RuleFor(_ => _.Password)
            .NotEmpty()
            .WithMessage(localizer.Message(ValidationConstants.NotEmptyMessageTemplate))
            .WithName(localizer.Name(FieldNameConstants.Password));

            PasswordRulesHelper.PasswordBaseRules(
                this,
                settings.PasswordPolicy,
                _ => _.Password,
                localizer,
                configuration,
                FieldNameConstants.Password);

            RuleFor(_ => _.Password)
            .Length(settings.PasswordPolicy.MinimumLength, settings.PasswordPolicy.MaximumLength)
            .WithMessage(
                localizer.Message(ValidationConstants.PasswordRequiredLength, settings.PasswordPolicy.MinimumLength, settings.PasswordPolicy.MaximumLength))
            .When(_ => !string.IsNullOrWhiteSpace(_.Password))
            .WithName(localizer.Name(FieldNameConstants.Password));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Checks the user.
        /// </summary>
        /// <param name="credentials">The credentials.</param>
        /// <returns></returns>
        /// <exception cref="AuthorizationErrorException"></exception>
        private async Task <User> CheckUser(LoginByPassCredentials credentials)
        {
            var user = await GetUser(credentials.UserName);

            if (user == null)
            {
                //_logger.Error(_validationLocalizer.Message(ValidationConstants.InvalidLoginOrPassword), LoggerEntityType.AuthProfileEntity, null);
                throw new AuthorizationErrorException(_validationLocalizer.Message(ValidationConstants.InvalidLoginOrPassword));
            }
            if (user.Status == UserStatus.Locked)
            {
                //_logger.Error(_validationLocalizer.Message(ValidationConstants.UserLocked), LoggerEntityType.AuthProfileEntity, user.UserName);
                throw new AuthorizationErrorException(_validationLocalizer.Message(ValidationConstants.UserLocked));
            }
            await CheckPasswordAsync(user, credentials.Password);

            return(user);
        }
        /// <inheritdoc />
        public ChangePasswordValidator(
            IValidationLocalizer localizer,
            IHttpContextAccessor accessor,
            UserManager <User> userManager,
            IIdentityAppSettings settings,
            IConfiguration configuration)
        {
            _userManager = userManager;

            RuleFor(_ => _.NewPassword)
            .NotEmpty()
            .WithMessage(localizer.Message(ValidationConstants.NotEmptyMessageTemplate))
            .WithName(localizer.Name(FieldNameConstants.NewPassword));

            RuleFor(_ => _.NewPassword)
            .MustAsync((_, x, y) => CheckNewPassword(accessor.HttpContext !.User !.Identity !.Name !, _))
            .WithMessage(localizer.Message(ValidationConstants.OldAndNewPassMatch))
            .WithName(localizer.Name(FieldNameConstants.NewPassword));

            RuleFor(_ => _.ConfirmNewPassword)
            .Must((x, y) => x.ConfirmNewPassword == x.NewPassword)
            .WithMessage(localizer.Message(ValidationConstants.NewPassAndConfirmMustBeEqual))
            .WhenAsync((_, x) => CheckOldPass(accessor.HttpContext !.User.Identity !.Name !, _.OldPassword));

            RuleFor(_ => _.OldPassword)
            .MustAsync((_, x) => CheckOldPass(accessor.HttpContext !.User.Identity !.Name !, _))
            .WithMessage(localizer.Message(ValidationConstants.CurrentPasswordIncorrectTemplate));

            PasswordRulesHelper.PasswordBaseRules(
                this,
                settings.PasswordPolicy,
                _ => _.NewPassword,
                localizer,
                configuration,
                FieldNameConstants.NewPassword);

            RuleFor(_ => _.NewPassword)
            .Length(settings.PasswordPolicy.MinimumLength, settings.PasswordPolicy.MaximumLength)
            .WithMessage(
                localizer.Message(ValidationConstants.PasswordRequiredLength, settings.PasswordPolicy.MinimumLength, settings.PasswordPolicy.MaximumLength))
            .When(_ => !string.IsNullOrWhiteSpace(_.NewPassword))
            .WithName(localizer.Name(FieldNameConstants.NewPassword));
        }
        /// <summary>
        /// Устанавливает правила валидации для пароля:
        /// - необходимы ли цифры;
        /// - символы в верхнем регистре;
        /// - символы в нижнем регистре;
        /// - нечисловые и нецифровые символы.
        /// </summary>
        /// <param name="passwordSettings"></param>
        /// <param name="expressionField">Поле, для которого необходимо установить правила валиацдии пароля</param>
        /// <param name="configuration"></param>
        /// <param name="fieldName">Название поля для ошибок</param>
        /// <param name="validator"></param>
        /// <param name="localizer"></param>
        /// <returns></returns>
        public static void PasswordBaseRules <T>(
            AbstractValidator <T> validator,
            PasswordPolicy passwordSettings,
            Expression <Func <T, string?> > expressionField,
            IValidationLocalizer localizer,
            IConfiguration?configuration,
            string fieldName = "Пароль")
        {
            var weakPasswordsSection = configuration?.GetSection("WeakPasswords")?.Get <List <string>?>();

            validator.RuleFor(expressionField)
            .Must(_ => !ContainsWeakPassword(_ !, weakPasswordsSection))
            .WithMessage(localizer.Message(ValidationConstants.PasswordContainsPopularPassword))
            .WithName(localizer.Name(fieldName));

            validator.RuleFor(expressionField)
            .Must(Validation.ContainsDigits)
            .WithMessage(localizer.Message(ValidationConstants.ContainsDigitsTemplate))
            .When(dto => passwordSettings.RequireDigit, ApplyConditionTo.CurrentValidator)
            .WithName(localizer.Name(fieldName));

            validator.RuleFor(expressionField)
            .Must(Validation.ContainsLowerCase)
            .WithMessage(localizer.Message(ValidationConstants.ContainsLowerCaseTemplate))
            .When(dto => passwordSettings.RequireLowercase, ApplyConditionTo.CurrentValidator)
            .WithName(localizer.Name(fieldName));

            validator.RuleFor(expressionField)
            .Must(Validation.ContainsUpperCase)
            .WithMessage(localizer.Message(ValidationConstants.ContainsUpperCaseTemplate))
            .When(dto => passwordSettings.RequireUppercase, ApplyConditionTo.CurrentValidator)
            .WithName(localizer.Name(fieldName));

            validator.RuleFor(expressionField)
            .Must(Validation.ContainsNonAlphaNumeric)
            .WithMessage(localizer.Message(ValidationConstants.ContainsNonAlphaNumericTemplate))
            .When(dto => passwordSettings.RequireNonAlphanumeric, ApplyConditionTo.CurrentValidator)
            .WithName(localizer.Name(fieldName));
        }
Exemplo n.º 5
0
        /// <inheritdoc />
        public async Task ChangePasswordAsync(
            string userName,
            string newPassword,
            bool passwordForReset   = false,
            CancellationToken token = default)
        {
            var curUser = await _userManager.FindByNameAsync(userName).ConfigureAwait(false);

            if (curUser == null)
            {
                throw new EntityNotFoundException();
            }

            if (!passwordForReset)
            {
                throw new WebSshServiceException(_localizer.Message(ValidationConstants.NewPasswordHasBeenUsedBefore));
            }

            string oldHash = curUser.PasswordHash;

            await _userManager.RemovePasswordAsync(curUser).ConfigureAwait(false);

            await _userManager.AddPasswordAsync(curUser, newPassword).ConfigureAwait(false);

            curUser.DatePasswordChanged = DateTimeOffset.UtcNow;

            curUser.PasswordResetedByAdministrator = passwordForReset;

            await _userManager.UpdateAsync(curUser);

            var hashHistoryRepo = _ufw.Repository <UserPasswordHashHistory>();
            var hashHistory     = new UserPasswordHashHistory
            {
                DateChanged = DateTime.Now,
                Hash        = oldHash,
                UserId      = curUser.Id,
            };
            await hashHistoryRepo.CreateAsync(hashHistory, token);
        }
        /// <inheritdoc />
        public ChangePasswordForUserValidator(
            IValidationLocalizer localizer,
            IIdentityAppSettings settings,
            IUnitOfWork ufw,
            IConfiguration?configuration)
        {
            _ufw = ufw;
            RuleFor(_ => _.UserId)
            .NotEmpty()
            .WithMessage(localizer.Message(ValidationConstants.NotEmptyMessageTemplate))
            .WithName(localizer.Name(FieldNameConstants.User));

            RuleFor(_ => _.UserId)
            .Must(UserExists)
            .WithMessage(localizer.Message(ValidationConstants.UserNotFound));

            RuleFor(_ => _.NewPassword)
            .NotEmpty()
            .WithMessage(localizer.Message(ValidationConstants.NotEmptyMessageTemplate))
            .WithName(localizer.Name(FieldNameConstants.Password));

            PasswordRulesHelper.PasswordBaseRules(
                this,
                settings.PasswordPolicy,
                _ => _.NewPassword,
                localizer,
                configuration,
                FieldNameConstants.Password);

            RuleFor(_ => _.NewPassword)
            .Length(settings.PasswordPolicy.MinimumLength, settings.PasswordPolicy.MaximumLength)
            .WithMessage(
                localizer.Message(ValidationConstants.PasswordRequiredLength, settings.PasswordPolicy.MinimumLength, settings.PasswordPolicy.MaximumLength))
            .When(_ => !string.IsNullOrWhiteSpace(_.NewPassword))
            .WithName(localizer.Name(FieldNameConstants.NewPassword));
        }
Exemplo n.º 7
0
        public PasswordPolicySettingValidator(
            IValidationLocalizer localizer)
        {
            RuleFor(_ => _.MinimumLength)
            .GreaterThanOrEqualTo(6)
            .WithMessage(localizer.Message(ValidationConstants.MoreOrEqualTemplate) + " 6")
            .LessThanOrEqualTo(30)
            .WithMessage(localizer.Message(ValidationConstants.MaxOrEqualTemplate) + " 30")
            .WithName(localizer.Name(FieldNameConstants.MinPasswordLength));

            RuleFor(_ => _.RequiredMaxExpireTime)
            .GreaterThan(0)
            .WithMessage(localizer.Message(ValidationConstants.MoreZeroTemplate))
            .LessThanOrEqualTo(90)
            .WithMessage(
                localizer.Message(ValidationConstants.MaxOrEqualTemplate) + " 90")
            .WithName(localizer.Name(FieldNameConstants.MaxPassExpireTime));

            RuleFor(_ => _.MaxFailedAccessAttempts)
            .GreaterThanOrEqualTo(3)
            .WithMessage(
                localizer.Message(ValidationConstants.MoreOrEqualTemplate) + " 3")
            .LessThanOrEqualTo(8)
            .WithMessage(
                localizer.Message(ValidationConstants.MaxOrEqualTemplate) + " 8")
            .WithName(localizer.Name(FieldNameConstants.MaxNumberOfPasswordAttempts));

            RuleFor(_ => _.DefaultLockoutTimeSpan)
            .GreaterThanOrEqualTo(10)
            .WithMessage(
                localizer.Message(ValidationConstants.MoreOrEqualTemplate) + " 10")
            .LessThanOrEqualTo(30)
            .WithMessage(
                localizer.Message(ValidationConstants.MaxOrEqualTemplate) + " 30")
            .WithName(localizer.Name(FieldNameConstants.UserLockTime));
        }
Exemplo n.º 8
0
        /// <inheritdoc />
        public UpdateUserValidator(
            IUnitOfWork ufw,
            IValidationLocalizer localizer)
        {
            _ufw = ufw;

            RuleFor(_ => _.Id)
            .Must((_, x) => CheckDefaultUser(_))
            .WithMessage(localizer.Message(ValidationConstants.ChangingDefaultUserIsProhibited));

            RuleFor(_ => _.Description)
            .Length(0, 250)
            .WithMessage(localizer.Message(ValidationConstants.Max250LengthMessageTemplate))
            .WithName(localizer.Name(FieldNameConstants.Description));

            RuleFor(_ => _.UserName)
            .Length(0, 50)
            .WithMessage(localizer.Message(ValidationConstants.Max50LengthMessageTemplate))
            .NotEmpty()
            .WithMessage(localizer.Message(ValidationConstants.NotEmptyMessageTemplate))
            .Must(Validation.UserNameIsValid)
            .WithMessage(localizer.Message(ValidationConstants.OnlyLatinAndSpecSymbolsTemplate))
            .WithName(localizer.Name(FieldNameConstants.UserName));

            RuleFor(_ => _.UserName)
            .Must((x, y) => UniqueName(x))
            .WithMessage(localizer.Message(ValidationConstants.EntityMustBeUniqueTemplate))
            .WithName(localizer.Name(FieldNameConstants.UserName));

            RuleFor(_ => _.RoleId)
            .NotEmpty()
            .WithMessage(localizer.Message(ValidationConstants.NotEmptyMessageTemplate))
            .Must(RoleExists)
            .WithMessage(localizer.Message(ValidationConstants.RoleNotFoundTemplate))
            .WithName(localizer.Name(FieldNameConstants.Role));
        }