Exemple #1
0
        public AzureSubscriptionCleaner(IAuthenticated authenticated, string subscriptionId, string exceptedRGsRegex, ILogger logger, IConfigurationRoot config)
        {
            this.Authenticated    = authenticated;
            this.SubscriptionId   = subscriptionId;
            this.ExceptedRGsRegex = exceptedRGsRegex;
            this.Logger           = logger;
            this.Config           = config;
            this.DefaultExpiry    = 2;
            this.DefaultExtension = 4;
            this.UsageLookback    = 1;

            if (Config["DefaultExpiry"] != null)
            {
                this.DefaultExpiry = Int32.Parse(Config["DefaultExpiry"]);
            }

            if (Config["DefaultExtension"] != null)
            {
                this.DefaultExtension = Int32.Parse(Config["DefaultExtension"]);
            }

            if (Config["UsageLookback"] != null)
            {
                this.UsageLookback = Int32.Parse(Config["UsageLookback"]);
            }
        }
Exemple #2
0
 ITwitchChatClientBuilder ITwitchChatClientBuilder.WithOAuthToken(string oAuthToken)
 {
     _authenticated = new AuthenticationBuilder()
                      .FromOAuthToken(oAuthToken)
                      .Build();
     return(this);
 }
Exemple #3
0
        public void Deploy(
            IAuthenticated azure,
            DeploymentOptions options,
            IEnumerable <AzureResource> resources)
        {
            foreach (AzureResource resource in resources)
            {
                Task.Factory.StartNew(async() =>
                {
                    try
                    {
                        Started?.Invoke(this, new DeploymentEventArgs(resource));

                        await CreateResourceAsync(azure, options, resource.Type);

                        Finished?.Invoke(this, new DeploymentEventArgs(resource));
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"Error creating resource of type {resource.Type}: {ex}");
                        Failed?.Invoke(this, new DeploymentErrorEventArgs(resource, ex));
                    }
                });
            }
        }
Exemple #4
0
        private Azure(RestClient restClient, string subscriptionId, string tenantId, IAuthenticated authenticated)
        {
            resourceManager          = ResourceManager.Fluent.ResourceManager.Authenticate(restClient).WithSubscription(subscriptionId);
            storageManager           = StorageManager.Authenticate(restClient, subscriptionId);
            computeManager           = ComputeManager.Authenticate(restClient, subscriptionId);
            networkManager           = NetworkManager.Authenticate(restClient, subscriptionId);
            batchManager             = BatchManager.Authenticate(restClient, subscriptionId);
            keyVaultManager          = KeyVaultManager.Authenticate(restClient, subscriptionId, tenantId);
            trafficManager           = TrafficManager.Fluent.TrafficManager.Authenticate(restClient, subscriptionId);
            dnsZoneManager           = DnsZoneManager.Authenticate(restClient, subscriptionId);
            sqlManager               = SqlManager.Authenticate(restClient, subscriptionId);
            redisManager             = RedisManager.Authenticate(restClient, subscriptionId);
            cdnManager               = CdnManager.Authenticate(restClient, subscriptionId);
            appServiceManager        = AppServiceManager.Authenticate(restClient, subscriptionId, tenantId);
            searchManager            = SearchManager.Authenticate(restClient, subscriptionId);
            serviceBusManager        = ServiceBusManager.Authenticate(restClient, subscriptionId);
            containerInstanceManager = ContainerInstanceManager.Authenticate(restClient, subscriptionId);
            registryManager          = RegistryManager.Authenticate(restClient, subscriptionId);
            containerServiceManager  = ContainerServiceManager.Authenticate(restClient, subscriptionId);
            cosmosDBManager          = CosmosDBManager.Authenticate(restClient, subscriptionId);
            authorizationManager     = AuthorizationManager.Authenticate(restClient, subscriptionId);
            msiManager               = MsiManager.Authenticate(restClient, subscriptionId);
            batchAIManager           = BatchAIManager.Authenticate(restClient, subscriptionId);
            monitorManager           = MonitorManager.Authenticate(restClient, subscriptionId);
            eventHubManager          = EventHubManager.Authenticate(restClient, subscriptionId);

            SubscriptionId     = subscriptionId;
            this.authenticated = authenticated;
        }
