Example #1
0
        public bool Validate(IValidatable sender, string fieldName, object value)
        {
            IFieldValidator constraint = Constraints[fieldName];

            if (constraint == null)
            {
                return(true);
            }                                       //nothing to validate, pass
            string message;

            if (constraint.Level == ErrorLevel.Error)
            {
                message = constraint.ErrorMessage;
            }
            else if (constraint.Level == ErrorLevel.Warning)
            {
                message = "Warning::" + constraint.ErrorMessage;
            }
            else
            {
                message = String.Empty;
            }
            if (constraint.Validate(sender, value) == false)//fail validation
            {
                sender.AddError(fieldName, message);
                return(false);
            }
            else //passes validation
            {
                sender.RemoveError(fieldName, message);
                return(true);
            }
        }
Example #2
0
        protected override void InitializeFieldValidators(IDecimalMetaField metaField)
        {
            base.InitializeFieldValidators(metaField);

            IFieldValidator fieldValidator = GetFieldValidator <decimal?>(nameof(IDecimalMetaField.MinValue));

            MinValueFieldItemViewModel = TextBoxFieldItemViewModel.Create(fieldValidator, Entity,
                                                                          metaField.MinValue?.ToString(CultureInfo.CurrentCulture));
            EditableItemsFields.Add(MinValueFieldItemViewModel);

            fieldValidator             = GetFieldValidator <decimal?>(nameof(IDecimalMetaField.MaxValue));
            MaxValueFieldItemViewModel = TextBoxFieldItemViewModel.Create(fieldValidator, Entity,
                                                                          metaField.MaxValue?.ToString(CultureInfo.CurrentCulture));
            EditableItemsFields.Add(MaxValueFieldItemViewModel);

            fieldValidator          = GetFieldValidator <int?>(nameof(IDecimalMetaField.Scale));
            ScaleFieldItemViewModel =
                TextBoxFieldItemViewModel.Create(fieldValidator, Entity, metaField.Scale.ToString());
            EditableItemsFields.Add(ScaleFieldItemViewModel);

            fieldValidator = GetFieldValidator <decimal?>(nameof(IDecimalMetaField.DefaultValue));
            DefaultValueFieldItemViewModel = TextBoxFieldItemViewModel.Create(fieldValidator, Entity,
                                                                              metaField.DefaultValue?.ToString(CultureInfo.CurrentCulture));
            EditableItemsFields.Add(DefaultValueFieldItemViewModel);
        }
        protected BaseFieldValidationWrapper(T objectForWrapping, IFieldValidator <T> fieldValidator)
        {
            InnerObj        = objectForWrapping;
            _fieldValidator = fieldValidator;

            InitializeValidator();
        }
        protected override void InitializeFieldValidators(IStringMetaField metaField)
        {
            base.InitializeFieldValidators(metaField);

            IFieldValidator fieldValidator = GetFieldValidator <int?>(nameof(IStringMetaField.MinLength));

            MinLengthFieldItemViewModel =
                TextBoxFieldItemViewModel.Create(fieldValidator, Entity, metaField.MinLength.ToString());
            EditableItemsFields.Add(MinLengthFieldItemViewModel);
            fieldValidator = GetFieldValidator <int?>(nameof(IStringMetaField.MaxLength));
            MaxLengthFieldItemViewModel =
                TextBoxFieldItemViewModel.Create(fieldValidator, Entity, metaField.MaxLength.ToString());
            EditableItemsFields.Add(MaxLengthFieldItemViewModel);
            fieldValidator = GetFieldValidator <int?>(nameof(IStringMetaField.DisplayedLinesCount));
            DisplayedLinesCountFieldItemViewModel = TextBoxFieldItemViewModel.Create(fieldValidator, Entity,
                                                                                     metaField.DisplayedLinesCount.ToString());
            EditableItemsFields.Add(DisplayedLinesCountFieldItemViewModel);
            fieldValidator = GetFieldValidator <string>(nameof(IStringMetaField.DefaultValue));
            DefaultValueFieldItemViewModel =
                TextBoxFieldItemViewModel.Create(fieldValidator, Entity, metaField.DefaultValue);
            EditableItemsFields.Add(DefaultValueFieldItemViewModel);
            fieldValidator = GetFieldValidator <IEntity>(nameof(IStringMetaField.RegularExpression));
            var regularExpressions          = MetaDataService.GetRegularExpressions().OrderBy(me => me.Label).ToList();
            var regularExpressionViewModels = regularExpressions.Select(RegularExpressionItemViewModel.Create);

            EntityRegularExpressionFieldItemViewModel =
                EntityFieldItemViewModel.Create(fieldValidator, Entity,
                                                regularExpressionViewModels, metaField.RegularExpression);
            EditableItemsFields.Add(EntityRegularExpressionFieldItemViewModel);
        }
Example #5
0
 public WebsiteValidator(ILoginValidator loginValidator,
                         IFieldValidator fieldValidator,
                         IWebsiteHomepageSnapshotValidator websiteHomepageSnapshotValidator)
 {
     LoginValidator = loginValidator;
     FieldValidator = fieldValidator;
     WebsiteHomepageSnapshotValidator = websiteHomepageSnapshotValidator;
 }
        public void Add(IFieldValidator fv)
        {
            var fieldName = fv.Field;
            if (!HasConstraint(fieldName)) { lookup.Add(fieldName, fv); }
            if (object.ReferenceEquals(lookup[fieldName], fv)) { return; }

            lookup[fieldName] = fv;
        }
        protected override void InitializeFieldValidators(IBooleanMetaField metaField)
        {
            base.InitializeFieldValidators(metaField);

            IFieldValidator fieldValidator = GetFieldValidator <bool?>(nameof(IBooleanMetaField.DefaultValue));

            DefaultValueFieldItemViewModel =
                CheckBoxFieldItemViewModel.Create(fieldValidator, Entity, metaField.DefaultValue);
            EditableItemsFields.Add(DefaultValueFieldItemViewModel);
        }
