Пример #1
0
        public bool Create(AccountCreateApiModel apiModel, int createdUser)
        {
            var validator = _accountValidator.Validate(apiModel);

            if (validator.IsValid)
            {
                return(_accountRepository.Create(apiModel, createdUser));
            }
            return(false);
        }
Пример #2
0
        public async Task Validate_TwoAccounts(bool valid, string email1, string email2)
        {
            using (var provider = await CreateProvider())
            {
                var access   = provider.GetRequiredService <IContextLock>();
                var context  = provider.GetRequiredService <IContext>();
                var accounts = provider.GetRequiredService <IAccountRepository>();
                IValidator <Account> validator = new AccountValidator(accounts);

                using (var handle = await access.Write())
                {
                    var one = new Account {
                        Email = new EmailAddress(email1)
                    };
                    context.Add(one);
                    await handle.Finish();
                }

                using (await access.Read())
                {
                    var two = new Account {
                        Email = new EmailAddress(email2)
                    };
                    var target = new ValidationTarget <Account>(two);
                    validator.Validate(target);
                    Assert.Equal(valid, !target.GetResult().HasErrors);
                }
            }
        }
Пример #3
0
        public override IEnumerable <BusinessRule> Validate()
        {
            AccountValidator validator = new AccountValidator();
            ValidationResult results   = validator.Validate(this);

            foreach (var item in results.Errors)
            {
                yield return(new BusinessRule(item.PropertyName, item.ErrorMessage));
            }
        }
Пример #4
0
        public void Validate(Account account)
        {
            var result = _validator.Validate(account);

            if (!result.IsValid)
            {
                var errorMessage = JsonConvert.SerializeObject(result.Errors);
                throw new ValidateException(errorMessage);
            }
        }
Пример #5
0
        /// <inheritdoc/>
        public Account Handle(Account entity)
        {
            var result = _accountValidator.Validate(entity);

            if (!result.IsValid)
            {
                return(null);
            }

            return(entity);
        }
        public override RepositoryModifyResult <Account> Update(int id, Account entity)
        {
            var validator = new AccountValidator(entity);

            validator.Validate();
            if (!validator.IsValid)
            {
                return(new RepositoryModifyResult <Account>(validator.Errors));
            }
            return(base.Update(id, entity));
        }
        public (bool isValid, IEnumerable <ValidationResult> errors) Validate()
        {
            var validator = new AccountValidator();
            var result    = validator.Validate(this);

            if (result.IsValid)
            {
                return(true, null);
            }

            return(false, result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new [] { item.PropertyName })));
        }
        /// <summary>
        /// Insert a new Account
        /// </summary>
        public Account Insert(Account account)
        {
            // hash the given password
            account.Password = GetPasswordHash(account.Password);

            // validate the new account
            var validator = new AccountValidator(m_accounts);
            var validationresults = validator.Validate(account, ruleSet: "default,Insert");

            if (!validationresults.IsValid)
                throw new ValidationException(validationresults.Errors);

            return m_accounts.Insert(account);
        }
Пример #9
0
        public void CustomerId_Is_One_Is_Valid()
        {
            // Arrange
            var validator = new AccountValidator <Account>();
            var account   = new Account {
                CustomerId = 1
            };

            // Act
            var result = validator.Validate(account);

            // Assert
            Assert.False(result.Errors.Any(e => e.ErrorMessage == "CustomerId is required"));
        }
