Exemplo n.º 1
0
        public async Task Activate_User_Should_Activate_User()
        {
            var idUserTest = _jimmyUser.Id;

            User myUserDesactivated = null;

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                myUserDesactivated         = context.Users.FirstOrDefault(u => u.Id.Equals(idUserTest));
                myUserDesactivated.IsValid = false;
                context.Update(myUserDesactivated);
                context.Commit();
            }
            Assert.IsNotNull(myUserDesactivated);
            Assert.IsFalse(myUserDesactivated.IsValid);

            var activateOrDesactivateUserDto = new ActivateOrDesactivateUserDto()
            {
                UserName = _jimmyUser.UserName
            };

            var httpResponseMessage = await _client.PutAsJsonAsync("users/activate", activateOrDesactivateUserDto);

            Assert.IsTrue(httpResponseMessage.IsSuccessStatusCode);

            User myUserActivated = null;

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                myUserActivated = context.Users.FirstOrDefault(u => u.Id.Equals(idUserTest));
            }
            Assert.IsNotNull(myUserActivated);
            Assert.IsTrue(myUserActivated.IsValid);
        }
Exemplo n.º 2
0
        public void Add_Should_Add_Entity()
        {
            var actualClientCount = 0;

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                actualClientCount = context.Clients.Count();

                var clientRepository = _repoFactory.GetClientRepository(context);
                clientRepository.Add(new Client()
                {
                    ClientSecret = "6",
                    ClientTypeId = 1,
                    CreationDate = DateTime.Now,
                    Description  = "Test 2",
                    IsValid      = true,
                    Name         = "testeur2",
                    PublicId     = "test"
                });
                context.Commit();
            }

            // Use a separate instance of the context to verify correct datas were saved to database
            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                Assert.AreEqual(actualClientCount + 1, context.Clients.Count());
            }
        }
Exemplo n.º 3
0
        public async Task Token_For_Grant_Type_Refresh_Token_Should_Return_Valid_Token()
        {
            var jwtService = new JwtService()
            {
                Configuration          = OAuthApiTestStartup.Configuration,
                Logger                 = new FakeLogger(),
                RepositoriesFactory    = null,
                StringLocalizerFactory = new FakeStringLocalizerFactory()
            };

            var jwtTokenDto = jwtService.GenerateToken(new CreateTokenDto()
            {
                ClientPublicId  = _sammyClientPublicIdConfidential,
                Scope           = _sammyScopeWording,
                SecondsLifeTime = OAuthApiTestStartup.Configuration.RefreshTokenLifeTimeInSeconds,
                TokenName       = OAuthConvention.RefreshToken,
                UserName        = _sammyUserName
            });

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                var userClient = context.UsersClients.
                                 FirstOrDefault(uc => uc.User.UserName.Equals(_sammyUserName) && uc.Client.PublicId.Equals(_sammyClientPublicIdConfidential));

                Assert.IsNotNull(userClient);

                userClient.RefreshToken = jwtTokenDto.Token;

                context.Update(userClient);

                context.Commit();
            }

            var formContent = BuildFormContent(
                _sammyClientPublicIdConfidential,
                String.Empty,
                OAuthConvention.GrantTypeRefreshToken,
                jwtTokenDto.Token,
                String.Empty,
                _sammyReturnUrlConfidential,
                _sammyScopeWording,
                _sammyUserName);

            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _client.DefaultRequestHeaders.Authorization = BuildAuthenticationHeaderValue(_sammyClientPublicIdConfidential, _sammyClientSecretConfidential);

            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/token");

            request.Content = formContent;

            var httpResponseMessage = await _client.SendAsync(request);

            Assert.IsTrue(httpResponseMessage.IsSuccessStatusCode);

            await CheckResponseContentIsValid(httpResponseMessage);
        }
Exemplo n.º 4
0
        public async Task Token_For_Grant_Type_Authorization_Code_Should_Return_Valid_Token()
        {
            var code = "abc";

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                var newCode = new Code()
                {
                    CodeValue           = code,
                    ExpirationTimeStamp = long.MaxValue,
                    Id           = 888,
                    IsValid      = true,
                    Scope        = _sammyScopeWording,
                    UserClientId = _sammyUserClientIdConfidential
                };

                context.Codes.Add(newCode);

                context.Commit();
            }

            var formContent = BuildFormContent(
                _sammyClientPublicIdConfidential,
                code,
                OAuthConvention.GrantTypeAuthorizationCode,
                String.Empty,
                String.Empty,
                _sammyReturnUrlConfidential,
                _sammyScopeWording,
                _sammyUserName);

            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _client.DefaultRequestHeaders.Authorization = BuildAuthenticationHeaderValue(_sammyClientPublicIdConfidential, _sammyClientSecretConfidential);

            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/token");

            request.Content = formContent;

            var httpResponseMessage = await _client.SendAsync(request);

            Assert.IsTrue(httpResponseMessage.IsSuccessStatusCode);

            await CheckResponseContentIsValid(httpResponseMessage);

            Code codeFromDb = null;

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                codeFromDb = context.Codes.Where(c => c.CodeValue.Equals(code) && c.UserClientId.Equals(_sammyUserClientIdConfidential)).FirstOrDefault();
            }

            Assert.IsNotNull(codeFromDb);
            Assert.IsFalse(codeFromDb.IsValid);
        }