Example #8
0
        private ValueCheckingResult CheckValue <TValue>(IFieldValidator <TValue> fieldValidator, TValue value)
        {
            var result = new ValueCheckingResult(fieldValidator.MetaField.Id.ToString());

            if (fieldValidator.MetaField.IsRequired && value == null)
            {
                result.InvalidMessage = "InvalidMessage";
            }

            return(result);
        }
Example #9
0
        public void Add(IFieldValidator fv)
        {
            var fieldName = fv.Field;

            if (!HasConstraint(fieldName))
            {
                lookup.Add(fieldName, fv);
            }
            if (object.ReferenceEquals(lookup[fieldName], fv))
            {
                return;
            }

            lookup[fieldName] = fv;
        }
        protected override void InitializeFieldValidators(IDateTimeMetaField metaField)
        {
            base.InitializeFieldValidators(metaField);

            IFieldValidator fieldValidator = GetFieldValidator <DateTime?>(nameof(IIntegerMetaField.MinValue));

            MinValueFieldItemViewModel = DateFieldItemViewModel.Create(fieldValidator, Entity, metaField.MinValue);
            EditableItemsFields.Add(MinValueFieldItemViewModel);
            fieldValidator             = GetFieldValidator <DateTime?>(nameof(IIntegerMetaField.MaxValue));
            MaxValueFieldItemViewModel = DateFieldItemViewModel.Create(fieldValidator, Entity, metaField.MaxValue);
            fieldValidator             = GetFieldValidator <DateTime?>(nameof(IIntegerMetaField.DefaultValue));
            EditableItemsFields.Add(MaxValueFieldItemViewModel);
            DefaultValueFieldItemViewModel =
                DateFieldItemViewModel.Create(fieldValidator, Entity, metaField.DefaultValue);
            EditableItemsFields.Add(DefaultValueFieldItemViewModel);
        }