Exemple #5
0
        public static TwitchAPIClient Create(IAuthenticated authenticated)
        {
            var loggerFactory = new LoggerFactory();
            var httpClient    = new HttpClient();

            return(new TwitchAPIClient(authenticated, httpClient, loggerFactory.CreateLogger <TwitchAPIClient>()));
        }
Exemple #6
0
        public BaseDeployment(IAuthenticated azure, DeploymentOptions options)
        {
            Azure   = azure;
            Options = options;

            analyticsService = DependencyService.Resolve <AnalyticsService>();
            watch            = new Stopwatch();
        }
Exemple #7
0
 public IGDBClient(IAuthenticated authenticated, IHttpClientFactory httpClientFactory, IMemoryCache memoryCache, TwitchAPIClient twitchAPIClient, ILogger <IGDBClient> logger)
 {
     _httpClient             = httpClientFactory.CreateClient();
     _httpClient.BaseAddress = new Uri("https://api.igdb.com/");
     _authenticated          = authenticated;
     _cache  = memoryCache;
     _logger = logger;
 }
Exemple #8
0
 public StorageAccountDeployment(
     string accountName,
     IAuthenticated azure,
     DeploymentOptions options)
     : base(azure, options)
 {
     AccountName = accountName;
 }
Exemple #9
0
 public SqlAzureDeployment(
     string serverName,
     IAuthenticated azure,
     DeploymentOptions options)
     : base(azure, options)
 {
     ServerName = serverName;
 }
 public CosmosDbAccountDeployment(
     string docDbName,
     IAuthenticated azure,
     DeploymentOptions options)
     : base(azure, options)
 {
     DocDbName = docDbName;
 }
 public KeyVaultDeployment(
     string vaultName,
     IAuthenticated azure,
     DeploymentOptions options)
     : base(azure, options)
 {
     VaultName = vaultName;
 }
 public WebAppDeployment(
     string appName,
     IAuthenticated azure,
     DeploymentOptions options)
     : base(azure, options)
 {
     AppName = appName;
 }
Exemple #13
0
        public AzureSubscription(IAuthenticated authenticated, ISubscription subscription) : base(subscription.DisplayName, "azure/subscription")
        {
            _azure = authenticated.WithSubscription(subscription.SubscriptionId);

            CommandGroups.Add(new HierarchicalResourceCommandGroup(
                                  new HierarchicalResourceCommand("refresh", Symbol.Refresh, RefreshAsync)));

            RefreshAsync().Forget();
        }
Exemple #14
0
 internal TwitchChatClient(IAuthenticated authenticated, Uri endpoint, ILogger <TwitchChatClient> logger)
 {
     _authenticated = authenticated;
     _endpoint      = endpoint;
     _logger        = logger;
     _webSocket     = new ClientWebSocket();
     _inBuffer      = new byte[8703]; // IRCv3 8191B Tags + 512B message
     _outBuffer     = new byte[1024];
 }
Exemple #15
0
        async Task HandleTransportAsync(IAsyncTransport transport, IHandler handler, object context)
        {
            IPrincipal principal = null;

            if (this.saslSettings != null)
            {
                ListenerSaslProfile profile = new ListenerSaslProfile(this);
                transport = await profile.NegotiateAsync(transport).ConfigureAwait(false);

                principal = profile.GetPrincipal();
            }

            var connection = new ListenerConnection(this, this.address, handler, transport);

            if (principal == null)
            {
                // SASL principal preferred. If not present, check transport.
                IAuthenticated authenticated = transport as IAuthenticated;
                if (authenticated != null)
                {
                    principal = authenticated.Principal;
                }
            }

            connection.Principal = principal;

            bool shouldClose = false;

            lock (this.connections)
            {
                if (!this.closed)
                {
                    connection.Closed += this.OnConnectionClosed;
                    this.connections.Add(connection);
                }
                else
                {
                    shouldClose = true;
                }
            }

            if (shouldClose)
            {
                await connection.CloseAsync().ConfigureAwait(false);
            }
            else
            {
                if (handler != null && handler.CanHandle(EventId.ConnectionAccept))
                {
                    handler.Handle(Event.Create(EventId.ConnectionAccept, connection, context: context));
                }

                AsyncPump pump = new AsyncPump(this.BufferManager, transport);
                pump.Start(connection);
            }
        }