Exemplo n.º 5
0
        protected void InitDataBase()
        {
            _dbContextOptions = new DbContextOptionsBuilder <DaOAuthContext>()
                                .UseInMemoryDatabase(databaseName: _dbName)
                                .Options;

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                context.ClientsTypes.Add(_confidentialClientType);
                context.ClientsTypes.Add(_publicClientType);

                context.RessourceServers.Add(_ressourceServer1);
                context.RessourceServers.Add(_ressourceServer2);
                context.RessourceServers.Add(_ressourceServer3);

                context.Scopes.Add(_scope1);
                context.Scopes.Add(_scope2);
                context.Scopes.Add(_scope3);
                context.Scopes.Add(_scope4);
                context.Scopes.Add(_scope5);

                context.Clients.Add(_clientConfidential1);
                context.Clients.Add(_clientConfidential2);
                context.Clients.Add(_invalidPublicClient1);

                context.ClientsScopes.Add(_client1Scope2);
                context.ClientsScopes.Add(_client2Scope3);
                context.ClientsScopes.Add(_client2Scope1);
                context.ClientsScopes.Add(_client1Scope4);
                context.ClientsScopes.Add(_client1Scope5);
                context.ClientsScopes.Add(_client2Scope5);

                context.ClientReturnUrls.Add(_clientReturnUrl1ForClient1);
                context.ClientReturnUrls.Add(_clientReturnUrl2ForClient1);

                context.Users.Add(_user1);
                context.Users.Add(_user2);

                context.UsersClients.Add(_user1Client1);
                context.UsersClients.Add(_user1Client2);
                context.UsersClients.Add(_user1ClientInvalid);

                context.Codes.Add(_code1);
                context.Codes.Add(_code2);

                context.Roles.Add(_role1);
                context.Roles.Add(_role2);

                context.UsersRoles.Add(_user1Role1);
                context.UsersRoles.Add(_user1Role2);

                context.Commit();
            }
        }
Exemplo n.º 6
0
        protected void InitDataBaseAndHttpClient()
        {
            _dbContextOptions = new DbContextOptionsBuilder <DaOAuthContext>()
                                .UseInMemoryDatabase(databaseName: OAuthApiTestStartup.TestDataBaseName)
                                .Options;

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                context.RessourceServers.Add(_validRessourceServer);

                context.Scopes.Add(_scope1);
                context.Scopes.Add(_scope2);
                context.Scopes.Add(_scope3);

                context.Roles.Add(_roleAdmin);
                context.Roles.Add(_roleUser);

                context.Users.Add(_sammyUser);

                context.UsersRoles.Add(_sammyAdminRole);

                context.ClientsTypes.Add(_confidentialClientType);
                context.ClientsTypes.Add(_publicClientType);

                context.Clients.Add(_sammyClientConfidential);
                context.Clients.Add(_sammyClientPublic);

                context.ClientsScopes.Add(_clientScopeConfidential);
                context.ClientsScopes.Add(_clientScopePublic);

                context.ClientReturnUrls.Add(_clientReturnUrlConfidential);
                context.ClientReturnUrls.Add(_clientReturnUrlPublic);

                context.UsersClients.Add(_sammyUserClientConfidential);
                context.UsersClients.Add(_sammyUserClientPublic);

                context.Commit();
            }

            var builder = new WebHostBuilder();

            var config = new ConfigurationBuilder()
                         .AddJsonFile("Configuration/appsettings.Test.json")
                         .Build();

            var server = new TestServer(builder
                                        .UseConfiguration(config)
                                        .UseEnvironment(OAuthApiTestStartup.TestEnvironnementName)
                                        .UseStartup <OAuthApiTestStartup>());

            _client = server.CreateClient();
        }
Exemplo n.º 7
0
        public async Task Validate_Should_Validate_User()
        {
            var validationToken  = "abc";
            var validateUserName = "******";

            var toValidateUser = new User()
            {
                BirthDate       = DateTime.Now.AddYears(-30),
                CreationDate    = DateTime.Now,
                EMail           = "*****@*****.**",
                FullName        = "To Validate",
                Id              = 2000,
                IsValid         = false,
                Password        = new byte[] { 1, 1, 1 },
                UserName        = validateUserName,
                ValidationToken = validationToken
            };

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                context.Users.Add(toValidateUser);
                context.Commit();
            }

            var validateUserDto = new ValidateUserDto()
            {
                Token    = validationToken,
                UserName = validateUserName
            };

            var httpResponseMessage = await _client.PutAsJsonAsync("users/validate", validateUserDto);

            Assert.IsTrue(httpResponseMessage.IsSuccessStatusCode);

            User validatedUser = null;

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                validatedUser = context.Users.FirstOrDefault(u => u.Id.Equals(toValidateUser.Id));
            }
            Assert.IsNotNull(validatedUser);

            Assert.IsTrue(validatedUser.IsValid);
        }