Example #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FieldDescriptor"/> class.
        /// </summary>
        /// <param name="lengthFormatter">
        /// The length formatter.
        /// </param>
        /// <param name="validator">
        /// The validator.
        /// </param>
        /// <param name="formatter">
        /// The formatter.
        /// </param>
        /// <param name="adjuster">
        /// The adjuster.
        /// </param>
        public FieldDescriptor(ILengthFormatter lengthFormatter, IFieldValidator validator, IFormatter formatter, Adjuster adjuster)
        {
            if (formatter is BinaryFormatter && !(validator is HexFieldValidator))
            {
                throw new FieldDescriptorException("A Binary field must have a hex validator");
            }

            if (formatter is BcdFormatter && !(validator is NumericFieldValidator))
            {
                throw new FieldDescriptorException("A BCD field must have a numeric validator");
            }

            this.LengthFormatter = lengthFormatter;
            this.Validator       = validator;
            this.Formatter       = formatter;
            Adjuster             = adjuster;
        }
        public UploadFieldValueAttachmentCommandValidator(
            IProjectValidator projectValidator,
            ITagValidator tagValidator,
            IFieldValidator fieldValidator)
        {
            CascadeMode = CascadeMode.Stop;

            RuleFor(command => command)
            .MustAsync((command, token) => NotBeAClosedProjectForTagAsync(command.TagId, token))
            .WithMessage(command => $"Project for tag is closed! Tag={command.TagId}")
            .MustAsync(BeAnExistingRequirementAsync)
            .WithMessage(command => "Tag and/or requirement doesn't exist!")
            .MustAsync(BeAnExistingFieldForRequirementAsync)
            .WithMessage(command => "Field doesn't exist in requirement!")
            .MustAsync((command, token) => NotBeAVoidedTagAsync(command.TagId, token))
            .WithMessage(command => $"Tag is voided! Tag={command.TagId}")
            .MustAsync((command, token) => HasRequirementWithActivePeriodAsync(command.TagId, command.RequirementId, token))
            .WithMessage(command =>
                         $"Tag doesn't have this requirement with active period! Tag={command.TagId}. Requirement={command.RequirementId}")
            .MustAsync((command, token) => BeAFieldForAttachmentAsync(command.FieldId, token))
            .WithMessage(command => $"Field values can not be recorded for field type! Field={command.FieldId}")
            .MustAsync((command, token) => NotBeAVoidedFieldAsync(command.FieldId, token))
            .WithMessage(command => $"Field is voided! Field={command.FieldId}");

            async Task <bool> NotBeAClosedProjectForTagAsync(int tagId, CancellationToken token)
            => !await projectValidator.IsClosedForTagAsync(tagId, token);

            async Task <bool> BeAnExistingRequirementAsync(UploadFieldValueAttachmentCommand command, CancellationToken token)
            => await tagValidator.ExistsRequirementAsync(command.TagId, command.RequirementId, token);

            async Task <bool> BeAnExistingFieldForRequirementAsync(UploadFieldValueAttachmentCommand command, CancellationToken token)
            => await tagValidator.ExistsFieldForRequirementAsync(command.TagId, command.RequirementId, command.FieldId, token);

            async Task <bool> NotBeAVoidedTagAsync(int tagId, CancellationToken token)
            => !await tagValidator.IsVoidedAsync(tagId, token);

            async Task <bool> HasRequirementWithActivePeriodAsync(int tagId, int requirementId, CancellationToken token)
            => await tagValidator.HasRequirementWithActivePeriodAsync(tagId, requirementId, token);

            async Task <bool> NotBeAVoidedFieldAsync(int fieldId, CancellationToken token)
            => !await fieldValidator.IsVoidedAsync(fieldId, token);

            async Task <bool> BeAFieldForAttachmentAsync(int fieldId, CancellationToken token)
            => await fieldValidator.IsValidForAttachmentAsync(fieldId, token);
        }
        protected override void InitializeFieldValidators(IEntityMetaField metaField)
        {
            base.InitializeFieldValidators(metaField);

            IFieldValidator fieldValidator = GetFieldValidator <int?>(nameof(IEntityMetaField.DefaultValueId));

            DefaultValueIdFieldItemViewModel =
                TextBoxFieldItemViewModel.Create(fieldValidator, Entity, metaField.DefaultValueId.ToString());
            EditableItemsFields.Add(DefaultValueIdFieldItemViewModel);
            fieldValidator = GetFieldValidator <IEntity>(nameof(IEntityMetaField.ValueType));
            var metaEntities         = MetaDataService.GetMetaEntities().OrderBy(me => me.Label).ToList();
            var metaEntityViewModels = metaEntities.Select(MetaEntityItemViewModel.Create);
            var metaEntity           = metaEntities.SingleOrDefault(me => me.Id == metaField.ValueType?.Id);

            ValueTypeFieldItemViewModel =
                EntityFieldItemViewModel.Create(fieldValidator, Entity, metaEntityViewModels, metaEntity);
            EditableItemsFields.Add(ValueTypeFieldItemViewModel);
        }
        private void InitializeFieldValidators(IMetaEntity metaEntity)
        {
            IFieldValidator fieldValidator = GetFieldValidator <string>(nameof(IMetaEntity.InterfaceName));

            InterfaceNameFieldItemViewModel =
                TextBoxFieldItemViewModel.Create(fieldValidator, Entity, metaEntity.InterfaceName);
            EditableItemsFields.Add(InterfaceNameFieldItemViewModel);
            fieldValidator          = GetFieldValidator <string>(nameof(IMetaEntity.Label));
            LabelFieldItemViewModel = TextBoxFieldItemViewModel.Create(fieldValidator, Entity, metaEntity.Label);
            EditableItemsFields.Add(LabelFieldItemViewModel);
            fieldValidator = GetFieldValidator <string>(nameof(IMetaEntity.PlurialLabel));
            PlurialLabelFieldItemViewModel =
                TextBoxFieldItemViewModel.Create(fieldValidator, Entity, metaEntity.PlurialLabel);
            EditableItemsFields.Add(PlurialLabelFieldItemViewModel);
            fieldValidator = GetFieldValidator <bool?>(nameof(IMetaEntity.IsMasculine));
            IsMasculineFieldItemViewModel =
                CheckBoxFieldItemViewModel.Create(fieldValidator, Entity, metaEntity.IsMasculine);
            EditableItemsFields.Add(IsMasculineFieldItemViewModel);
            fieldValidator = GetFieldValidator <string>(nameof(IMetaEntity.Description));
            DescriptionFieldItemViewModel =
                TextBoxFieldItemViewModel.Create(fieldValidator, Entity, metaEntity.Description);
            EditableItemsFields.Add(DescriptionFieldItemViewModel);

            var metaField = ModelFactory.CreateMetaField(
                "MetaFieldTemplate",
                "Ajouter un méta-champ",
                "Choisissez un model de méta champ");

            var metaFieldTemplates          = MetaDataService.GetMetaFieldTemplates().OrderBy(me => me.Label).ToList();
            var metaFieldTemplateViewModels = metaFieldTemplates.Select(MetaFieldItemTemplateViewModel.Create);

            fieldValidator = ModelFactory.CreateFieldValidator <IEntity>(metaField);
            EntityService.CreateFieldValidator(fieldValidator);
            MetaFieldTemplateItemViewModel =
                EntityFieldItemViewModel.Create(fieldValidator, Entity, metaFieldTemplateViewModels, metaField);
            EditableItemsFields.Add(MetaFieldTemplateItemViewModel);
        }
Example #15
0
 /// <summary>
 /// Create a Binary variable length field descriptor
 /// </summary>
 /// <param name="lengthIndicator">length indicator</param>
 /// <param name="maxLength">max length of field</param>
 /// <param name="validator">validator to use on the field</param>
 /// <returns>field descriptor</returns>
 public static IFieldDescriptor BinaryVar(int lengthIndicator, int maxLength, IFieldValidator validator)
 {
     return(new FieldDescriptor(new VariableLengthFormatter(lengthIndicator, maxLength, Formatters.Ascii), FieldValidators.Hex, Formatters.Binary, null));
 }
