示例#1
0
        public async Task SaveActivation(ActivationInfo activationInfo)
        {
            var     defaultAdGroup = Config.DefaultAdGroup;
            ADGroup orgGroup       = AzureADGraphApiUtil.CheckIfADGroupExistsByOrgName(activationInfo.Organization.Id, defaultAdGroup);

            if (orgGroup == null)
            {
                await AzureADGraphApiUtil.CreateGroup(activationInfo.Organization.Id, defaultAdGroup);

                orgGroup = AzureADGraphApiUtil.CheckIfADGroupExistsByOrgName(activationInfo.Organization.Id, defaultAdGroup);
            }

            if (orgGroup == null)
            {
                throw new UnauthorizedAccessException($"Default ADGroup: {defaultAdGroup} could not be created! Make sure you have ADMIN access to the Azure AD");
            }

            //var orgGroups = AzureADGraphApiUtil.GetAllGroupsForOrganization(activationInfo.Organization.Id);
            activationInfo.Organization.CreateProductGroup = orgGroup.Id; //orgGroups[0].Id;
            activationInfo.Organization.AdminGroup         = orgGroup.Id; //orgGroups[0].Id;
            activationInfo.Organization.DeployGroup        = orgGroup.Id; //orgGroups[0].Id;

            await SaveHostSubscription(activationInfo);
            await SaveEnrolledSubscriptions(activationInfo);

            await this.coreRepository.SaveOrganization(activationInfo.Organization);
            await AddEnrollingUserToAllGroups(activationInfo.Organization);

            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("ASC");
            const string queryUrl = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vm-simple-windows/azuredeploy.json";
            // Initially set the nextLink to the origin URL
            TemplateViewModel templateInit = new TemplateViewModel();
            var response = await httpClient.GetStringAsync(queryUrl);

            templateInit.Name         = "Simple Window VM";
            templateInit.IsPublished  = true;
            templateInit.TemplateData = response;
            TemplateViewModel savedTemplateEntity = await repository.SaveTemplate(templateInit);

            const string queryUrl2 = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-create-ase-with-webapp/azuredeploy.parameters.json";
            // Initially set the nextLink to the origin URL
            TemplateViewModel templateInit2 = new TemplateViewModel();
            var response2 = await httpClient.GetStringAsync(queryUrl2);

            templateInit2.Name         = "Web App with Redis Cache and SQL Database";
            templateInit2.IsPublished  = true;
            templateInit2.TemplateData = response;
            TemplateViewModel savedTemplateEntity2 = await repository.SaveTemplate(templateInit2);

            var notifProcessor = new NotificationProcessor();

            notifProcessor.SendActivationNotification(activationInfo.Organization);
        }
示例#2
0
        private async Task SaveHostSubscription(ActivationInfo activationInfo)
        {
            if (string.IsNullOrEmpty(activationInfo.HostSubscription.ServicePrincipalId))
            {
                var organizations        = AzureResourceManagerUtil.GetUserOrganizations();
                var selectedOrganization = organizations.Where(o => o.Id == activationInfo.HostSubscription.OrganizationId).FirstOrDefault();
                activationInfo.HostSubscription.ServicePrincipalId = selectedOrganization.ObjectIdOfCloudSenseServicePrincipal;
            }
            Run.WithProgressBackOff(5, 1, 5, () =>
            {
                AzureResourceManagerUtil.GrantRoleToServicePrincipalOnSubscription(activationInfo.HostSubscription.ServicePrincipalId, activationInfo.HostSubscription.SubscriptionId);
            });

            // Create Resource Group to hold Storage Account
            string resourceGroup = Config.DefaultResourceGroup;
            var    json          = await AzureResourceManagerUtil.GetStorageProvider(activationInfo.HostSubscription.SubscriptionId);

            JObject storageProvider = Newtonsoft.Json.JsonConvert.DeserializeObject <JObject>(json);
            var     client          = Utils.GetResourceManagementClient(activationInfo.HostSubscription.SubscriptionId);
            string  location        = storageProvider["resourceTypes"][0]["locations"][0].ToString();
            var     rg     = new ResourceGroup(location);
            var     result = await client.ResourceGroups.CreateOrUpdateAsync(resourceGroup, rg, new CancellationToken());


            // Create Storage Account
            this.storageName = await AzureResourceManagerUtil.CreateServiceCatalogMetadataStorageAccount(activationInfo.HostSubscription.SubscriptionId, resourceGroup);

            string key = await AzureResourceManagerUtil.GetStorageAccountKeysArm(activationInfo.HostSubscription.SubscriptionId, this.storageName);

            BlobHelpers.CreateInitialTablesAndBlobContainers(storageName, key);
            CacheDetails(activationInfo.HostSubscription.SubscriptionId, key, storageName, activationInfo.HostSubscription.OrganizationId);
            var orgGroups = AzureADGraphApiUtil.GetAllGroupsForOrganization(activationInfo.Organization.Id);

            ContributorGroup[] contributorGroups = new ContributorGroup[1];
            contributorGroups[0]      = new ContributorGroup();
            contributorGroups[0].Id   = orgGroups[0].Id;
            contributorGroups[0].Name = orgGroups[0].Name;

            var jsonContributorGroups = JsonConvert.SerializeObject(contributorGroups);

            await this.coreRepository.SaveSubscription(new Subscription
            {
                Id                = activationInfo.HostSubscription.SubscriptionId,
                IsConnected       = true,
                ConnectedOn       = DateTime.Now,
                ContributorGroups = jsonContributorGroups,
                DisplayName       = activationInfo.HostSubscription.SubscriptionName,
                OrganizationId    = activationInfo.HostSubscription.OrganizationId,
                StorageName       = storageName,
                ConnectedBy       = ClaimsPrincipal.Current.Identity.Name,
            });
        }