Exemplo n.º 8
0
        public void Delete_Should_Delete_Entity()
        {
            Scope scope   = null;
            var   idScope = _scope1.Id;

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                var scopeRepo = _repoFactory.GetScopeRepository(context);
                scope = scopeRepo.GetById(idScope);
                scopeRepo.Delete(scope);
                context.Commit();
            }

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                Assert.AreEqual(0, context.Scopes.Count(s => s.Id.Equals(idScope)));

                var scopeRepository = _repoFactory.GetScopeRepository(context);
                scope = scopeRepository.GetById(idScope);
            }

            Assert.IsNull(scope);
        }
Exemplo n.º 9
0
        public void Update_Should_Update_Entity()
        {
            Scope scope      = null;
            var   idScope    = _scope1.Id;
            var   newWording = "update";

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                var scopeRepository = _repoFactory.GetScopeRepository(context);
                scope         = scopeRepository.GetById(idScope);
                scope.Wording = newWording;
                scopeRepository.Update(scope);
                context.Commit();
            }

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                var scopeRepository = _repoFactory.GetScopeRepository(context);
                scope = scopeRepository.GetById(idScope);
            }

            Assert.IsNotNull(scope);
            Assert.AreEqual(newWording, scope.Wording);
        }
Exemplo n.º 10
0
        protected void InitDataBaseAndHttpClient()
        {
            _dbContextOptions = new DbContextOptionsBuilder <DaOAuthContext>()
                                .UseInMemoryDatabase(databaseName: GuiApiTestStartup.TestDataBaseName)
                                .Options;

            using (var context = new DaOAuthContext(_dbContextOptions))
            {
                context.RessourceServers.Add(_validRessourceServer);

                context.Scopes.Add(_scope1);
                context.Scopes.Add(_scope2);
                context.Scopes.Add(_scope3);

                context.Roles.Add(_roleAdmin);
                context.Roles.Add(_roleUser);

                context.Users.Add(_sammyUser);
                context.Users.Add(_mariusUser);
                context.Users.Add(_jimmyUser);

                context.UsersRoles.Add(_sammyAdminRole);
                context.UsersRoles.Add(_mariusUserRole);
                context.UsersRoles.Add(_jimmyUserRole);

                context.ClientsTypes.Add(_confidentialClientType);
                context.ClientsTypes.Add(_publicClientType);

                context.Clients.Add(_jimmyClient);
                context.Clients.Add(_sammyClient);

                context.ClientsScopes.Add(_clientScope1);
                context.ClientsScopes.Add(_clientScope2);
                context.ClientsScopes.Add(_clientScope3);
                context.ClientsScopes.Add(_clientScope4);

                context.ClientReturnUrls.Add(_clientReturnUrl1);
                context.ClientReturnUrls.Add(_clientReturnUrl2);
                context.ClientReturnUrls.Add(_clientReturnUrl3);
                context.ClientReturnUrls.Add(_clientReturnUrl4);
                context.ClientReturnUrls.Add(_clientReturnUrl5);

                context.UsersClients.Add(_jimmyUserClient);
                context.UsersClients.Add(_sammyUserClient);

                context.Commit();
            }

            var builder = new WebHostBuilder();

            var config = new ConfigurationBuilder()
                         .AddJsonFile("Configuration/appsettings.test.json")
                         .Build();

            var server = new TestServer(builder
                                        .UseConfiguration(config)
                                        .ConfigureTestServices(services =>
            {
                services.AddTransient <IUserService>(u => new UserService()
                {
                    Configuration       = GuiApiTestStartup.Configuration,
                    RepositoriesFactory = new EfRepositoriesFactory()
                    {
                        DbContextOptions = _dbContextOptions
                    },
                    StringLocalizerFactory = new FakeStringLocalizerFactory(),
                    Logger            = new FakeLogger(),
                    MailService       = _fakeMailService,
                    RandomService     = new RandomService(),
                    EncryptionService = new EncryptionService(),
                    JwtService        = new JwtService()
                    {
                        Configuration          = GuiApiTestStartup.Configuration,
                        StringLocalizerFactory = new FakeStringLocalizerFactory(),
                        Logger = new FakeLogger()
                    }
                });
            })
                                        .UseEnvironment(GuiApiTestStartup.TestEnvironnementName)
                                        .UseStartup <GuiApiTestStartup>());

            _client = server.CreateClient();
        }