Example #16
0
 /// <summary>
 /// Create an ASCII fixed length field descriptor
 /// </summary>
 /// <param name="packedLength">
 /// The packed length of the field. For BCD fields, this is half the size of the field you want
 /// </param>
 /// <param name="validator">
 /// Validator to use on the field
 /// </param>
 /// <returns>
 /// field descriptor
 /// </returns>
 public static IFieldDescriptor AsciiFixed(int packedLength, IFieldValidator validator)
 {
     return(Create(new FixedLengthFormatter(packedLength), validator, Formatters.Ascii));
 }
Example #17
0
 /// <summary>
 /// Create an ASCII variable length field descriptor
 /// </summary>
 /// <param name="lengthIndicator">
 /// length indicator
 /// </param>
 /// <param name="maxLength">
 /// maximum length of the field
 /// </param>
 /// <param name="validator">
 /// Validator to use on the field
 /// </param>
 /// <returns>
 /// field descriptor
 /// </returns>
 public static IFieldDescriptor AsciiVar(int lengthIndicator, int maxLength, IFieldValidator validator)
 {
     return(Create(new VariableLengthFormatter(lengthIndicator, maxLength), validator, Formatters.Ascii));
 }
Example #18
0
 /// <summary>
 ///   Create an ASCII variable length field
 /// </summary>
 /// <param name = "fieldNumber">field number</param>
 /// <param name = "lengthIndicator">length indicator</param>
 /// <param name = "maxLength">maximum length of field</param>
 /// <param name = "validator">validator to use on the field</param>
 /// <returns>field</returns>
 public static IField AsciiVar(int fieldNumber, int lengthIndicator, int maxLength, IFieldValidator validator)
 {
     return(new Field(fieldNumber, FieldDescriptor.AsciiVar(lengthIndicator, maxLength, validator)));
 }
