Exemplo n.º 1
0
        public async Task CanModifyUser()
        {
            // arrange
            var httpClient   = new UsersHttpClient(this.Authority, this.Handler);
            var originalUser = new User
            {
                Username    = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Password    = "******",
                Email       = "*****@*****.**",
                PhoneNumber = "123456789",
                Roles       = { "admin" },
            };

            var expectedUser = new User
            {
                Username    = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Password    = "******",
                Email       = "*****@*****.**",
                PhoneNumber = "987654321",
                Roles       = { "auth_admin", "user_admin" },
            };

            var initialUser = await httpClient.AddUserAsync(originalUser).ConfigureAwait(false);

            // act
            var actualUser = await httpClient.ModifyUserAsync(expectedUser, originalUser.Username).ConfigureAwait(false);

            // assert
            actualUser.Should().NotBeNull();
            actualUser.Should().BeEquivalentTo(expectedUser, options => options.Excluding(user => user.Id).Excluding(user => user.Password));
            actualUser.Id.Should().Be(initialUser.Id);
        }
Exemplo n.º 2
0
        public async Task CanAddUserWithConfirmationEmail()
        {
            // arrange
            var httpClient   = new UsersHttpClient(this.Authority, this.Handler);
            var expectedUser = new User
            {
                Username = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Email    = "*****@*****.**",
                SendConfirmationEmail = true,
                PhoneNumber           = "123456789",
                Roles = { "admin" },
            };

            // act
            var actualUser = await httpClient.AddUserAsync(expectedUser).ConfigureAwait(false);

            // assert
            // TODO (Cameron): Assert email was sent (somehow).
            actualUser.Should().NotBeNull();
            actualUser.Should().BeEquivalentTo(
                expectedUser,
                options => options
                .Excluding(user => user.Id)
                .Excluding(user => user.Password)
                .Excluding(user => user.SendConfirmationEmail)
                .Excluding(user => user.RegistrationLink));
            actualUser.RegistrationLink.Should().NotBeNull();
        }
Exemplo n.º 3
0
        public async Task CanGetRoleSummariesWithQuery()
        {
            // arrange
            var httpClient = new UsersHttpClient(this.Authority, this.Handler);
            var user1      = new User {
                Username = "******"
            };
            var user2 = new User {
                Username = "******"
            };
            var user3 = new User {
                Username = "******"
            };

            await httpClient.AddUserAsync(user1).ConfigureAwait(false);

            await httpClient.AddUserAsync(user2).ConfigureAwait(false);

            await httpClient.AddUserAsync(user3).ConfigureAwait(false);

            // act
            var userSummaries = await httpClient.GetUserSummariesAsync("query_").ConfigureAwait(false);

            // assert
            userSummaries.Should().NotBeNull();
            userSummaries.Should().HaveCount(2);
            userSummaries.Should().Contain(summary => summary.Username == user2.Username);
            userSummaries.Should().Contain(summary => summary.Username == user3.Username);
        }
