Exemplo n.º 1
0
        public async Task ShouldBeReturnedAuthenticationResultWithSuccessAndCreatedNewAuthor()
        {
            var salt      = SecurePasswordHasher.CreateSalt(8);
            var newAuthor = new AuthorBuilder()
                            .WithFirstName(_faker.Person.FirstName)
                            .WithLastName(_faker.Person.LastName)
                            .WithUsername(_faker.Person.UserName)
                            .WithEmail(_faker.Person.Email)
                            .WithPassword(SecurePasswordHasher.GenerateHash("joao123", salt))
                            .WithSalt(salt)
                            .Build();

            var authenticationResult = await _authenticationService.RegisterAsync(newAuthor);

            authenticationResult.Should().BeOfType <AuthenticationResult>();
            authenticationResult.Success.Should().BeTrue();
            authenticationResult.Errors.Should().BeNull();
            authenticationResult.Token.Should().NotBeNullOrEmpty();

            _output.WriteLine($"Success: {authenticationResult.Success} | Token: {authenticationResult.Token}");

            // Verificando se o autor foi inserido no banco de dados
            var insertedAuthor = await _unitOfWork.Authors
                                 .FindByConditionAsync(a => a.Id == newAuthor.Id)
                                 .Result.SingleOrDefaultAsync();

            insertedAuthor.Should().NotBeNull();
            insertedAuthor.FirstName.Should().Be(newAuthor.FirstName);
            insertedAuthor.Username.Should().Be(newAuthor.Username);
            insertedAuthor.Email.Should().Be(newAuthor.Email);
        }
Exemplo n.º 2
0
        public void Configure(EntityTypeBuilder <Author> builder)
        {
            builder.Property(x => x.Id).ValueGeneratedOnAdd();
            builder.Property(x => x.Bio).IsRequired(false);
            builder.Property(x => x.Avatar).IsRequired(false);

            var salt = SecurePasswordHasher.CreateSalt(8);

            builder.HasData
            (
                new Author
            {
                Id             = Guid.Parse("4f29ee19-ea4b-421d-a796-c2ee446becd2"),
                FirstName      = "Administrador",
                LastName       = "Master",
                Username       = "******",
                Password       = SecurePasswordHasher.GenerateHash("Admin2020#", salt),
                Salt           = salt,
                Email          = "*****@*****.**",
                ConfirmedEmail = true,
                Deactivated    = false,
                Deleted        = false,
            }
            );
        }
        public async Task <AuthenticationResult> ResetPasswordAsync(string email, string newPassword)
        {
            var existingAuthor = await _unitOfWork.Authors
                                 .FindByConditionAsync(a => a.Email == email)
                                 .Result.SingleOrDefaultAsync();

            if (existingAuthor == null)
            {
                return(new AuthenticationResult
                {
                    Success = false,
                    Errors = new[] { "Email does not exist" }
                });
            }

            if (existingAuthor.Deleted)
            {
                return(new AuthenticationResult
                {
                    Success = false,
                    Errors = new[] { "Email does not exist" }
                });
            }

            existingAuthor.Password = SecurePasswordHasher
                                      .GenerateHash(newPassword, existingAuthor.Salt);

            await _unitOfWork.Authors.UpdateAuthorAsync(existingAuthor);

            int updated = await _unitOfWork.Commit();

            if (updated <= 0)
            {
                return(new AuthenticationResult
                {
                    Success = false,
                    Errors = new[] { "An error occurred when try updated author" }
                });
            }

            return(new AuthenticationResult
            {
                Success = true
            });
        }