Example #19
0
        public UpdateRequirementDefinitionCommandValidator(
            IRequirementTypeValidator requirementTypeValidator,
            IRequirementDefinitionValidator requirementDefinitionValidator,
            IFieldValidator fieldValidator)
        {
            CascadeMode = CascadeMode.Stop;

            RuleFor(command => command)
            .MustAsync(BeAnExistingRequirementDefinitionAsync)
            .WithMessage(command => "Requirement type and/or requirement definition doesn't exist!")
            .MustAsync((command, token) => NotBeAVoidedRequirementDefinitionAsync(command.RequirementDefinitionId, token))
            .WithMessage(command => $"Requirement definition is voided! Requirement definition={command.Title}")
            .MustAsync(RequirementDefinitionTitleMustBeUniqueOnType)
            .WithMessage(command => $"A requirement definition with this title already exists on the requirement type! Requirement type={command.Title}")
            .MustAsync((command, token) => AllFieldsToBeDeletedAreVoidedAsync(command.RequirementDefinitionId, command.UpdateFields, token))
            .WithMessage(command => $"Fields to be deleted must be voided! Requirement definition={command.Title}")
            .MustAsync((command, token) => NoFieldsToBeDeletedShouldBeInUseAsync(command.RequirementDefinitionId, command.UpdateFields, token))
            .WithMessage(command => $"Fields to be deleted can not be in use! Requirement definition={command.Title}");

            RuleForEach(command => command.UpdateFields)
            .MustAsync((command, field, __, token) => BeAnExistingField(command, field.Id, token))
            .WithMessage(command => "Field doesn't exist in requirement!")
            .MustAsync((command, field, __, token) => BeSameFieldTypeOnExistingFieldsAsync(field, token))
            .WithMessage((_, field) => $"Cannot change field type on existing fields! Field={field.Id}");

            async Task <bool> BeAnExistingRequirementDefinitionAsync(UpdateRequirementDefinitionCommand command, CancellationToken token)
            => await requirementTypeValidator.RequirementDefinitionExistsAsync(command.RequirementTypeId, command.RequirementDefinitionId, token);

            async Task <bool> NotBeAVoidedRequirementDefinitionAsync(int requirementDefinitionId, CancellationToken token)
            => !await requirementDefinitionValidator.IsVoidedAsync(requirementDefinitionId, token);

            async Task <bool> RequirementDefinitionTitleMustBeUniqueOnType(
                UpdateRequirementDefinitionCommand command,
                CancellationToken token)
            {
                var fieldTypesFromUpdated = command.UpdateFields.Select(uf => uf.FieldType).ToList();
                var fieldTypesFromNew     = command.NewFields.Select(nf => nf.FieldType).ToList();

                return(!await requirementTypeValidator.OtherRequirementDefinitionExistsWithSameTitleAsync(
                           command.RequirementTypeId,
                           command.RequirementDefinitionId,
                           command.Title,
                           fieldTypesFromUpdated.Concat(fieldTypesFromNew).Distinct().ToList(),
                           token));
            }

            async Task <bool> BeAnExistingField(UpdateRequirementDefinitionCommand command, int fieldId, CancellationToken token)
            => await requirementTypeValidator.FieldExistsAsync(command.RequirementTypeId, command.RequirementDefinitionId, fieldId, token);

            async Task <bool> BeSameFieldTypeOnExistingFieldsAsync(UpdateFieldsForCommand field, CancellationToken token)
            => await fieldValidator.VerifyFieldTypeAsync(field.Id, field.FieldType, token);

            async Task <bool> AllFieldsToBeDeletedAreVoidedAsync(int requirementDefinitionId, IList <UpdateFieldsForCommand> updateFields, CancellationToken token)
            {
                var updateFieldIds = updateFields.Select(u => u.Id).ToList();

                return(await requirementDefinitionValidator.AllExcludedFieldsAreVoidedAsync(requirementDefinitionId, updateFieldIds, token));
            }

            async Task <bool> NoFieldsToBeDeletedShouldBeInUseAsync(int requirementDefinitionId, IList <UpdateFieldsForCommand> updateFields, CancellationToken token)
            {
                var updateFieldIds = updateFields.Select(u => u.Id).ToList();

                return(!await requirementDefinitionValidator.AnyExcludedFieldsIsInUseAsync(requirementDefinitionId, updateFieldIds, token));
            }
        }
        /// <summary>
        /// Create an instance of AuthManager
        /// </summary>
        /// <param name="database"></param>
        /// <param name="authTokenDurationDays">How long new <see cref="AuthToken"/> instances are valid for</param>
        /// <param name="resetCodeLength">How many digits should a reset code be</param>
        /// <param name="resetTokenDurationMinutes">How long new reset codes are valid for</param>
        /// <param name="accountTableName">Table name of the account table (default is "account")</param>
        /// <param name="userTableName">Table name of the user table (default is "user")</param>
        /// <param name="userTableIdFieldName">Field name of the id field on the user table (default is "id")</param>
        /// <param name="userTableUsernameFieldName">Field name of the username field on the user table (default is "username")</param>
        /// <param name="userTableEmailFieldName">Field name of the email field on the user table (default is "email")</param>
        /// <param name="userTableEmailVerifiedAtFieldName">Field name of the email verified at field on the user table (default is "email_verified_at")</param>
        /// <param name="userTablePhoneFieldName">Field name of the phone field on the user table (default is "phone")</param>
        /// <param name="userTablePhoneVerifiedAtFieldName">Field name of the phone verified at field on the user table (default is "phone_verified_at")</param>
        /// <param name="userTableSaltFieldName">Field name of the salt field on the user table (default is "salt")</param>
        /// <param name="userTablePasswordHashFieldName">Field name of the password hash field on the user table (default is "password_hash")</param>
        /// <param name="userTableFirstNameFieldName">Field name of the first name field on the user table (default is "first_name")</param>
        /// <param name="userTableLastNameFieldName">Field name of the last name field on the user table (default is "last_name")</param>
        /// <param name="userTableResetCodeFieldName">Field name of the reset code field on the user table (default is "reset_code")</param>
        /// <param name="userTableResetCodeExpiresAtFieldName">Field name of the reset code expires at field on the user table (default is "reset_code_expires_at")</param>
        /// <param name="userTableAccountIdFieldName">Field name of the account id field on the user table (default is "account_id")</param>
        /// <param name="userTableRoleFieldName">Field name of the role field on the user table (default is "role")</param>
        /// <param name="authTokenTableName">Table name of the auth token table (default is "auth_token")</param>
        /// <param name="authTokenIdFieldName">Field name of the id field on the auth token table (default is "id")</param>
        /// <param name="authTokenTableUserIdFieldName">Field name of the user id field on the auth token table (default is "user_id")</param>
        /// <param name="authTokenTableExpiresAtFieldName">Field name of the expires at field on the auth token table (default is "expires_at")</param>
        /// <param name="defaultRole">Default value for the role field on a new user</param>
        /// <param name="onEmailVerify">Callback when <see cref="AuthManager.VerifyAsync(Dict, string, string, Func{string, int, Task})"/> is called with an email address</param>
        /// <param name="onPhoneVerify">Callback when <see cref="AuthManager.VerifyAsync(Dict, string, string, Func{string, int, Task})"/> is called with a phone number</param>
        /// <param name="onRegister">Callback when <see cref="AuthManager.RegisterAsync(dynamic, Dict)"/> is called</param>
        /// <param name="onForgotPassword">Callback when <see cref="AuthManager.ForgotPasswordAsync(string)"/> is called</param>
        public AuthManager(
            IDatabase database,
            int authTokenDurationDays                   = 90,
            int resetCodeLength                         = 6,
            int resetTokenDurationMinutes               = 90,
            string accountTableName                     = "account",
            string userTableName                        = "user",
            string userTableIdFieldName                 = "id",
            string userTableUsernameFieldName           = "username",
            string userTableEmailFieldName              = "email",
            string userTableEmailVerifiedAtFieldName    = "email_verified_at",
            string userTablePhoneFieldName              = "phone",
            string userTablePhoneVerifiedAtFieldName    = "phone_verified_at",
            string userTableSaltFieldName               = "salt",
            string userTablePasswordHashFieldName       = "password_hash",
            string userTableFirstNameFieldName          = "first_name",
            string userTableLastNameFieldName           = "last_name",
            string userTableResetCodeFieldName          = "reset_code",
            string userTableResetCodeExpiresAtFieldName = "reset_code_expires_at",
            string userTableAccountIdFieldName          = "account_id",
            string userTableRoleFieldName               = "role",
            string authTokenTableName                   = "auth_token",
            string authTokenIdFieldName                 = "id",
            string authTokenTableUserIdFieldName        = "user_id",
            string authTokenTableExpiresAtFieldName     = "expires_at",
            string defaultRole = null,
            Func <string, int, Task> onEmailVerify = null,
            Func <string, int, Task> onPhoneVerify = null,
            Func <Dict, Task> onRegister           = null,
            Func <Dict, Task> onForgotPassword     = null,
            Action <Version> onCheckVersion        = null
            )
        {
            this.database = database;

            this.authTokenDurationDays     = authTokenDurationDays;
            this.resetCodeLength           = resetCodeLength;
            this.resetTokenDurationMinutes = resetTokenDurationMinutes;

            this.accountTableName = accountTableName;

            this.userTableName                        = userTableName;
            this.userTableIdFieldName                 = userTableIdFieldName;
            this.userTableUsernameFieldName           = userTableUsernameFieldName;
            this.userTableEmailFieldName              = userTableEmailFieldName;
            this.userTableEmailVerifiedAtFieldName    = userTableEmailVerifiedAtFieldName;
            this.userTablePhoneFieldName              = userTablePhoneFieldName;
            this.userTablePhoneVerifiedAtFieldName    = userTablePhoneVerifiedAtFieldName;
            this.userTableSaltFieldName               = userTableSaltFieldName;
            this.userTablePasswordHashFieldName       = userTablePasswordHashFieldName;
            this.userTableFirstNameFieldName          = userTableFirstNameFieldName;
            this.userTableLastNameFieldName           = userTableLastNameFieldName;
            this.userTableResetCodeFieldName          = userTableResetCodeFieldName;
            this.userTableResetCodeExpiresAtFieldName = userTableResetCodeExpiresAtFieldName;
            this.userTableAccountIdFieldName          = userTableAccountIdFieldName;
            this.userTableRoleFieldName               = userTableRoleFieldName;

            this.authTokenTableName               = authTokenTableName;
            this.authTokenIdFieldName             = authTokenIdFieldName;
            this.authTokenTableUserIdFieldName    = authTokenTableUserIdFieldName;
            this.authTokenTableExpiresAtFieldName = authTokenTableExpiresAtFieldName;

            this.defaultRole = defaultRole;

            this.onEmailVerify    = onEmailVerify;
            this.onPhoneVerify    = onPhoneVerify;
            this.onRegister       = onRegister;
            this.onForgotPassword = onForgotPassword;
            this.onCheckVersion   = onCheckVersion;

            this.usernameFieldValidator = new GenericFieldValidator(this.userTableUsernameFieldName, @"^[_A-z0-9\-\.]{3,25}$", allowNull: false, forceLowerCase: true, includeValueInError: true);
            this.passwordFieldValidator = new GenericFieldValidator("password", "^.{6,255}$", allowNull: false, forceLowerCase: false, includeValueInError: false);
            this.nameFieldValidator     = new NameFieldValidator(this.userTableLastNameFieldName, allowNull: false, maxLength: 25);
            this.emailFieldValidator    = new EmailFieldValidator(this.userTableEmailFieldName, allowNull: true);
            this.phoneFieldValidator    = new PhoneFieldValidator(this.userTableEmailFieldName, allowNull: false);
        }