Exemplo n.º 4
0
        public void CannotRemoveDefaultAdminUser()
        {
            // arrange
            var httpClient = new UsersHttpClient(this.Authority, this.Handler);
            var username   = "******";

            // act
            Func <Task> func = async() => await httpClient.RemoveUserAsync(username).ConfigureAwait(false);

            // assert
            func.Should().Throw <HttpException>().And.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
Exemplo n.º 5
0
        public void CannotAddInvalidUser()
        {
            // arrange
            var httpClient = new UsersHttpClient(this.Authority, this.Handler);
            var user       = new User();

            // act
            Func <Task> func = async() => await httpClient.AddUserAsync(user).ConfigureAwait(false);

            // assert
            func.Should().Throw <HttpException>();
        }
Exemplo n.º 6
0
        public async Task CanAddUserMinimum()
        {
            // arrange
            var httpClient   = new UsersHttpClient(this.Authority, this.Handler);
            var expectedUser = new User
            {
                Username = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
            };

            // act
            var actualUser = await httpClient.AddUserAsync(expectedUser).ConfigureAwait(false);

            // assert
            actualUser.Should().NotBeNull();
            actualUser.Username.Should().Be(expectedUser.Username);
        }
Exemplo n.º 7
0
        public async Task CannotAddDuplicateUser()
        {
            // arrange
            var httpClient = new UsersHttpClient(this.Authority, this.Handler);
            var user       = new User
            {
                Username = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
            };

            await httpClient.AddUserAsync(user).ConfigureAwait(false);

            // act
            Func <Task> func = async() => await httpClient.AddUserAsync(user).ConfigureAwait(false);

            // assert
            func.Should().Throw <HttpException>().And.StatusCode.Should().Be(HttpStatusCode.Conflict);
        }
Exemplo n.º 8
0
        public async Task CanGetUserSummaries()
        {
            // arrange
            var httpClient   = new UsersHttpClient(this.Authority, this.Handler);
            var expectedUser = new User
            {
                Username = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Email    = "*****@*****.**",
            };

            var actualUser = await httpClient.AddUserAsync(expectedUser).ConfigureAwait(false);

            // act
            var userSummaries = await httpClient.GetUserSummariesAsync().ConfigureAwait(false);

            // assert
            userSummaries.Should().NotBeNull();
            userSummaries.Should().Contain(summary => summary.Id == actualUser.Id && summary.Username == expectedUser.Username && summary.Email == expectedUser.Email);
        }
Exemplo n.º 9
0
        public void ShouldNotThrowInternalServerError()
        {
            // arrange
            var httpClient = new UsersHttpClient(this.Authority, this.Handler);
            var user       = new User
            {
                Username    = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Password    = "******",
                Email       = "*****@*****.**",
                PhoneNumber = "0123456789",
                Roles       = { "auth_admin", "user_admin" },
            };

            // act
            Func <Task> func = async() => await httpClient.AddUserAsync(user).ConfigureAwait(false);

            // assert
            func.Should().NotThrow <HttpException>();
        }
Exemplo n.º 10
0
        public async Task CanRemoveUser()
        {
            // arrange
            var httpClient = new UsersHttpClient(this.Authority, this.Handler);
            var user       = new User
            {
                Username = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
            };

            await httpClient.AddUserAsync(user).ConfigureAwait(false);

            // act
            await httpClient.RemoveUserAsync(user.Username).ConfigureAwait(false);

            // assert
            var userSummaries = await httpClient.GetUserSummariesAsync().ConfigureAwait(false);

            userSummaries.Should().NotBeNull();
            userSummaries.Should().NotContain(summary => summary.Username == user.Username);
        }
Exemplo n.º 11
0
        public async Task CanAddUser()
        {
            // arrange
            var httpClient   = new UsersHttpClient("http://localhost:5009", this.Handler);
            var expectedUser = new User
            {
                UserId                = "sub",
                ClientTier            = ClientTierDto.TIER_2,
                DefaultAssetAccountId = "account",
            };

            var actualUser = default(User);

            // hook into the context (somehow) and verify
            this.AssignRequestDelegate(
                async httpContext =>
            {
                if (httpContext.Request.Method.Equals("POST", StringComparison.InvariantCultureIgnoreCase) &&
                    httpContext.Request.Path.Value.Equals("/api/user", StringComparison.InvariantCultureIgnoreCase))
                {
                    actualUser = await httpContext.Request.DeserializeBody <User>().ConfigureAwait(false);

                    if (actualUser != null)
                    {
                        httpContext.Response.StatusCode = (int)HttpStatusCode.Accepted;

                        return;
                    }
                }

                httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            });

            // act
            await httpClient.AddUserAsync(expectedUser).ConfigureAwait(false);

            // assert
            actualUser.Should().BeEquivalentTo(expectedUser);
        }
Exemplo n.º 12
0
        public async Task CanUseUser()
        {
            // arrange
            var httpClient = new UsersHttpClient(this.Authority, this.Handler);
            var user       = new User
            {
                Username = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
                Password = "******",
            };

            await httpClient.AddUserAsync(user).ConfigureAwait(false);

            // act
            var automation = new BrowserAutomation(user.Username, user.Password);
            var browser    = new Browser(automation);
            var options    = new OidcClientOptions
            {
                Authority    = this.Authority,
                ClientId     = "auth_console",
                RedirectUri  = $"http://127.0.0.1:{browser.Port}",
                Scope        = "openid profile auth_api offline_access",
                FilterClaims = false,
                Browser      = browser,
                Policy       = new Policy {
                    Discovery = new DiscoveryPolicy {
                        ValidateIssuerName = false
                    }
                }
            };

            var oidcClient = new OidcClient(options);
            var result     = await oidcClient.LoginAsync(new LoginRequest()).ConfigureAwait(false);

            // assert
            result.IsError.Should().BeFalse();
        }
Exemplo n.º 13
0
        public async Task <int> TryRunAsync(string[] args)
        {
            CommandLineOptions options;

            try
            {
                options = CommandLineOptions.Parse(args, this.console);
            }
            catch (CommandParsingException ex)
            {
                new ConsoleReporter(this.console).Warn(ex.Message);
                return(1);
            }

            if (options == null)
            {
                return(1);
            }

            if (options.Help.HasValue())
            {
                return(2);
            }

            if (options.Command == null)
            {
                return(3);
            }

            var repository = new CommandDataRepository(this.provider);

            if (options.Command is LoginCommand.Reset)
            {
                await options.Command.ExecuteAsync(new CommandContext(this.console, null, null, null, repository)).ConfigureAwait(false);

                return(0);
            }

            var data = repository.GetCommandData() ??
                       new CommandData
            {
                Authority  = LoginCommand.DefaultAuthority,
                ServiceUrl = LoginCommand.DefaultService,
            };

            var authority = data.Authority;
            var service   = data.ServiceUrl;

            if (options.Command is LoginCommand loginCommand)
            {
                authority = loginCommand.Authority;
                service   = loginCommand.ServiceUrl;
            }
            else
            {
                this.console.WriteLine("Executing command against ");
                this.console.ForegroundColor = ConsoleColor.White;
                this.console.WriteLine($"Authority: {authority}");
                this.console.WriteLine($"Service Url: {service}");
                this.console.ResetColor();
                this.console.WriteLine("...");
            }

            var discoveryResponse = default(DiscoveryResponse);

            using (var discoveryClient = new DiscoveryClient(authority))
            {
                discoveryResponse = await discoveryClient.GetAsync().ConfigureAwait(false);

                if (discoveryResponse.IsError)
                {
                    await this.console.Error.WriteLineAsync(discoveryResponse.Error).ConfigureAwait(false);

                    return(500);
                }
            }

            var api = default(Api);

            using (var client = new HttpClient())
            {
                try
                {
                    using (var response = client.GetAsync(new Uri($"{service}/platform")).GetAwaiter().GetResult())
                    {
                        response.EnsureSuccessStatusCode();
                        api = JsonConvert.DeserializeObject <Api>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
                    }
                }
                catch (HttpRequestException)
                {
                    await this.console.Error.WriteLineAsync($"Unable to connect to service: {service}.").ConfigureAwait(false);

                    return(500);
                }

                if (api == null)
                {
                    await this.console.Error.WriteLineAsync($"Invalid response from: {service}.").ConfigureAwait(false);

                    return(500);
                }
            }

            using (var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "donut_console"))
                using (var refreshTokenHandler = new RefreshTokenHandler(tokenClient, data.RefreshToken, data.AccessToken))
                    using (var usersClient = new UsersHttpClient(service, refreshTokenHandler))
                        using (var assetAccountsClient = new AssetAccountsHttpClient(service, refreshTokenHandler))
                        {
                            refreshTokenHandler.TokenRefreshed += (sender, e) =>
                            {
                                repository.SetCommandData(
                                    new CommandData
                                {
                                    Authority    = authority,
                                    AccessToken  = e.AccessToken,
                                    RefreshToken = e.RefreshToken,
                                    ServiceUrl   = service,
                                });
                            };

                            var reporter = new ConsoleReporter(this.console, options.Verbose.HasValue(), false);
                            var context  = new CommandContext(this.console, reporter, usersClient, assetAccountsClient, repository);

                            try
                            {
                                await options.Command.ExecuteAsync(context).ConfigureAwait(false);
                            }
                            catch (Exception ex)
                            {
                                reporter.Error(ex.Message);
                                return(500);
                            }
                            finally
                            {
                                this.console.ResetColor();
                            }

                            return(0);
                        }
        }
