public async Task <HttpResponseMessage> Post()
        {
            // The post body should contain a JSON representation of the AADGroup object
            HttpResponseMessage response = new HttpResponseMessage();
            string   content             = Request.Content.ReadAsStringAsync().Result;
            AADGroup model = null;

            try
            {
                // Convert the JSON payload to an AADGroup
                model = JsonConvert.DeserializeObject <AADGroup>(content);
            }
            catch (Exception ex)
            {
                response.StatusCode = HttpStatusCode.InternalServerError;
                response.Content    = new StringContent(ex.Message);
            }

            if (model != null)
            {
                // Authenticate to the Microsoft Graph and create a graph client
                string           clientId         = ConfigurationManager.AppSettings["ClientId"];
                string           clientSecret     = ConfigurationManager.AppSettings["ClientSecret"];
                string           tenant           = ConfigurationManager.AppSettings["Tenant"];
                ClientCredential clientCredential = new ClientCredential(clientSecret);
                IConfidentialClientApplication clientApplication = ClientCredentialProvider.CreateClientApplication(clientId, clientCredential, null, tenant);
                ClientCredentialProvider       authProvider      = new ClientCredentialProvider(clientApplication);
                GraphServiceClient             graphClient       = new GraphServiceClient(authProvider);

                var group = new Group
                {
                    Description     = model.Description,
                    DisplayName     = model.DisplayName,
                    MailEnabled     = model.MailEnabled,
                    MailNickname    = model.MailNickname,
                    SecurityEnabled = model.SecurityEnabled
                };

                try
                {
                    // Add the group to Azure AD
                    var newGroup = await graphClient.Groups
                                   .Request()
                                   .AddAsync(group);

                    // Capture the object ID of the newly created group
                    model.Id            = newGroup.Id;
                    response.StatusCode = HttpStatusCode.OK;
                    response.Content    = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
                }
                catch (Exception ex)
                {
                    response.StatusCode = HttpStatusCode.InternalServerError;
                    response.Content    = new StringContent(ex.Message);
                }
            }

            return(response);
        }
Exemple #2
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string ipGroups      = req.Query["aadGroups"];
            string ipAdlsAccount = req.Query["adlsAccount"];
            string ipAdlsPath    = req.Query["adlsPath"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            ipGroups      = ipGroups ?? data?.aadGroups;
            ipAdlsAccount = ipAdlsAccount ?? data?.adlsAccount;
            ipAdlsPath    = ipAdlsPath ?? data?.adlsPath;

            if (string.IsNullOrEmpty(ipGroups))
            {
                return(makeHttpErrorResponse(System.Net.HttpStatusCode.BadRequest,
                                             "Please provide a value for the `aadGroups` parameter"));
            }

            if (string.IsNullOrEmpty(ipAdlsAccount))
            {
                return(makeHttpErrorResponse(System.Net.HttpStatusCode.BadRequest, "Please provide a value for the `adlsAccount` parameter"));
            }

            if (string.IsNullOrEmpty(ipAdlsPath))
            {
                return(makeHttpErrorResponse(System.Net.HttpStatusCode.BadRequest, "Please provide a value for the `adlsPath` parameter"));
            }


            List <String> groupNames = new List <String>(ipGroups.Split(";"));

            log.LogInformation("C# HTTP trigger function processed a request.");

            var client = GetGraphApiClient(log).Result;

            if (client != null)
            {
                log.LogInformation($"Received client");
            }

            List <AADGroup>             aadGroups         = new List <AADGroup>();
            List <AADGroupMember>       otherMembers      = new List <AADGroupMember>();
            List <AADUser>              users             = new List <AADUser>();
            List <AADServicePrincipal>  servicePrincipals = new List <AADServicePrincipal>();
            Dictionary <string, string> fileNames         = new Dictionary <string, string>();


            foreach (string groupName in groupNames)
            {
                Graph.IGraphServiceGroupsCollectionPage groups = await
                                                                 client.Groups.Request()
                                                                 .Filter($"DisplayName eq '{groupName}'")
                                                                 .Expand("Members")
                                                                 .GetAsync();


                if (groups?.Count > 0)
                {
                    foreach (Graph.Group group in groups)
                    {
                        AADGroup aadGroup = new AADGroup(group.Id, group.DisplayName);
                        log.LogInformation($"Processing '{group.DisplayName}'");
                        if (group.Members?.Count > 0)
                        {
                            foreach (Graph.DirectoryObject dobj in group.Members)
                            {
                                switch (dobj)
                                {
                                case Graph.User user:
                                    users.Add(new AADUser(group, user.Id, "User", user.DisplayName, user.UserPrincipalName));
                                    break;

                                case Graph.ServicePrincipal spn:
                                    servicePrincipals.Add(new AADServicePrincipal(group, spn.Id, "SPN", spn.DisplayName, spn.AppId));
                                    break;

                                default:
                                    otherMembers.Add(new AADGroupMember(group, dobj.Id, dobj.GetType().ToString()));
                                    break;
                                }
                            }
                        }
                        aadGroups.Add(aadGroup);
                    }
                }
            }


            string filename;
            bool   success;


            filename = $"User_{Guid.NewGuid()}.json";
            success  = await LakeWriter.writeTextFile(Environment.GetEnvironmentVariable("AAD_TENANT"), ipAdlsAccount,
                                                      ipAdlsPath, filename, JsonConvert.SerializeObject(users), log);

            if (success)
            {
                fileNames.Add("User", filename);
            }

            filename = $"Group_{Guid.NewGuid()}.json";
            success  = await LakeWriter.writeTextFile(Environment.GetEnvironmentVariable("AAD_TENANT"), ipAdlsAccount,
                                                      ipAdlsPath, filename, JsonConvert.SerializeObject(aadGroups), log);

            if (success)
            {
                fileNames.Add("Group", filename);
            }

            filename = $"SPN_{Guid.NewGuid()}.json";
            success  = await LakeWriter.writeTextFile(Environment.GetEnvironmentVariable("AAD_TENANT"), ipAdlsAccount,
                                                      ipAdlsPath, filename, JsonConvert.SerializeObject(servicePrincipals), log);

            if (success)
            {
                fileNames.Add("SPN", filename);
            }

            filename = $"OtherMember_{Guid.NewGuid()}.json";
            success  = await LakeWriter.writeTextFile(Environment.GetEnvironmentVariable("AAD_TENANT"), ipAdlsAccount,
                                                      ipAdlsPath, filename, JsonConvert.SerializeObject(otherMembers), log);

            if (success)
            {
                fileNames.Add("OtherMember", filename);
            }

            log.LogInformation(fileNames.ToString());
            return(new HttpResponseMessage(System.Net.HttpStatusCode.OK)
            {
                Content = new StringContent(JsonConvert.SerializeObject(fileNames), Encoding.UTF8, "application/json")
            });
        }