Exemple #16
0
        public async Task <IReadOnlyCollection <KeyValuePair <string, ISubscription> > > ListAllSubscriptionsAsync()
        {
            IAuthenticated             globalClient = GetAuthenticated();
            IPagedCollection <ITenant> tenants      = await globalClient.Tenants.ListAsync().ConfigureAwait(false);

            var all = new List <KeyValuePair <string, ISubscription> >();
            await Task.WhenAll(tenants.Select(t => ListSubscriptionsAsync(t.TenantId, all))).ConfigureAwait(false);

            return(all.AsReadOnly());
        }
Exemple #17
0
        public static async Task ListSubscriptionAsync(this IAuthenticated azure)
        {
            Console.WriteLine("List Subscriptions... ");
            var subs = await azure.Subscriptions.ListAsync();

            foreach (var sub in subs)
            {
                Console.WriteLine(sub.SubscriptionId);
            }
        }
Exemple #18
0
        private async Task ListSubscriptionsAsync(string tenantId, IList <KeyValuePair <string, ISubscription> > subscriptions)
        {
            IAuthenticated tenantClient           = GetAuthenticated(tenantId);
            IPagedCollection <ISubscription> subs = await tenantClient.Subscriptions.ListAsync().ConfigureAwait(false);

            foreach (ISubscription sub in subs)
            {
                subscriptions.Add(new KeyValuePair <string, ISubscription>(tenantId, sub));
            }
        }
Exemple #19
0
            public IPrincipal GetPrincipal()
            {
                IAuthenticated authenticated = this.innerProfile as IAuthenticated;

                if (authenticated != null)
                {
                    return(authenticated.Principal);
                }

                return(null);
            }