Пример #10
0
        private void CreateAccount()
        {
            var results = AccountValidator.Validate(ViewModel);

            if (!results.IsValid)
            {
                Android.Support.V7.App.AlertDialog         alertDialog = null;
                Android.Support.V7.App.AlertDialog.Builder builder     = new Android.Support.V7.App.AlertDialog.Builder(this)
                                                                         .SetTitle("Invalid Model")
                                                                         .SetMessage("- " + string.Join(" \n -", results.Errors.Select(x => x.ErrorMessage).ToList()))
                                                                         .SetPositiveButton("Ok", (object s, Android.Content.DialogClickEventArgs dialogClickEventArgs) =>
                {
                    alertDialog.Hide();
                });

                alertDialog = builder.Create();
                alertDialog.Show();
            }
            else
            {
                try
                {
                    var db = new SQLiteConnection(DBPath);

                    var insert = db.Insert(new Account()
                    {
                        Password    = ViewModel.Password,
                        UserName    = ViewModel.UserName,
                        FirstName   = ViewModel.FirstName,
                        LastName    = ViewModel.LastName,
                        PhoneNumber = ViewModel.PhoneNumber,
                        ServiceDate = ViewModel.ServiceStartDate.Value
                    });

                    if (insert == 1)
                    {
                        var intent = new Intent(this, typeof(ConfirmationActivity));
                        StartActivity(intent);
                    }
                    else
                    {
                        //TODO: Let the user know the database wasn't updated
                    }
                }
                catch (Exception ex)
                {
                    //TODO: Let the user know something went wrong
                }
            }
        }
Пример #11
0
        public void CustomerId_Is_Zero_Generates_Error()
        {
            // Arrange
            var validator = new AccountValidator <Account>();
            var account   = new Account {
                CustomerId = 0
            };

            // Act
            var result = validator.Validate(account);

            // Assert
            Assert.True(result.Errors.Any(e => e.ErrorMessage == "CustomerId is required"));
        }
Пример #12
0
        public OpResult UpdateAccount(string userName, AccountUpdateRequest dto)
        {
            var account = _repo.GetFirst <Account>(a => a.UserName == userName, null, "Profiles");

            if (account == null)
            {
                return(OpResult.FailureResult("Account not found"));
            }

            var profile = account.GetProfile();

            if (profile == null)
            {
                if (!(string.IsNullOrEmpty(dto.FirstName) && string.IsNullOrWhiteSpace(dto.LastName)))
                {
                    profile = new Profile();
                    account.Profiles.Add(profile);
                }
            }
            if (profile != null)
            {
                profile.FirstName = dto.FirstName;
                profile.LastName  = dto.LastName;
            }

            if (account.Email != dto.Email)
            {
                var anotherAccount = _repo.GetFirst <Account>(a => a.ID != dto.Id && a.Email == dto.Email, null, "Profiles");
                if (anotherAccount != null)
                {
                    return(OpResult.FailureResult("eMail already exists"));
                }

                account.Email = dto.Email;
            }

            AccountValidator validator = new AccountValidator();
            var validationResult       = validator.Validate(account);

            if (!validationResult.IsValid)
            {
                return(OpResult.FailureResult(validationResult.Errors.Select(e => e.ErrorMessage).ToList()));
            }

            _repo.Update <Account>(account);
            _repo.Save();

            return(OpResult.SuccessResult());
        }
Пример #13
0
        private bool IsValidAccountPassword()
        {
            BCryptHashGenerator bCryptHashGenerator = new BCryptHashGenerator();
            string hashedPassword = bCryptHashGenerator.GenerateHashedString(accountCurrent.Password, accountReceived.Salt);

            accountCurrent.Password = hashedPassword;
            _password = hashedPassword;
            AccountValidator          accountValidator     = new AccountValidator(accountReceived);
            ValidationResult          dataValidationResult = accountValidator.Validate(accountCurrent);
            IList <ValidationFailure> validationFailures   = dataValidationResult.Errors;
            UserFeedback userFeedback = new UserFeedback(FormGrid, validationFailures);

            userFeedback.ShowFeedback();
            return(dataValidationResult.IsValid);
        }
Пример #14
0
        public async Task Validate_OneAccount()
        {
            using (var provider = await CreateProvider())
            {
                var access   = provider.GetRequiredService <IContextLock>();
                var accounts = provider.GetRequiredService <IAccountRepository>();
                IValidator <Account> validator = new AccountValidator(accounts);
                var account = new Account();

                using (await access.Read())
                {
                    var target = new ValidationTarget <Account>(account);
                    validator.Validate(target);
                    Assert.False(target.GetResult().HasErrors);
                }
            }
        }