Exemplo n.º 4
0
        public async Task ShouldBeReturnedAuthenticationResultWithFailedIfEmailAlreadyExists()
        {
            var alreadyEmail = "*****@*****.**";
            var salt         = SecurePasswordHasher.CreateSalt(8);
            var newAuthor    = new AuthorBuilder()
                               .WithFirstName(_faker.Person.FirstName)
                               .WithLastName(_faker.Person.LastName)
                               .WithUsername(_faker.Person.UserName)
                               .WithEmail(alreadyEmail)
                               .WithPassword(SecurePasswordHasher.GenerateHash("joao123", salt))
                               .WithSalt(salt)
                               .Build();

            var authenticationResult = await _authenticationService.RegisterAsync(newAuthor);

            authenticationResult.Should().BeOfType <AuthenticationResult>();
            authenticationResult.Success.Should().BeFalse();
            authenticationResult.Token.Should().BeNull();
            authenticationResult.Errors.Should().SatisfyRespectively(
                err => err.Should().Be("Author with this email already exists"));
        }
        public async Task <AuthenticationResult> RegisterAsync(Author author)
        {
            var existingAuthor = await _unitOfWork.Authors
                                 .FindByConditionAsync(a => a.Email == author.Email)
                                 .Result.SingleOrDefaultAsync();

            if (existingAuthor != null)
            {
                return(new AuthenticationResult
                {
                    Success = false,
                    Errors = new[] { "Author with this email already exists" }
                });
            }

            string salt           = SecurePasswordHasher.CreateSalt(8);
            string hashedPassword = SecurePasswordHasher.GenerateHash(author.Password, salt);

            author.Id       = Guid.NewGuid();
            author.Password = hashedPassword;
            author.Salt     = salt;

            await _unitOfWork.Authors.CreateAuthorAsync(author);

            var createdAuthor = await _unitOfWork.Commit();

            if (createdAuthor <= 0)
            {
                return(new AuthenticationResult
                {
                    Success = false,
                    Errors = new[] { "An error occurred when try inserted new author" }
                });
            }

            return(await TokenUtils.GenerateAuthenticationResultForUserAsync(author, _jwtOptions));
        }
Exemplo n.º 6
0
        public async Task <bool> CreateAuthorAsync(Author author)
        {
            var newAuthor = await _unitOfWork.Authors
                            .FindByConditionAsync(a => a.Email == author.Email ||
                                                  a.Username == author.Username)
                            .Result.SingleOrDefaultAsync();

            if (newAuthor != null)
            {
                return(false);
            }

            string salt           = SecurePasswordHasher.CreateSalt(8);
            string hashedPassword = SecurePasswordHasher.GenerateHash(author.Password, salt);

            author.Password = hashedPassword;
            author.Salt     = salt;

            await _unitOfWork.Authors.CreateAsync(author);

            var created = await _unitOfWork.Commit();

            return(created > 0);
        }
        public static DataContext SeedTestData(this DataContext dataContext)
        {
            #region Authors

            var salt    = SecurePasswordHasher.CreateSalt(8);
            var authors = new List <Author>
            {
                new AuthorBuilder()
                .WithId(Guid.Parse("d4182477-0823-4908-be1d-af808e594306"))
                .WithFirstName("João")
                .WithEmail("*****@*****.**")
                .WithPassword(SecurePasswordHasher.GenerateHash("joao123", salt))
                .WithSalt(salt)
                .Build(),
                new AuthorBuilder()
                .WithId(Guid.Parse("9ab3d110-71e1-418f-86eb-519146e7d702"))
                .WithFirstName("Maria")
                .WithEmail("*****@*****.**")
                .WithPassword(SecurePasswordHasher.GenerateHash("maria123", salt))
                .WithSalt(salt)
                .Build(),
            };

            dataContext.Authors.AddRange(authors);

            #endregion

            #region Posts

            var posts = new List <Post>
            {
                new Post
                {
                    Id          = Guid.Parse("b65afc54-d766-4377-8c89-22662582174e"),
                    Title       = "Post 1",
                    Content     = "First post content",
                    Attachments = "post1img1.jpg,post1img2.jpg",
                    AuthorId    = authors[0].Id
                },
                new Post
                {
                    Id          = Guid.Parse("a06ba60c-c999-4de3-aa23-4f0c13bd71ad"),
                    Title       = "Post 2",
                    Content     = "Second post content",
                    Attachments = "post2img1.jpg,post2img2.jpg",
                    AuthorId    = authors[1].Id
                }
            };

            dataContext.Posts.AddRange(posts);

            #endregion

            #region Tags

            var tags = new List <Tag>
            {
                new Tag
                {
                    Id       = Guid.Parse("5d5e9a28-7c3e-4c2a-8098-b866eab33e61"),
                    Name     = "Tag_1",
                    AuthorId = authors[0].Id
                },
                new Tag
                {
                    Id       = Guid.Parse("d94e6e00-96d0-4fc7-b621-c7746705b471"),
                    Name     = "Tag_2",
                    AuthorId = authors[1].Id
                },
            };

            dataContext.Tags.AddRange(tags);

            #endregion

            dataContext.SaveChanges();

            foreach (var entity in dataContext.ChangeTracker.Entries())
            {
                entity.State = EntityState.Detached;
            }

            return(dataContext);
        }