Exemple #20
0
        public static List <KeyVaultProperties> runProgram(string[] args, bool testing)
        {
            AccessPoliciesToYaml   ap = new AccessPoliciesToYaml(testing);
            UpdatePoliciesFromYaml up = new UpdatePoliciesFromYaml(testing);

            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("Refer to 'Log.log' for more details should an error be thrown.\n");
            Console.ResetColor();

            Console.WriteLine("Reading input files...");
            up.verifyFileExtensions(args);
            JsonInput vaultList = ap.readJsonFile(args[0]);

            Console.WriteLine("Finished!");

            Console.WriteLine("Grabbing secrets...");
            Dictionary <string, string> secrets = ap.getSecrets();

            Console.WriteLine("Finished!");

            Console.WriteLine("Creating KeyVaultManagementClient, GraphServiceClient, and AzureClient...");
            KeyVaultManagementClient kvmClient   = ap.createKVMClient(secrets);
            GraphServiceClient       graphClient = ap.createGraphClient(secrets);
            IAuthenticated           azureClient = ap.createAzureClient(secrets);

            Console.WriteLine("Finished!");;

            Console.WriteLine("Checking access and retrieving key vaults...");
            ap.checkAccess(vaultList, azureClient);
            List <KeyVaultProperties> vaultsRetrieved = ap.getVaults(vaultList, kvmClient, graphClient);

            Console.WriteLine("Finished!");

            Console.WriteLine("Reading yaml file...");
            List <KeyVaultProperties> yamlVaults = up.deserializeYaml(args[1]);

            Console.WriteLine("Finished!");

            Console.WriteLine("Updating key vaults...");
            List <KeyVaultProperties> deletedPolicies = up.updateVaults(yamlVaults, vaultsRetrieved, kvmClient, secrets, graphClient);

            Console.WriteLine("Finished!");

            Console.WriteLine("Generating DeletedPolicies yaml...");
            up.convertToYaml(deletedPolicies, args[2]);
            Console.WriteLine("Finished!");

            if (testing)
            {
                return(up.Changed);
            }
            return(null);
        }
        async Task HandleTransportAsync(IAsyncTransport transport)
        {
            IPrincipal principal = null;

            if (this.saslSettings != null)
            {
                ListenerSaslProfile profile = new ListenerSaslProfile(this);
                transport = await profile.NegotiateAsync(transport);

                principal = profile.GetPrincipal();
            }

            IHandler handler    = this.HandlerFactory?.Invoke(this);
            var      connection = new ListenerConnection(this, this.address, handler, transport);

            if (principal == null)
            {
                // SASL principal preferred. If not present, check transport.
                IAuthenticated authenticated = transport as IAuthenticated;
                if (authenticated != null)
                {
                    principal = authenticated.Principal;
                }
            }

            connection.Principal = principal;

            bool shouldClose = false;

            lock (this.connections)
            {
                if (!this.closed)
                {
                    connection.Closed += this.OnConnectionClosed;
                    this.connections.Add(connection);
                }
                else
                {
                    shouldClose = true;
                }
            }

            if (shouldClose)
            {
                await connection.CloseAsync();
            }
            else
            {
                AsyncPump pump = new AsyncPump(this.BufferManager, transport);
                pump.Start(connection);
            }
        }
        private void AuthenticateClient()
        {
            // clint credentials flow with secret
            var clientId     = _configuration.GetValue <string>("AzureManagementFluent:ClientId");
            var clientSecret = _configuration.GetValue <string>("AzureManagementFluent:ClientSecret");
            var tenantId     = _configuration.GetValue <string>("AzureManagementFluent:TenantId");

            AzureCredentialsFactory azureCredentialsFactory = new AzureCredentialsFactory();
            var credentials = azureCredentialsFactory
                              .FromServicePrincipal(clientId,
                                                    clientSecret,
                                                    tenantId,
                                                    AzureEnvironment.AzureGlobalCloud);

            // authenticate to Azure AD
            _authenticatedClient = Microsoft.Azure.Management.Fluent.Azure.Configure()
                                   .Authenticate(credentials);
        }
Exemple #23
0
        private Task CreateResourceAsync(
            IAuthenticated azure,
            DeploymentOptions options,
            AzureResourceType resourceType)
        {
            string         resourceName = GetRandomResourceName(resourceType);
            BaseDeployment deployment   = null;

            switch (resourceType)
            {
            case AzureResourceType.AppService:
            case AzureResourceType.WebApp:
                deployment = new WebAppDeployment(resourceName, azure, options);
                break;

            case AzureResourceType.Storage:
                deployment = new StorageAccountDeployment(resourceName, azure, options);
                break;

            case AzureResourceType.CosmosDB:
                deployment = new CosmosDbAccountDeployment(resourceName, azure, options);
                break;

            case AzureResourceType.Functions:
                deployment = new AzureFunctionDeployment(resourceName, azure, options);
                break;

            case AzureResourceType.SqlDatabase:
                deployment = new SqlAzureDeployment(resourceName, azure, options);
                break;

            case AzureResourceType.KeyVault:
                deployment = new KeyVaultDeployment(resourceName, azure, options);
                break;

            default:
                Debug.WriteLine($"Service of type {resourceType} not supported!");
                break;
            }

            return(deployment != null
                ? deployment.CreateAsync()
                : Task.CompletedTask);
        }