Пример #15
0
        //private RepositoryPlaceholder _repo = new RepositoryPlaceholder();

        public OpResult CreateAccount(AccountCreateRequest dto)
        {
            Account account = new Account
            {
                UserName = dto.Username,
                Password = dto.Password,
                Email    = dto.Email,
                EmailVerificationCode = Guid.NewGuid().ToString("N")
            };

            AccountValidator validator = new AccountValidator();
            var validationResult       = validator.Validate(account);

            if (!validationResult.IsValid)
            {
                return(OpResult.FailureResult(validationResult.Errors.Select(e => e.ErrorMessage).ToList()));
            }

            var existingAccount = _repo.GetFirst <Account>(a => a.UserName == dto.Username || a.Email == dto.Email);

            if (existingAccount != null)
            {
                if (existingAccount.UserName == dto.Username)
                {
                    return(OpResult.FailureResult("username already exists"));
                }
                if (existingAccount.Email == dto.Email)
                {
                    return(OpResult.FailureResult("eMail already exists"));
                }
            }

            var salt       = EncryptionUtil.GenerateRandomSaltString();
            var hashedPass = EncryptionUtil.GeneratePBKDF2Hash(dto.Password, salt);

            account.PasswordHash = hashedPass;
            account.PasswordSalt = salt;

            _repo.Create <Account>(account);
            _repo.Save();

            _emailService.SendEmail(_configService.GetFromEmailAddress(), _configService.GetFromEmailName(),
                                    account.Email, "Verify Account", "Your verification code is " + account.EmailVerificationCode);

            return(OpResult.SuccessResult());
        }
Пример #16
0
        public ActionResult Login(LoginRegisterViewModel VM)
        {
            if (VM.Login.Name != null)
            {
                var vm = VM.Login;
                try
                {
                    AccountValidator validator = new AccountValidator(ModelState, citizensRepository, entityService);
                    validator.ModelStatePrefix = "Login.";
                    validator.Validate(vm);

                    if (validator.IsValid)
                    {
                        SessionHelper.SwitchStack = new Stack <EntityDom>();
                        Credentials credentials = createCredentials(vm);
                        //now we will delete old cookies associated with the users. They are not needed
                        deleteOldSessions(credentials.Username);

                        SessionHelper.Session = authService.Login(credentials, SessionHelper.ClientIP);
                        SessionHelper.SwitchStack.Push(new EntityDom(SessionHelper.LoggedCitizen.Entity));

                        return(RedirectToAction("Index", "Home"));
                    }
                    VM.Login    = vm;
                    VM.Register = new RegisterViewModel();
                    VM.Register.LoadSelectLists(countriesRepository, regionService);
                    return(View(VM));
                }
                catch (DbEntityValidationException e)
                {
                    var str = "";

                    foreach (var error in e.EntityValidationErrors)
                    {
                        str += string.Format("Name : {0}<br/>", error.Entry.Entity.GetType().Name);
                        foreach (var ee in error.ValidationErrors)
                        {
                            str += string.Format("{0} - {1}<br/>", ee.PropertyName, ee.ErrorMessage);
                        }
                        str += "<br/>";
                    }

                    str = string.Format("<html><body>{0}</body></html>", str);
                    return(Content(str));
                }
            }
            else
            {
                var vm = VM.Register;
                vm.LoadSelectLists(countriesRepository, regionService);
                AccountValidator validator = new AccountValidator(ModelState, citizensRepository, entityService);
                validator.ModelStatePrefix = "Register.";
                validator.Validate(vm);

                if (validator.IsValid)
                {
                    RegisterInfo info = new RegisterInfo()
                    {
                        Name       = vm.Name,
                        Password   = vm.Password,
                        CountryID  = vm.CountryID.Value,
                        RegionID   = vm.RegionID.Value,
                        Email      = vm.Email,
                        PlayerType = PlayerTypeEnum.Player
                    };

                    AddSuccess("Your account was created!");
                    authService.Register(info);

                    return(RedirectToAction("Login"));
                }
                VM.Register = vm;
                return(View(VM));
            }
        }
Пример #17
0
 public override IEnumerable<BusinessRule> Validate()
 {
     AccountValidator validator = new AccountValidator();
     ValidationResult results = validator.Validate(this);
     foreach (var item in results.Errors)
     {
         yield return new BusinessRule(item.PropertyName, item.ErrorMessage);
     }
 }