示例#3
0
        private static async Task AddEnrollingUserToAllGroups(Organization org)
        {
            var userId = ClaimsPrincipal.Current.UserId();
            await AzureADGraphApiUtil.AddUserToGroup(org.Id, org.CreateProductGroup, userId);

            if (org.DeployGroup != org.CreateProductGroup)
            {
                await AzureADGraphApiUtil.AddUserToGroup(org.Id, org.DeployGroup, userId);
            }
            if (org.AdminGroup != org.CreateProductGroup)
            {
                await AzureADGraphApiUtil.AddUserToGroup(org.Id, org.AdminGroup, userId);
            }
        }
示例#4
0
        public static List <string> GetCurrentUserGroups()
        {
            List <string> userGroups   = null;
            var           userAdGroups = AzureADGraphApiUtil.GetUserGroups(ClaimsPrincipal.Current.UserId(), ClaimsPrincipal.Current.TenantId());

            if (userAdGroups != null)
            {
                //During enrollment a new AD group is added. This group will not be available in Claims until user logs out and logs in again.
                //So we first try to get the user groups directly from the AD
                userGroups = userAdGroups.Select(x => x.Id).ToList();
            }
            else
            {
                userGroups = ClaimsPrincipal.Current.Groups();
            }

            return(userGroups);
        }
示例#5
0
        /// <summary>
        /// Gets the user organizations.
        /// </summary>
        /// <returns></returns>
        public static List <Organization> GetUserOrganizations()
        {
            List <Organization> organizations = new List <Organization>();
            string              tenantId      = ClaimsPrincipal.Current.TenantId();
            var                 requestUrl    = new Uri($"{Config.AzureResourceManagerUrl}/tenants?api-version={Config.AzureResourceManagerAPIVersion}");
            var                 httpClient    = Utils.GetAuthenticatedHttpClientForApp();
            HttpRequestMessage  request       = new HttpRequestMessage(HttpMethod.Get, requestUrl);
            HttpResponseMessage response      = httpClient.SendAsync(request).Result;

            // Endpoint returns JSON with an array of Tenant Objects
            // id                                            tenantId
            // --                                            --------
            // /tenants/7fe877e6-a150-4992-bbfe-f517e304dfa0 7fe877e6-a150-4992-bbfe-f517e304dfa0
            // /tenants/62e173e9-301e-423e-bcd4-29121ec1aa24 62e173e9-301e-423e-bcd4-29121ec1aa24

            if (response.IsSuccessStatusCode)
            {
                string responseContent     = response.Content.ReadAsStringAsync().Result;
                var    organizationsResult = (Json.Decode(responseContent)).value;
                foreach (var organization in organizationsResult)
                {
                    var spid = AzureADGraphApiUtil.GetObjectIdOfServicePrincipalInOrganization(organization.tenantId, Config.ClientId);

                    //if (!string.IsNullOrEmpty(spid))
                    if (spid != string.Empty)
                    {
                        Organization orgDetails = AzureADGraphApiUtil.GetOrganizationDetails(organization.tenantId);
                        organizations.Add(new Organization()
                        {
                            Id             = organization.tenantId,
                            DisplayName    = orgDetails.DisplayName,
                            VerifiedDomain = orgDetails.VerifiedDomain,
                            ObjectIdOfCloudSenseServicePrincipal = spid
                        });
                    }
                }
            }
            return(organizations);
        }