public UsuarioRepositorioTeste()
        {
            var configServices = ServicesConfiguration.Configure();

            _memoryDb = configServices
                        .GetRequiredService <MatchDayAppContext>()
                        .SeedFakeData();

            _usuarioRepositorio = new UsuarioRepositorio(_memoryDb);
            _usuarioTest        = _memoryDb.Usuarios.First();

            string salt = SenhaHasherHelper.CriarSalt(8);

            _usuarioFake = new Faker <Usuario>()
                           .RuleFor(u => u.Nome, f => f.Person.FirstName)
                           .RuleFor(u => u.Sobrenome, f => f.Person.LastName)
                           .RuleFor(u => u.Email, f => f.Person.Email)
                           .RuleFor(u => u.Telefone, f => f.Person.Phone)
                           .RuleFor(u => u.Username, f => f.UniqueIndex + f.Person.UserName)
                           .RuleFor(u => u.Senha, f => SenhaHasherHelper.GerarHash(f.Internet.Password(), salt))
                           .RuleFor(u => u.Salt, salt)
                           .RuleFor(u => u.TipoUsuario, TipoUsuario.Jogador);

            _usuarioEsperado = new
            {
                Nome        = "Test",
                Sobrenome   = "One",
                Username    = "******",
                Email       = "*****@*****.**",
                Telefone    = "+551155256325",
                TipoUsuario = TipoUsuario.ProprietarioQuadra,
            };
        }
Exemple #2
0
        public async Task ResetarSenhaAsync_AutenticacaoServico_SucessoNoResetDaSenhaDoUsuario()
        {
            var novaSenha = _faker.Internet.Password();
            var model     = new ResetarSenhaModel
            {
                Email            = "*****@*****.**",
                Senha            = novaSenha,
                ConfirmacaoSenha = novaSenha
            };

            var authResult = await _autenticacaoServico
                             .ResetarSenhaAsync(model);

            authResult.Mensagem.Should().Be(Dicionario.MS002);
            authResult.Sucesso.Should().BeTrue();

            var usuarioComSenhaResetada = await _uow.UsuarioRepositorio
                                          .ObterUsuarioPorEmailAsync(model.Email);

            var senhaHashEsperado = SenhaHasherHelper
                                    .GerarHash(model.Senha, usuarioComSenhaResetada.Salt);

            usuarioComSenhaResetada.Senha.Should()
            .Be(senhaHashEsperado);
        }
        public async Task <AutenticacaoResult> LoginAsync(LoginModel login)
        {
            var usuario = await _uow.UsuarioRepositorio
                          .ObterUsuarioPorEmailAsync(login.Email);

            if (usuario == null || usuario.Deletado)
            {
                return(new AutenticacaoResult
                {
                    Mensagem = Dicionario.ME004,
                    Sucesso = false,
                    Errors = new[] { Dicionario.MV001 }
                });
            }

            if (!SenhaHasherHelper.SaoIguais(
                    login.Senha, usuario.Senha, usuario.Salt))
            {
                return(new AutenticacaoResult
                {
                    Mensagem = Dicionario.ME004,
                    Sucesso = false,
                    Errors = new[] { Dicionario.MV002 }
                });
            }

            return(new AutenticacaoResult
            {
                Mensagem = Dicionario.MS001,
                Sucesso = true,
                Token = await TokenHelper.GerarTokenUsuarioAsync(usuario, _jwtOptions),
                Usuario = _mapper.Map <UsuarioModel>(usuario)
            });
        }
        public async Task <AutenticacaoResult> ResetarSenhaAsync(ResetarSenhaModel model)
        {
            var usuario = await _uow.UsuarioRepositorio
                          .ObterUsuarioPorEmailAsync(model.Email);

            if (usuario == null || usuario.Deletado)
            {
                return(new AutenticacaoResult
                {
                    Mensagem = Dicionario.ME001,
                    Sucesso = false,
                });
            }

            usuario.Salt  = SenhaHasherHelper.CriarSalt(8);
            usuario.Senha = SenhaHasherHelper
                            .GerarHash(model.Senha, usuario.Salt);

            await _uow.UsuarioRepositorio.SaveAsync(usuario);

            return(new AutenticacaoResult
            {
                Mensagem = Dicionario.MS002,
                Sucesso = true
            });
        }
Exemple #5
0
        public void SaoIguais_SenhaHasherHelper_ValidarHashDeSenhaSeIgualASenha(string senha)
        {
            string senhaSalt = SenhaHasherHelper.CriarSalt(_tamanhoSalt);
            string senhaHash = SenhaHasherHelper.GerarHash(senha, senhaSalt);

            bool senhaValida = SenhaHasherHelper.SaoIguais(senha, senhaHash, senhaSalt);

            senhaValida.Should().BeTrue();
        }