Example #21
0
 protected void Init(string Name, int Size, int Number, FieldLength Length, FieldFormat Format, IFieldFormatter Formatter, IFieldValidator Validator, IFieldParser Parser)
 {
     this.Name      = Name;
     this.Size      = Size;
     this.Number    = Number;
     this.Length    = Length;
     this.Format    = Format;
     this.Formatter = Formatter;
     this.Validator = Validator;
     this.Parser    = Parser;
     this.Parent    = null;
     this.Content   = null;
     this.Subfields = new SortedList <int, IField>();
 }
 private void InitializeFieldValidators(IMetaEntity metaEntity)
 {
     IFieldValidator fieldValidator = GetFieldValidator <string>(nameof(IMetaEntity.InterfaceName));
 }
 public SchemaValidator(IFieldValidator fieldValidator)
 {
     FieldValidator = fieldValidator;
 }
 protected BaseValidatorTests(IFieldValidator fieldValidator)
 {
     FieldValidator = fieldValidator;
     ValidValues    = new List <string>();
     InvalidValues  = new List <string>();
 }
Example #25
0
 public FileImporter(IFieldValidator fieldValidator, ITransactionStore transactionStore)
 {
     _fieldValidator = fieldValidator;
     _transactionStore = transactionStore;
 }
Example #26
0
 public PollValidator(IFieldValidator fieldValidator)
 {
     FieldValidator = fieldValidator;
 }
 private bool IsCorrectable(IRowStream row, FieldDescription field,
     string fieldValue, bool isValidated,
     ValidateStatement vs, IFieldValidator validator)
 {
     if (vs.AutoCorrect)
     {
         string newValue = validator.Correct(fieldValue);
         if (!string.IsNullOrEmpty(newValue))
         {
             XmlDocument xmldoc = new XmlDocument();
             xmldoc.LoadXml(newValue);
             newValue = xmldoc.DocumentElement.InnerText;
             if (AutoCorrect != null)
             {
                 AutoCorrectEventArgs args = new AutoCorrectEventArgs(row, ValidatorType.Field, field.Name, fieldValue, newValue);
                 if (AutoCorrect != null) AutoCorrect(this, args);
             }
             isValidated = false;
         }
         else
         {
             ErrorCapturedEventArgs args = new ErrorCapturedEventArgs(row, ValidatorType.Field, vs.ErrorType, field.Name, validator.ToString(vs.Description));
             if (ErrorCaptured != null) ErrorCaptured(this, args);
         }
     }
     else
     {
         ErrorCapturedEventArgs args = new ErrorCapturedEventArgs(row, ValidatorType.Field, vs.ErrorType, field.Name, validator.ToString(vs.Description));
         if (ErrorCaptured != null) ErrorCaptured(this, args);
     }
     return isValidated;
 }