Exemplo n.º 14
0
        public async Task <int> TryRunAsync(string[] args)
        {
            CommandLineOptions options;

            try
            {
                options = CommandLineOptions.Parse(args, this.console);
            }
            catch (CommandParsingException ex)
            {
                new ConsoleReporter(this.console).Warn(ex.Message);
                return(1);
            }

            if (options == null)
            {
                return(1);
            }

            if (options.Help.HasValue())
            {
                return(2);
            }

            if (options.Command == null)
            {
                return(3);
            }

            var repository = new CommandDataRepository(this.provider);

            if (options.Command is LoginCommand.Reset)
            {
                await options.Command.ExecuteAsync(new CommandContext(this.console, null, null, null, null, null, null, repository)).ConfigureAwait(false);

                return(0);
            }

            var data = repository.GetCommandData() ??
                       new CommandData
            {
                Authority = LoginCommand.ProductionAuthority,
            };

            var authority = data.Authority;

            if (options.Command is LoginCommand loginCommand)
            {
                authority = loginCommand.Authority;
            }
            else
            {
                this.console.Write("Executing command against ");
                this.console.ForegroundColor = ConsoleColor.White;
                this.console.Write(authority);
                this.console.ResetColor();
                this.console.WriteLine("...");
            }

            var discoveryResponse = default(DiscoveryResponse);

            using (var discoveryClient = new DiscoveryClient(authority))
            {
                discoveryResponse = await discoveryClient.GetAsync().ConfigureAwait(false);

                if (discoveryResponse.IsError)
                {
                    await this.console.Error.WriteLineAsync(discoveryResponse.Error).ConfigureAwait(false);

                    return(500);
                }
            }

            using (var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "auth_console"))
                using (var refreshTokenHandler = new RefreshTokenHandler(tokenClient, data.RefreshToken, data.AccessToken))
                    using (var clientsClient = new ClientsHttpClient(authority, refreshTokenHandler))
                        using (var apiResourcesClient = new ApiResourcesHttpClient(authority, refreshTokenHandler))
                            using (var identityResourcesClient = new IdentityResourcesHttpClient(authority, refreshTokenHandler))
                                using (var rolesClient = new RolesHttpClient(authority, refreshTokenHandler))
                                    using (var usersClient = new UsersHttpClient(authority, refreshTokenHandler))
                                    {
                                        refreshTokenHandler.TokenRefreshed += (sender, e) =>
                                        {
                                            repository.SetCommandData(
                                                new CommandData
                                            {
                                                Authority    = authority,
                                                AccessToken  = e.AccessToken,
                                                RefreshToken = e.RefreshToken,
                                            });
                                        };

                                        var reporter = new ConsoleReporter(this.console, options.Verbose.HasValue(), false);
                                        var context  = new CommandContext(this.console, reporter, clientsClient, apiResourcesClient, identityResourcesClient, rolesClient, usersClient, repository);

                                        try
                                        {
                                            await options.Command.ExecuteAsync(context).ConfigureAwait(false);
                                        }
                                        catch (Exception ex)
                                        {
                                            reporter.Error(ex.Message);
                                            return(500);
                                        }
                                        finally
                                        {
                                            this.console.ResetColor();
                                        }

                                        return(0);
                                    }
        }