Exemple #6
0
        public void SaoIguais_SenhaHasherHelper_InvalidarSenhaSeHashDeSenhaNaoForIgual(string senha)
        {
            string senhaFake = new Faker().Internet.Password();
            string senhaSalt = SenhaHasherHelper.CriarSalt(_tamanhoSalt);
            string senhaHash = SenhaHasherHelper.GerarHash(senha, senhaSalt);

            bool senhaInvalida = SenhaHasherHelper.SaoIguais(senhaFake, senhaHash, senhaSalt);

            senhaInvalida.Should().BeFalse();
        }
Exemple #7
0
        public void CriarSalt_SenhaHasherHelper_CriarSaltValido()
        {
            string salt = string.Empty;

            salt = SenhaHasherHelper.CriarSalt(_tamanhoSalt);

            salt.Should()
            .NotBeNullOrEmpty()
            .And.HaveLength(12)
            .And.NotMatchRegex("^[A-Z][a-zA-Z]*$");
        }
Exemple #8
0
        public void GerarHash_SenhaHasherHelper_GerarHashValidoDaSenha(string senha)
        {
            string hash = string.Empty;
            string salt = SenhaHasherHelper.CriarSalt(_tamanhoSalt);

            hash = SenhaHasherHelper.GerarHash(senha, salt);

            hash.Should()
            .NotBeNullOrEmpty()
            .And.HaveLength(44)
            .And.NotMatchRegex("^[A-Z][a-zA-Z]*$");
        }
Exemple #9
0
        public void Configure(EntityTypeBuilder <Usuario> builder)
        {
            builder.ToTable("Usuario");

            builder.HasKey(prop => prop.Id);

            builder.Property(prop => prop.Nome)
            .IsRequired()
            .HasMaxLength(50);

            builder.Property(prop => prop.Sobrenome)
            .IsRequired()
            .HasMaxLength(50);

            builder.HasIndex(prop => prop.Username)
            .IsUnique();
            builder.Property(prop => prop.Username)
            .IsRequired()
            .HasMaxLength(50);

            builder.HasIndex(prop => prop.Email)
            .IsUnique();
            builder.Property(prop => prop.Email)
            .IsRequired()
            .HasMaxLength(100);

            builder.Property(prop => prop.Senha)
            .IsRequired();

            builder.Property(prop => prop.Salt)
            .IsRequired()
            .HasMaxLength(15);

            builder.Property(prop => prop.TipoUsuario)
            .HasConversion <int>();

            var salt = SenhaHasherHelper.CriarSalt(8);

            // Seeding usuários
            builder.HasData(new Usuario
            {
                Nome            = "Administrador",
                Sobrenome       = "Master",
                Username        = "******",
                Email           = "*****@*****.**",
                EmailConfirmado = true,
                Telefone        = "+55 (11)1020-3040",
                Senha           = SenhaHasherHelper.GerarHash("Admin@Master123", salt),
                Salt            = salt,
                TipoUsuario     = TipoUsuario.ProprietarioTime,
            });
        }
        public async Task <AutenticacaoResult> RegistrarUsuarioAsync(RegistrarUsuarioModel model)
        {
            var emailExiste = await _uow.UsuarioRepositorio
                              .ObterUsuarioPorEmailAsync(model.Email);

            if (emailExiste != null)
            {
                return(new AutenticacaoResult
                {
                    Mensagem = Dicionario.ME005,
                    Sucesso = false,
                    Errors = new[] { Dicionario.MV003 }
                });
            }

            var usuarionameExiste = await _uow.UsuarioRepositorio
                                    .GetAsync(u => u.Username.Contains(model.Username));

            if (usuarionameExiste.Any())
            {
                return(new AutenticacaoResult
                {
                    Mensagem = Dicionario.ME005,
                    Sucesso = false,
                    Errors = new[] { Dicionario.MV004 }
                });
            }

            string salt           = SenhaHasherHelper.CriarSalt(8);
            string hashedPassword = SenhaHasherHelper
                                    .GerarHash(model.Senha, salt);

            var novoUsuario = _mapper.Map <Usuario>(model);

            novoUsuario.Salt  = salt;
            novoUsuario.Senha = hashedPassword;

            await _uow.UsuarioRepositorio
            .AddRangeAsync(new[] { novoUsuario });

            return(new AutenticacaoResult
            {
                Mensagem = Dicionario.MS003,
                Sucesso = true,
                Token = await TokenHelper.GerarTokenUsuarioAsync(novoUsuario, _jwtOptions),
                Usuario = _mapper.Map <UsuarioModel>(novoUsuario)
            });
        }
        public async Task GerarTokenUsuarioAsync_TokenHelper_GerarERetornarTokenDoUsuario()
        {
            var usuario = new Faker <Usuario>()
                          .RuleFor(u => u.Nome, f => f.Person.FirstName)
                          .RuleFor(u => u.Sobrenome, f => f.Person.LastName)
                          .RuleFor(u => u.Email, f => f.Person.Email)
                          .RuleFor(u => u.Username, f => f.UniqueIndex + f.Person.UserName)
                          .RuleFor(u => u.Senha, f => SenhaHasherHelper.GerarHash(f.Internet.Password(), _salt))
                          .RuleFor(u => u.Salt, _salt)
                          .RuleFor(u => u.TipoUsuario, TipoUsuario.Jogador);

            var result = await TokenHelper
                         .GerarTokenUsuarioAsync(usuario, _jwtOptions);

            result.Length.Should().BeGreaterThan(20);
            result.Should().NotBeNullOrEmpty();
        }