Example #28
0
 public void Add(IFieldValidator fv)
 {
     this.Constraints.Add( fv);
 }
Example #29
0
 /// <summary>
 /// Create a Field descriptor.
 /// </summary>
 /// <param name="lengthFormatter">
 /// The length formatter.
 /// </param>
 /// <param name="fieldValidator">
 /// The field validator.
 /// </param>
 /// <param name="formatter">
 /// The formatter.
 /// </param>
 /// <returns>
 /// Field descriptor
 /// </returns>
 public static IFieldDescriptor Create(ILengthFormatter lengthFormatter, IFieldValidator fieldValidator, IFormatter formatter)
 {
     return(new FieldDescriptor(lengthFormatter, fieldValidator, formatter, null));
 }
Example #30
0
 public void Add(IFieldValidator fv)
 {
     this.Constraints.Add(fv);
 }
Example #31
0
 ///<summary>
 ///  Create an ASCII fixed length field descriptor
 ///</summary>
 ///<param name = "fieldNumber">Field number</param>
 ///<param name = "packedLength">The packed length of the field.  For BCD fields, this is half the size of the field you want</param>
 ///<param name = "validator">Validator to use on the field</param>
 ///<returns>field</returns>
 public static IField AsciiFixed(int fieldNumber, int packedLength, IFieldValidator validator)
 {
     return(new Field(fieldNumber, FieldDescriptor.AsciiFixed(packedLength, validator)));
 }
        /// <summary>
        /// Create an instance of AuthManager
        /// </summary>
        /// <param name="database"></param>
        /// <param name="authTokenDurationDays">How long new <see cref="AuthToken"/> instances are valid for</param>
        /// <param name="resetCodeLength">How many digits should a reset code be</param>
        /// <param name="resetTokenDurationMinutes">How long new reset codes are valid for</param>
        /// <param name="accountTableName">Table name of the account table (default is "account")</param>
        /// <param name="accountTableIdFieldName">Field name of the id field on the account table (default is "id")</param>
        /// <param name="accountTableShareCodeFieldName">Field name of the share code field on the account table (default is "share_code")</param>
        /// <param name="userTableName">Table name of the user table (default is "user")</param>
        /// <param name="userTableIdFieldName">Field name of the id field on the user table (default is "id")</param>
        /// <param name="userTableUsernameFieldName">Field name of the username field on the user table (default is "username")</param>
        /// <param name="userTableEmailFieldName">Field name of the email field on the user table (default is "email")</param>
        /// <param name="userTableEmailVerifiedAtFieldName">Field name of the email verified at field on the user table (default is "email_verified_at")</param>
        /// <param name="userTablePhoneFieldName">Field name of the phone field on the user table (default is "phone")</param>
        /// <param name="userTablePhoneVerifiedAtFieldName">Field name of the phone verified at field on the user table (default is "phone_verified_at")</param>
        /// <param name="userTableSaltFieldName">Field name of the salt field on the user table (default is "salt")</param>
        /// <param name="userTablePasswordHashFieldName">Field name of the password hash field on the user table (default is "password_hash")</param>
        /// <param name="userTableFirstNameFieldName">Field name of the first name field on the user table (default is "first_name")</param>
        /// <param name="userTableLastNameFieldName">Field name of the last name field on the user table (default is "last_name")</param>
        /// <param name="userTableResetCodeFieldName">Field name of the reset code field on the user table (default is "reset_code")</param>
        /// <param name="userTableResetCodeExpiresAtFieldName">Field name of the reset code expires at field on the user table (default is "reset_code_expires_at")</param>
        /// <param name="userTableAccountIdFieldName">Field name of the account id field on the user table (default is "account_id")</param>
        /// <param name="userTableRoleFieldName">Field name of the role field on the user table (default is "role")</param>
        /// <param name="defaultRole">Default value for the role field on a new user</param>
        /// <param name="getExtraAccountInfo"></param>
        /// <param name="getExtraUserInfo"></param>
        /// <param name="onEmailVerify">Callback when <see cref="AuthManager.VerifyAsync(Dict, string, string, Func{string, int, Task})"/> is called with an email address</param>
        /// <param name="onPhoneVerify">Callback when <see cref="AuthManager.VerifyAsync(Dict, string, string, Func{string, int, Task})"/> is called with a phone number</param>
        /// <param name="onRegisterAccount">Callback when a new account is registered</param>
        /// <param name="onRegisterUser">Callback when a new user is registered</param>
        /// <param name="onForgotPassword">Callback when a forgot password request is made</param>
        /// <param name="onForgotUsername">Callback when a forgot username request is made</param>
        /// <param name="onCheckVersion"></param>
        public AuthManager(
            IDatabase database,
            int authTokenDurationDays                   = 90,
            int resetCodeLength                         = 6,
            int resetTokenDurationMinutes               = 90,
            string accountTableName                     = "account",
            string accountTableIdFieldName              = "id",
            string accountTableShareCodeFieldName       = "share_code",
            string userTableName                        = "user",
            string userTableIdFieldName                 = "id",
            string userTableUsernameFieldName           = "username",
            string userTableEmailFieldName              = "email",
            string userTableEmailVerifiedAtFieldName    = "email_verified_at",
            string userTablePhoneFieldName              = "phone",
            string userTablePhoneVerifiedAtFieldName    = "phone_verified_at",
            string userTableSaltFieldName               = "salt",
            string userTablePasswordHashFieldName       = "password_hash",
            string userTableFirstNameFieldName          = "first_name",
            string userTableLastNameFieldName           = "last_name",
            string userTableResetCodeFieldName          = "reset_code",
            string userTableResetCodeExpiresAtFieldName = "reset_code_expires_at",
            string userTableAccountIdFieldName          = "account_id",
            string userTableRoleFieldName               = "role",
            string defaultRole = null,
            Func <Dict, Dict> getExtraAccountInfo  = null,
            Func <Dict, Dict> getExtraUserInfo     = null,
            Func <string, int, Task> onEmailVerify = null,
            Func <string, int, Task> onPhoneVerify = null,
            Func <Dict, Task> onRegisterAccount    = null,
            Func <Dict, Task> onRegisterUser       = null,
            Func <Dict, Task> onForgotPassword     = null,
            Func <Dict, Task> onForgotUsername     = null,
            Action <Version> onCheckVersion        = null
            )
        {
            this.database = database;

            this.authTokenDurationDays     = authTokenDurationDays;
            this.resetCodeLength           = resetCodeLength;
            this.resetTokenDurationMinutes = resetTokenDurationMinutes;

            this.accountTableName               = accountTableName;
            this.accountTableIdFieldName        = accountTableIdFieldName;
            this.accountTableShareCodeFieldName = accountTableShareCodeFieldName;

            this.userTableName                        = userTableName;
            this.userTableIdFieldName                 = userTableIdFieldName;
            this.userTableUsernameFieldName           = userTableUsernameFieldName;
            this.userTableEmailFieldName              = userTableEmailFieldName;
            this.userTableEmailVerifiedAtFieldName    = userTableEmailVerifiedAtFieldName;
            this.userTablePhoneFieldName              = userTablePhoneFieldName;
            this.userTablePhoneVerifiedAtFieldName    = userTablePhoneVerifiedAtFieldName;
            this.userTableSaltFieldName               = userTableSaltFieldName;
            this.userTablePasswordHashFieldName       = userTablePasswordHashFieldName;
            this.userTableFirstNameFieldName          = userTableFirstNameFieldName;
            this.userTableLastNameFieldName           = userTableLastNameFieldName;
            this.userTableResetCodeFieldName          = userTableResetCodeFieldName;
            this.userTableResetCodeExpiresAtFieldName = userTableResetCodeExpiresAtFieldName;
            this.userTableAccountIdFieldName          = userTableAccountIdFieldName;
            this.userTableRoleFieldName               = userTableRoleFieldName;

            this.defaultRole = defaultRole;

            this.getExtraAccountInfo = getExtraAccountInfo;
            this.getExtraUserInfo    = getExtraUserInfo;
            this.onEmailVerify       = onEmailVerify;
            this.onPhoneVerify       = onPhoneVerify;
            this.onRegisterAccount   = onRegisterAccount;
            this.onRegisterUser      = onRegisterUser;
            this.onForgotPassword    = onForgotPassword;
            this.onForgotUsername    = onForgotUsername;
            this.onCheckVersion      = onCheckVersion;

            this.usernameFieldValidator = new GenericFieldValidator(this.userTableUsernameFieldName, @"^[_A-z0-9\-\.\@\+]{3,25}$", allowNull: false, forceLowerCase: true, includeValueInError: true);
            this.passwordFieldValidator = new GenericFieldValidator("password", "^.{6,255}$", allowNull: false, forceLowerCase: false, includeValueInError: false);
            this.nameFieldValidator     = new TextFieldValidator(this.userTableLastNameFieldName, allowNull: false, maxLength: 25);
            this.emailFieldValidator    = new EmailFieldValidator(this.userTableEmailFieldName, allowNull: true);
            this.phoneFieldValidator    = new PhoneFieldValidator(this.userTablePhoneFieldName, allowNull: false);

            this.userRefTokenAuthenticator = new UserRefTokenAuthenticator(
                database,
                userTableName: this.userTableName,
                userTableUsernameFieldName: this.userTableUsernameFieldName,
                userTableAccountIdFieldName: this.userTableAccountIdFieldName,
                userTableRoleFieldName: this.userTableRoleFieldName
                );

            this.shareCodeAuthenticator = new ShareCodeAuthenticator(
                database,
                accountTableName: this.accountTableName,
                accountTableIdFieldName: this.accountTableIdFieldName,
                accountTableShareCodeFieldName: this.accountTableShareCodeFieldName
                );

            this.authenticatorByType = new Dictionary <string, IAuthenticator> {
                [UserRefTokenAuthenticator.AUTH_TYPE] = this.userRefTokenAuthenticator,
                [ShareCodeAuthenticator.AUTH_TYPE]    = this.shareCodeAuthenticator
            };
        }
Example #33
0
 public IField Configure(string Name, int Size, int Number, FieldLength Length, FieldFormat Format, IFieldFormatter Formatter, IFieldValidator Validator, IFieldParser Parser)
 {
     this.Init(Name, Size, Number, Length, Format, Formatter, Validator, Parser);
     return(this);
 }
Example #34
0
 /// <summary>
 /// Creates new instance with <paramref name="fieldValidator"/> to validating fields.
 /// </summary>
 /// <param name="fieldValidator">Field validator.</param>
 public ModelValidator(IFieldValidator fieldValidator)
 {
     Ensure.NotNull(fieldValidator, "fieldValidator");
     FieldValidator = fieldValidator;
 }