Exemple #24
0
        public IAuthenticated GetAuthenticated(string tenantId = "common")
        {
            if (!_tenantIdToAuthenticated.TryGetValue(tenantId, out IAuthenticated auth))
            {
                var armCredentials = new CleverServiceClientCredentials(
                    "https://management.azure.com/",
                    _clientId,
                    tenantId,
                    _tokenCache);
                armCredentials.UserTokenInteraction = UserTokenInteraction;
                if (!_userInfoReceiverSet)
                {
                    armCredentials.UserInfoReceiver = this;
                    _userInfoReceiverSet            = true;
                }

                var            azureCreds    = new AzureCredentials(armCredentials, null, tenantId, AzureEnvironment.AzureGlobalCloud);
                IAuthenticated authenticated = Azure.Authenticate(azureCreds);
                _tenantIdToAuthenticated[tenantId] = authenticated;
                return(authenticated);
            }

            return(auth);
        }
        /// <summary>
        /// This method reads in a Json config file and converts it into a serialized list of KeyVaults that are displayed in a Yaml file.
        /// </summary>
        public static void Main(string[] args)
        {
            AccessPoliciesToYaml ap = new AccessPoliciesToYaml(false);

            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("Refer to 'Log.log' for more details should an error be thrown.\n");
            Console.ResetColor();

            Console.WriteLine("Reading input file...");
            ap.verifyFileExtensions(args);
            JsonInput vaultList = ap.readJsonFile(args[0]);

            Console.WriteLine("Finished!");

            Console.WriteLine("Grabbing secrets...");
            Dictionary <string, string> secrets = ap.getSecrets();

            Console.WriteLine("Finished!");

            Console.WriteLine("Creating KeyVaultManagementClient, GraphServiceClient, and AzureClient...");
            KeyVaultManagementClient kvmClient   = ap.createKVMClient(secrets);
            GraphServiceClient       graphClient = ap.createGraphClient(secrets);
            IAuthenticated           azureClient = ap.createAzureClient(secrets);

            Console.WriteLine("Finished!");;

            Console.WriteLine("Checking access and retrieving key vaults...");
            ap.checkAccess(vaultList, azureClient);
            List <KeyVaultProperties> vaultsRetrieved = ap.getVaults(vaultList, kvmClient, graphClient);

            Console.WriteLine("Finished!");

            Console.WriteLine("Generating YAML output...");
            ap.convertToYaml(vaultsRetrieved, args[1]);
            Console.WriteLine("Finished!");
        }
Exemple #26
0
        public ActionResult Login(LoginAccountViewModel account)
        {
            IAuthenticated authenticated = null;

            if (ModelState.IsValid)
            {
                RestClient client = RemoteConfig.Client;

                RestRequest request = RemoteConfig.AUTHENTICATE.Request;
                request.AddParameter("email", account.Email);
                request.AddParameter("password", account.Password);

                IRestResponse response = client.Execute(request);

                try
                {
                    JObject jObject = JObject.Parse(response.Content);
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        String token = (String)jObject["token"];

                        request = RemoteConfig.USER.Request;
                        request.AddHeader("Authorization", $"JWT {token}");
                        response = client.Execute(request);

                        try
                        {
                            jObject = JObject.Parse(response.Content);

                            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                            {
                                JToken jToken = jObject["user"];
                                authenticated = new AuthUser(new User
                                {
                                    Id        = (String)jToken["_id"],
                                    FirstName = (String)jToken["firstName"],
                                    LastName  = (String)jToken["lastName"],
                                    Email     = (String)jToken["email"],
                                    // TODO createdAt, convert string to date
                                }, token);
                            }
                        }
                        catch
                        {
                            Debug.WriteLine("exception");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("password", (String)jObject["message"]);
                    }
                }
                catch
                {
                    ModelState.AddModelError("password", "Unable issue the server for authentication");
                }
            }

            if (authenticated != null)
            {
                Session[Reference.KEY_USER_SESSION] = authenticated as IAuthenticated;

                return(RedirectToAction("Index", "Default"));
            }

            return(View());
        }
Exemple #27
0
 public AccountController(IAuthenticated authenticated) : base(authenticated)
 {
 }
 public DeletionOrchestrator(IAuthenticated auth, ILoggerFactory loggerFactory, IOptions <DeletionOptions> options) : base(auth, loggerFactory)
 {
     _options = options.Value;
 }
Exemple #29
0
 public BaseController(IAuthenticated authenticated)
 {
     Authenticated = authenticated;
 }
Exemple #30
0
 ITwitchChatClientBuilder ITwitchChatClientBuilder.WithAuthenticatedUser(IAuthenticated authenticated)
 {
     _authenticated = authenticated;
     return(this);
 }