public void MethodShouldCallCreateUserMethodFromRepoOnce()
        {
            //Given
            var authHelper = new Mock <IAuthenticationHelper>();
            var userRepo   = new Mock <IUserRepository>();

            byte[] passwordHash;
            byte[] passwordSalt;

            //When
            userRepo.Setup(mr => mr.CreateUser(It.IsAny <AlarmSystem.Core.Entity.DB.User>()));
            authHelper.Setup(mr => mr.CreatePasswordHash(It.IsAny <string>(), out passwordHash, out passwordSalt));

            var userToCreate = new UserToCreate {
                Name     = "Tom",
                Email    = "*****@*****.**",
                Password = "******"
            };
            var userService = new UserService(userRepo.Object, authHelper.Object);

            userService.CreateUser(userToCreate);

            //Then
            userRepo.Verify(mr => mr.CreateUser(It.IsAny <AlarmSystem.Core.Entity.DB.User>()), Times.Once);
        }
        public async Task <ActionResult> PostRegistrationForm(UserRegistrationViewModel viewModel)
        {
            if (!viewModel.Password.Equals(viewModel.ConfirmPassword, System.StringComparison.Ordinal))
            {
                ModelState.AddModelError("ConfirmPassword", "The two passwords do not match.");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var user = new UserToCreate(viewModel.Email, viewModel.Password);
                    await userService.AddUserAsync(user);
                }
                catch (InvalidEmailException e)
                {
                    ModelState.AddModelError("Email", e.Message);
                }
                catch (InvalidPasswordException e)
                {
                    ModelState.AddModelError("Password", e.Message);
                }
            }

            if (ModelState.IsValid)
            {
                return(RedirectToAction(ActionNames.REGISTRATION_SUCCESS));
            }
            else
            {
                return(View(ViewNames.REGISTRATION_FORM, viewModel));
            }
        }
        public void WhenPasswordDoesNotContainAtLeast8NonWhitespaceCharactersThenInvalidPasswordExceptionIsThrown(string invalidPassword)
        {
            var invalidUser = new UserToCreate(VALID_EMAIL, invalidPassword);

            userValidationService.Invoking(s => s.ValidateUserToCreate(invalidUser))
            .Should().Throw <InvalidPasswordException>();
        }
        public void WhenEmailHasNoAtSymbolThenInvalidEmailExceptionIsThrown()
        {
            var invalidUser = new UserToCreate("not an email address", VALID_PASSWORD);

            userValidationService.Invoking(s => s.ValidateUserToCreate(invalidUser))
            .Should().Throw <InvalidEmailException>()
            .WithMessage("The email address is not valid.");
        }
        public void WhenEmailIsMissingThenInvalidEmailExceptionIsThrown(string missingEmail)
        {
            var invalidUser = new UserToCreate(missingEmail, VALID_PASSWORD);

            userValidationService.Invoking(s => s.ValidateUserToCreate(invalidUser))
            .Should().Throw <InvalidEmailException>()
            .WithMessage("The email address is required.");
        }
Beispiel #6
0
 public static UserModelData ToUserData(this UserToCreate userToCreate)
 => new UserModelData
 {
     Name     = userToCreate.Name,
     Email    = userToCreate.Email,
     Password = userToCreate.Password,
     Dateborn = userToCreate.Dateborn.ToDate(),
     Gender   = userToCreate.Gender.ToGender(),
     Admin    = userToCreate.Admin
 };
Beispiel #7
0
        public async Task <IActionResult> Register(UserToCreate userToCreate)
        {
            var user = _mapper.Map <User>(userToCreate);

            var result = await _userManager.CreateAsync(user, userToCreate.Password);

            if (result.Succeeded)
            {
                return(Ok());
            }

            return(BadRequest(result.Errors));
        }
        public async Task Setup()
        {
            mockUserValidationService = new Mock <IUserValidationService>();

            mockPasswordService = new Mock <IPasswordService>();
            mockPasswordService.Setup(s => s.SaltAndHashPassword(PASSWORD))
            .Returns(MOCK_HASH);

            mockAddUserProvider = new Mock <IAddUserProvider>();
            mockAddUserProvider.Setup(p => p.AddUserAsync(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Task.CompletedTask);

            var userService = new UserService(
                mockUserValidationService.Object,
                mockPasswordService.Object,
                mockAddUserProvider.Object);

            userToCreate = new UserToCreate(EMAIL, PASSWORD);
            await userService.AddUserAsync(userToCreate);
        }
Beispiel #9
0
 public void CreateUser(UserToCreate user)
 {
     if (user != null)
     {
         if (_userRepo.GetUserByEmail(user.Email) == null)
         {
             byte[] passwordHash;
             byte[] passwordSalt;
             _authHelper.CreatePasswordHash(user.Password, out passwordHash, out passwordSalt);
             var guid = Guid.NewGuid();
             _userRepo.CreateUser(new User {
                 UserId       = guid.ToString(),
                 Name         = user.Name,
                 Email        = user.Email,
                 PasswordHash = passwordHash,
                 PasswordSalt = passwordSalt
             });
         }
     }
     else
     {
         throw new InvalidDataException("User id cannot be empty or non existent! Please include a user id");
     }
 }
        public async Task <Json> PostCreate([FromBody] UserToCreate userSend, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfiguration tokenConfigurations)
        {
            var repositoy = UserRepository.GetInstance(_context);

            if (repositoy.EmailValidation(userSend.Email))
            {
                return(Json.Conflit("Este email está sendo utilizado por outro usuário", userSend));
            }

            var userValidate = userSend.ToValidate();

            if (userValidate.Erro)
            {
                return(Json.Conflit("Erro ao validar usuário, verifique os erros", userValidate.Erros));
            }

            var userCreate = await repositoy.Create(userSend.ToUserData());

            if (userCreate.Erro)
            {
                return(Json.Conflit("Falha ao criar usuário!", userCreate.Description));
            }

            var userLogin = UserToLogin.Create(userSend.Email, userSend.Password);

            var login = await Login(userLogin, signingConfigurations, tokenConfigurations);

            if (login == null)
            {
                return(Json.BadRequest("Falha ao criar usuário", userSend));
            }

            var userResponse = LoginToResponse.Create(login.User, login.Token);

            return(Json.Ok("Ususário criado com sucesso!", userResponse));
        }
Beispiel #11
0
 public static User ToValidate(this UserToCreate user)
 => User.Create(user.Name, user.Email, user.Password, user.Dateborn.ToDate(), user.Gender.ToGender());
Beispiel #12
0
 /// <inheritdoc />
 /// <exception cref="InvalidEmailException">Thrown if the user does not have a valid email address.</exception>
 /// <remarks>We do not attempt to enforce the full (very complicated) validity rules for email addresses,
 /// because a real application would send a message to confirm that the address exists.
 /// Instead, we simply reject addresses that are blank or contain no '@' symbol.</remarks>
 /// <exception cref="InvalidPasswordException">Thrown if the password is too weak.</exception>
 public void ValidateUserToCreate(UserToCreate user)
 {
     CheckEmailAddress(user.Email);
     CheckPassword(user.Password);
 }
Beispiel #13
0
 /// <inheritdoc/>
 /// <exception cref="InvalidEmailException">Thrown if the user's email address is invalid or already exists in the database.</exception>
 /// <exception cref="InvalidPasswordException">Thrown if the password is too weak.</exception>
 public async Task AddUserAsync(UserToCreate user)
 {
     userValidationService.ValidateUserToCreate(user);
     string hash = passwordService.SaltAndHashPassword(user.Password);
     await addUserProvider.AddUserAsync(user.Email, hash);
 }