Exemple #12
0
        public static MatchDayAppContext SeedFakeData(this MatchDayAppContext testContext)
        {
            #region Usuarios

            var salt = SenhaHasherHelper.CriarSalt(8);

            var Usuarios = new List <Usuario>
            {
                new Usuario
                {
                    Nome            = "Test",
                    Sobrenome       = "One",
                    Username        = "******",
                    Email           = "*****@*****.**",
                    EmailConfirmado = true,
                    Telefone        = "+551155256325",
                    Senha           = SenhaHasherHelper.GerarHash("test123", salt),
                    Salt            = salt,
                    TipoUsuario     = TipoUsuario.ProprietarioQuadra,
                    Deletado        = true
                },
                new Usuario
                {
                    Nome            = "Test",
                    Sobrenome       = "Two",
                    Username        = "******",
                    Email           = "*****@*****.**",
                    EmailConfirmado = true,
                    Telefone        = "+551112345525",
                    Senha           = SenhaHasherHelper.GerarHash("test321", salt),
                    Salt            = salt,
                    TipoUsuario     = TipoUsuario.ProprietarioTime
                },

                new Usuario
                {
                    Nome            = "Test",
                    Sobrenome       = "Three",
                    Username        = "******",
                    Email           = "*****@*****.**",
                    EmailConfirmado = true,
                    Telefone        = "+551198765525",
                    Senha           = SenhaHasherHelper.GerarHash("test231", salt),
                    Salt            = salt,
                    TipoUsuario     = TipoUsuario.ProprietarioQuadra
                }
            };

            testContext.Usuarios.AddRange(Usuarios);
            testContext.SaveChanges();

            #endregion

            #region Confirmação Email Request

            var confirmacaoEmail = new ConfirmacaoEmail
            {
                Id               = Guid.NewGuid(),
                UsuarioId        = Usuarios.Last().Id,
                RequisicaoEm     = DateTime.Now,
                ChaveConfirmacao = Guid.Parse("C9267B0B-54A1-4971-9ED7-173008905696")
            };

            testContext.ConfirmacaoEmails.AddRange(confirmacaoEmail);
            testContext.SaveChanges();

            #endregion

            #region Times

            var teams = new List <Time>
            {
                new Time
                {
                    Nome                  = "Team 1",
                    Imagem                = "team1.png",
                    QtdIntegrantes        = 15,
                    UsuarioProprietarioId = testContext.Usuarios.ToList()[0].Id
                },
                new Time
                {
                    Nome                  = "Team 2",
                    Imagem                = "team2.png",
                    QtdIntegrantes        = 13,
                    UsuarioProprietarioId = testContext.Usuarios.ToList()[1].Id
                },
                new Time
                {
                    Nome                  = "Team 3",
                    Imagem                = "team3.png",
                    QtdIntegrantes        = 11,
                    UsuarioProprietarioId = testContext.Usuarios.ToList()[2].Id
                }
            };

            Usuarios[0].UsuarioTime = new UsuarioTime {
                UsuarioId = Usuarios[0].Id, TimeId = teams[0].Id, Aceito = true
            };
            Usuarios[1].UsuarioTime = new UsuarioTime {
                UsuarioId = Usuarios[1].Id, TimeId = teams[1].Id, Aceito = true
            };
            Usuarios[2].UsuarioTime = new UsuarioTime {
                UsuarioId = Usuarios[2].Id, TimeId = teams[2].Id, Aceito = true
            };

            testContext.Usuarios.UpdateRange(Usuarios);
            testContext.Times.AddRange(teams);
            testContext.SaveChanges();

            #endregion

            #region Quadras

            var quadra = new List <QuadraFutebol>
            {
                new QuadraFutebol
                {
                    Nome                  = "Soccer Court 1",
                    Imagem                = "soccerCourt1.png",
                    PrecoHora             = 100M,
                    Telefone              = "(11) 1234-5678",
                    Endereco              = "Av. teste 10, teste",
                    Cep                   = "12345-789",
                    Latitude              = -23.1278154,
                    Longitude             = -46.5552845,
                    UsuarioProprietarioId = testContext.Usuarios.ToList()[0].Id
                },
                new QuadraFutebol
                {
                    Nome                  = "Soccer Court 2",
                    Imagem                = "soccerCourt2.png",
                    PrecoHora             = 110M,
                    Telefone              = "(11) 0000-9999",
                    Endereco              = "Av. teste 123, teste",
                    Cep                   = "98745-036",
                    Latitude              = -22.3254,
                    Longitude             = -43.7595,
                    UsuarioProprietarioId = testContext.Usuarios.ToList()[1].Id
                },
                new QuadraFutebol
                {
                    Nome                  = "Soccer Court 3",
                    Imagem                = "soccerCourt3.png",
                    PrecoHora             = 90M,
                    Telefone              = "(11) 3692-1472",
                    Endereco              = "Av. teste 321, teste",
                    Cep                   = "01012-345",
                    Latitude              = -23.1096504,
                    Longitude             = -46.533172,
                    UsuarioProprietarioId = testContext.Usuarios.ToList()[2].Id
                }
            };

            testContext.Quadras.AddRange(quadra);
            testContext.SaveChanges();

            #endregion

            #region Partidas

            var matches = new List <Partida>
            {
                new Partida
                {
                    PrimeiroTimeId         = testContext.Times.ToList()[0].Id,
                    PrimeiroTimeConfirmado = true,
                    SegundoTimeId          = testContext.Times.ToList()[2].Id,
                    SegundoTimeConfirmado  = true,
                    QuadraFutebolId        = testContext.Quadras.ToList()[2].Id,
                    HorasPartida           = 1,
                    DataPartida            = new DateTime(2020, 10, 20, 21, 0, 0, DateTimeKind.Local),
                    StatusPartida          = StatusPartida.Confirmada
                },
                new Partida
                {
                    PrimeiroTimeId         = testContext.Times.ToList()[1].Id,
                    PrimeiroTimeConfirmado = true,
                    SegundoTimeId          = testContext.Times.ToList()[0].Id,
                    SegundoTimeConfirmado  = false,
                    QuadraFutebolId        = testContext.Quadras.ToList()[1].Id,
                    HorasPartida           = 1,
                    DataPartida            = new DateTime(2020, 10, 19, 18, 0, 0, DateTimeKind.Local),
                    StatusPartida          = StatusPartida.AguardandoConfirmacao
                },
                new Partida
                {
                    PrimeiroTimeId         = testContext.Times.ToList()[1].Id,
                    PrimeiroTimeConfirmado = true,
                    SegundoTimeId          = testContext.Times.ToList()[2].Id,
                    SegundoTimeConfirmado  = true,
                    QuadraFutebolId        = testContext.Quadras.ToList()[1].Id,
                    HorasPartida           = 1,
                    DataPartida            = new DateTime(2020, 10, 21, 19, 0, 0, DateTimeKind.Local),
                    StatusPartida          = StatusPartida.Confirmada
                },
                new Partida
                {
                    PrimeiroTimeId         = testContext.Times.ToList()[0].Id,
                    PrimeiroTimeConfirmado = true,
                    SegundoTimeId          = testContext.Times.ToList()[1].Id,
                    SegundoTimeConfirmado  = true,
                    QuadraFutebolId        = testContext.Quadras.ToList()[0].Id,
                    HorasPartida           = 1,
                    DataPartida            = new DateTime(2020, 10, 16, 20, 0, 0, DateTimeKind.Local),
                    StatusPartida          = StatusPartida.Finalizada
                },
                new Partida
                {
                    PrimeiroTimeId         = testContext.Times.ToList()[2].Id,
                    PrimeiroTimeConfirmado = false,
                    SegundoTimeId          = testContext.Times.ToList()[1].Id,
                    SegundoTimeConfirmado  = true,
                    QuadraFutebolId        = testContext.Quadras.ToList()[2].Id,
                    HorasPartida           = 1,
                    DataPartida            = new DateTime(2020, 10, 18, 17, 0, 0, DateTimeKind.Local),
                    StatusPartida          = StatusPartida.Cancelada
                }
            };

            testContext.Partidas.Add(matches[0]);
            testContext.SaveChanges();
            testContext.Partidas.Add(matches[1]);
            testContext.SaveChanges();
            testContext.Partidas.Add(matches[2]);
            testContext.SaveChanges();
            testContext.Partidas.Add(matches[3]);
            testContext.SaveChanges();
            testContext.Partidas.Add(matches[4]);
            testContext.SaveChanges();

            #endregion

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

            return(testContext);
        }