Exemple #1
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] DeleteGroupRequest request, TraceWriter log)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.GroupId))
                {
                    throw new ArgumentException("Parameter cannot be null", "GroupId");
                }

                GraphServiceClient client = ConnectADAL.GetGraphClient(GraphEndpoint.v1);
                await client.Groups[request.GroupId].Request().DeleteAsync();
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <DeleteGroupResponse>(new DeleteGroupResponse {
                        GroupDeleted = true
                    }, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <DeleteGroupResponse>(new DeleteGroupResponse {
                        GroupDeleted = false
                    }, new JsonMediaTypeFormatter())
                }));
            }
        }
        private static async Task SetGroupSettings(CreateGroupRequest request, CreateGroupResponse response, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            try
            {
                if (!request.AllowToAddGuests)
                {
                    var groupUnifiedGuestSetting = new GroupSetting()
                    {
                        DisplayName = "Group.Unified.Guest",
                        TemplateId  = "08d542b9-071f-4e16-94b0-74abb372e3d9",
                        Values      = new List <SettingValue> {
                            new SettingValue()
                            {
                                Name = "AllowToAddGuests", Value = "false"
                            }
                        }
                    };
                    log.Info($"Setting setting in Group.Unified.Guest (08d542b9-071f-4e16-94b0-74abb372e3d9), AllowToAddGuests = false");
                    await client.Groups[response.GroupId].Settings.Request().AddAsync(groupUnifiedGuestSetting);
                }
            }
            catch (Exception e)
            {
                log.Error($"Error setting AllowToAddGuests for group {response.GroupId}: {e.Message }\n\n{e.StackTrace}");
            }
        }
        private static async Task <List <User> > GetUsers(string[] userEmails)
        {
            List <User> usersList = new List <User>();

            if (userEmails == null || userEmails.Length == 0)
            {
                return(usersList);
            }
            GraphServiceClient client = ConnectADAL.GetGraphClient();
            var users = await client.Users.Request().Top(999).GetAsync();

            while (users.Count > 0)
            {
                foreach (var user in users)
                {
                    if (userEmails.Any(mail => string.Compare(user.UserPrincipalName, mail, true) == 0))
                    {
                        usersList.Add(user);
                    }
                }

                if (users.NextPageRequest != null)
                {
                    users = await users.NextPageRequest.GetAsync();
                }
                else
                {
                    break;
                }
            }
            return(usersList);
        }
Exemple #4
0
        public static async Task <AddOwnerResponse> Run([HttpTrigger(AuthorizationLevel.Function, "post")] AddOwnerRequest request, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            int idx = request.LoginName.LastIndexOf('|');

            if (idx > 0)
            {
                request.LoginName = request.LoginName.Substring(idx + 1);
            }

            var ownerQuery = await client.Users
                             .Request()
                             .Filter($"userPrincipalName eq '{request.LoginName}'")
                             .GetAsync();

            var  owner = ownerQuery.FirstOrDefault();
            bool added = false;

            if (owner != null)
            {
                try
                {
                    // And if any, add it to the collection of group's owners
                    log.Info($"Adding user {request.LoginName} to Owners group for {request.GroupId}");
                    await client.Groups[request.GroupId].Owners.References.Request().AddAsync(owner);
                    if (request.AddOption == AddOwnerOption.AddAsOwnerAndMember)
                    {
                        log.Info($"Adding user {request.LoginName} to Members group for {request.GroupId}");
                        await client.Groups[request.GroupId].Members.References.Request().AddAsync(owner);
                    }
                    added = true;
                }
                catch (ServiceException ex)
                {
                    if (ex.Error.Code == "Request_BadRequest" &&
                        ex.Error.Message.Contains("added object references already exist"))
                    {
                        // Skip any already existing owner
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            return(new AddOwnerResponse()
            {
                Added = added
            });
        }
Exemple #5
0
        public static async Task <AllowExternalMembersInGroupResponse> Run([HttpTrigger(AuthorizationLevel.Function, "post")] AllowExternalMembersInGroupRequest request, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            try
            {
                const string externalTemplateId    = "08d542b9-071f-4e16-94b0-74abb372e3d9";
                GroupSetting externalMemberSetting = new GroupSetting {
                    TemplateId = externalTemplateId
                };
                SettingValue setVal = new SettingValue
                {
                    Name  = "AllowToAddGuests",
                    Value = request.ExternalAllowed.ToString()
                };
                externalMemberSetting.Values = new List <SettingValue> {
                    setVal
                };

                var existingSettings = await client.Groups[request.GroupId].Settings.Request().GetAsync();

                bool hasExistingSetting = false;
                foreach (GroupSetting groupSetting in existingSettings)
                {
                    if (!groupSetting.TemplateId.Equals(externalTemplateId, StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    await client.Groups[request.GroupId].Settings[groupSetting.Id].Request().UpdateAsync(externalMemberSetting);
                    hasExistingSetting = true;
                    break;
                }

                if (!hasExistingSetting)
                {
                    await client.Groups[request.GroupId].Settings.Request().AddAsync(externalMemberSetting);
                }

                return(new AllowExternalMembersInGroupResponse {
                    ExternalAllowed = request.ExternalAllowed
                });
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                throw;
            }
        }
        private static async Task SetGroupMembership(CreateGroupResponse response, List <User> owners, List <User> members, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            foreach (var owner in owners)
            {
                try
                {
                    log.Info($"Setting {owner.Mail} as Owner for the group.");
                    await client.Groups[response.GroupId].Owners.References.Request().AddAsync(owner);
                }
                catch (ServiceException ex)
                {
                    if (ex.Error.Code == "Request_BadRequest" && ex.Error.Message.Contains("added object references already exist"))
                    {
                        // Skip any already existing member
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
            foreach (var member in members)
            {
                try
                {
                    log.Info($"Setting {member.Mail} as Member for the group.");
                    await client.Groups[response.GroupId].Owners.References.Request().AddAsync(member);
                }
                catch (ServiceException ex)
                {
                    if (ex.Error.Code == "Request_BadRequest" && ex.Error.Message.Contains("added object references already exist"))
                    {
                        // Skip any already existing member
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
        }
Exemple #7
0
        public static async Task <GetGroupSiteResponse> Run([HttpTrigger(AuthorizationLevel.Function, "post")] GetGroupSiteRequest request, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            try
            {
                var rootSite = await client.Groups[request.GroupId].Sites["root"].Request().GetAsync();
                return(string.IsNullOrWhiteSpace(rootSite.WebUrl) ? new GetGroupSiteResponse {
                    SiteURL = "n/a"
                } : new GetGroupSiteResponse {
                    SiteURL = rootSite.WebUrl
                });
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(new GetGroupSiteResponse()
                {
                    SiteURL = e.Message
                });
            }
        }
        public static async Task <GetClassificationValuesResponse> Run([HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestMessage req, TraceWriter log)
        {
            GraphServiceClient client = ConnectADAL.GetGraphClient();

            try
            {
                const string groupTemplateId  = "62375ab9-6b52-47ed-826b-58e47e0e304b";
                var          existingSettings = await client.GroupSettings.Request().GetAsync();

                var response = new GetClassificationValuesResponse();
                foreach (GroupSetting groupSetting in existingSettings)
                {
                    if (!groupSetting.TemplateId.Equals(groupTemplateId, StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }
                    foreach (SettingValue settingValue in groupSetting.Values)
                    {
                        if (settingValue.Name.Equals("ClassificationList"))
                        {
                            response.Classifications = settingValue.Value.Split(',');
                        }
                        else if (settingValue.Name.Equals("DefaultClassification"))
                        {
                            response.DefaultClassification = settingValue.Value;
                        }
                    }
                    break;
                }

                return(response);
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                throw;
            }
        }
Exemple #9
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] DeleteGroupRequest request, TraceWriter log)
        {
            try
            {
                GraphServiceClient client = ConnectADAL.GetGraphClient(GraphEndpoint.Beta);

                // get the group to be deleted
                var delgroup = await client.Groups[request.GroupId].Request().GetAsync();

                // Create a response for the deleted group
                var DelGroupResponse = new DeletedGroupResponse
                {
                    GroupId     = delgroup.Id,
                    DisplayName = delgroup.DisplayName,
                    Mail        = delgroup.Mail
                };

                // delete the group, if the group is deleted the SP Site will be deleted also but take some time.
                await client.Groups[request.GroupId].Request().DeleteAsync();


                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <DeletedGroupResponse>(DelGroupResponse, new JsonMediaTypeFormatter())
                }));
            }

            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
Exemple #10
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] RemoveGroupMembersRequest request, TraceWriter log)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.GroupId))
                {
                    throw new ArgumentException("Parameter cannot be null", "GroupId");
                }
                GraphServiceClient client = ConnectADAL.GetGraphClient(GraphEndpoint.v1);
                var group   = client.Groups[request.GroupId];
                var members = await group.Members.Request().Select("displayName, id, mail, userPrincipalName, userType").GetAsync();

                var users = new List <GroupUser>();

                foreach (var u in members.CurrentPage.Where(p => p.GetType() == typeof(User)).Cast <User>().ToList())
                {
                    users.Add(new GroupUser()
                    {
                        Id = u.Id, UserType = u.UserType, Mail = u.Mail
                    });
                }


                // Removing users from group members
                for (int i = 0; i < users.Count; i++)
                {
                    var user = users[i];
                    if (user.UserType != "Guest" && request.GroupMembersRemoval == GroupMembersRemoval.GuestUsersOnly)
                    {
                        continue;
                    }
                    log.Info($"Removing user {user.Id} from group {request.GroupId}");
                    await group.Members[user.Id].Reference.Request().DeleteAsync();
                }


                var removedGuestUsers = new List <GroupUser>();
                if (request.RemoveGuestUsers)
                {
                    var guestUsers = users.Where(u => u.UserType.Equals("Guest")).ToList();
                    for (int i = 0; i < guestUsers.Count; i++)
                    {
                        var guestUser = guestUsers[i];
                        log.Info($"Retrieving unified membership for user {guestUser.Id}");
                        var memberOfPage  = await client.Users[guestUser.Id].MemberOf.Request().GetAsync();
                        var unifiedGroups = memberOfPage.CurrentPage.Where(p => p.GetType() == typeof(Group)).Cast <Group>().ToList().Where(g => g.GroupTypes.Contains("Unified")).ToList();
                        if (unifiedGroups.Count == 0)
                        {
                            log.Info($"Removing guest user {guestUser.Id}");
                            await client.Users[guestUser.Id].Request().DeleteAsync();
                            removedGuestUsers.Add(guestUser);
                        }
                    }
                }

                var removeGroupMembersResponse = new RemoveGroupMembersResponse {
                    RemovedMembers    = users,
                    RemovedGuestUsers = removedGuestUsers
                };

                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <RemoveGroupMembersResponse>(removeGroupMembersResponse, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
        static async Task <string> GetUniqueMailAlias(CreateGroupRequest request)
        {
            string name         = string.IsNullOrEmpty(request.Alias) ? request.Name : request.Alias;
            string prefix       = request.Prefix;
            string suffix       = request.Suffix;
            string mailNickname = ReRemoveIllegalChars.Replace(name, "").ToLower();

            prefix = ReRemoveIllegalChars.Replace(prefix + "", "").ToLower();
            suffix = ReRemoveIllegalChars.Replace(suffix + "", "").ToLower();

            string prefixSeparator = string.Empty;

            if (!string.IsNullOrWhiteSpace(prefix) && request.UsePrefixInMailAlias)
            {
                prefixSeparator = string.IsNullOrWhiteSpace(request.PrefixSeparator) ? "-" : request.PrefixSeparator;
            }
            string suffixSeparator = string.Empty;

            if (!string.IsNullOrWhiteSpace(suffix) && request.UseSuffixInMailAlias)
            {
                suffixSeparator = string.IsNullOrWhiteSpace(request.SuffixSeparator) ? "-" : request.SuffixSeparator;
            }

            int maxCharsInEmail = 40 - prefix.Length - prefixSeparator.Length - suffixSeparator.Length - suffix.Length;

            if (mailNickname.Length > maxCharsInEmail)
            {
                mailNickname = mailNickname.Substring(0, maxCharsInEmail);
            }

            mailNickname = $"{prefix}{prefixSeparator}{mailNickname}{suffixSeparator}{suffix}";

            if (string.IsNullOrWhiteSpace(mailNickname))
            {
                mailNickname = new Random().Next(0, 9).ToString();
            }

            GraphServiceClient client = ConnectADAL.GetGraphClient();

            while (true)
            {
                IGraphServiceGroupsCollectionPage groupExist = await client.Groups.Request()
                                                               .Filter($"groupTypes/any(grp: grp eq 'Unified') and MailNickname eq '{mailNickname}'").Top(1)
                                                               .GetAsync();

                if (groupExist.Count > 0)
                {
                    string number = new Random().Next(0, 9).ToString();
                    if (string.IsNullOrWhiteSpace(suffixSeparator + suffix))
                    {
                        mailNickname += new Random().Next(0, 9).ToString();
                    }
                    else
                    {
                        int suffixIdx = mailNickname.IndexOf(suffixSeparator + suffix);
                        mailNickname = mailNickname.Insert(suffixIdx, number);
                    }
                }
                else
                {
                    break;
                }
            }
            return(mailNickname);
        }
Exemple #12
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] CreateGroupRequest request, TraceWriter log)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Name))
                {
                    throw new ArgumentException("Parameter cannot be null", "Name");
                }
                if (string.IsNullOrWhiteSpace(request.Description))
                {
                    throw new ArgumentException("Parameter cannot be null", "Description");
                }
                string mailNickName = await GetUniqueMailAlias(request);

                string             displayName = GetDisplayName(request);
                GraphServiceClient client      = ConnectADAL.GetGraphClient(GraphEndpoint.Beta);
                var newGroup = new Group
                {
                    DisplayName     = displayName,
                    Description     = GetDescription(request.Description, 1000),
                    MailNickname    = mailNickName,
                    MailEnabled     = true,
                    SecurityEnabled = false,
                    Visibility      = request.Public ? "Public" : "Private",
                    GroupTypes      = new List <string> {
                        "Unified"
                    },
                    Classification = request.Classification
                };
                var addedGroup = await client.Groups.Request().AddAsync(newGroup);

                var createGroupResponse = new CreateGroupResponse
                {
                    GroupId     = addedGroup.Id,
                    DisplayName = displayName,
                    Mail        = addedGroup.Mail
                };
                try
                {
                    if (!request.AllowToAddGuests)
                    {
                        var groupUnifiedGuestSetting = new GroupSetting()
                        {
                            DisplayName = "Group.Unified.Guest",
                            TemplateId  = "08d542b9-071f-4e16-94b0-74abb372e3d9",
                            Values      = new List <SettingValue> {
                                new SettingValue()
                                {
                                    Name = "AllowToAddGuests", Value = "false"
                                }
                            }
                        };
                        log.Info($"Setting setting in Group.Unified.Guest (08d542b9-071f-4e16-94b0-74abb372e3d9), AllowToAddGuests = false");
                        await client.Groups[addedGroup.Id].Settings.Request().AddAsync(groupUnifiedGuestSetting);
                    }
                }
                catch (Exception e)
                {
                    log.Error($"Error setting AllowToAddGuests for group {addedGroup.Id}: {e.Message }\n\n{e.StackTrace}");
                }
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <CreateGroupResponse>(createGroupResponse, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }