示例#1
0
        public async Task <UsersModel> GetDeletedUser()
        {
            UsersModel usersModel = new UsersModel();
            var        client     = GraphClientUtility.GetGraphServiceClient();

            if (client == null)
            {
                return(usersModel);
            }

            var delUserList = await client.Directory.DeletedItems["microsoft.graph.user"].Request().GetAsync();

            var delUsers = JArray.Parse(delUserList.AdditionalData["value"].ToString()).ToList();

            if (delUsers != null)
            {
                foreach (var user in delUsers)
                {
                    UserModel userModel = GraphClientUtility.ConvertDeletedGraphUserToUserModel(user, null);
                    usersModel.Users.Add(userModel);
                }
            }

            return(usersModel);
        }
示例#2
0
        private async Task <IDictionary <string, string> > FetchGroups()
        {
            Dictionary <string, string> retVal = null;

            try
            {
                _logger.LogInfo("FetchGroups-GetGroups: Getting group detail from Azure AD B2C");

                var _graphServiceClient = GraphClientUtility.GetGraphServiceClient();
                var groupList           = await _graphServiceClient.Groups.Request().Select(e => new { e.DisplayName, e.Id }).GetAsync();

                if (groupList != null)
                {
                    _logger.LogInfo($"Found {groupList.Count} group from Azure AD B2C");
                    retVal = new Dictionary <string, string>();
                    foreach (var group in groupList.OrderBy(x => x.DisplayName))
                    {
                        if (!retVal.ContainsKey(group.DisplayName))
                        {
                            retVal.Add(group.DisplayName, group.Id);
                        }
                    }
                }

                _logger.LogInfo("FetchGroups-GetGroups: Completed getting the group detail from Azure AD B2C");
            }
            catch (Exception ex)
            {
                _logger.LogError("FetchGroups-GetGroups: Exception occured....");
                _logger.LogError(ex);
                throw ex;
            }
            return(retVal);
        }
示例#3
0
        public async Task <GroupModel> GetGroup(string id)
        {
            try
            {
                var groupModel = new GroupModel();

                if (string.IsNullOrEmpty(id) || string.IsNullOrWhiteSpace(id))
                {
                    _logger.LogError("GroupService-GetGroup: Id cannot be empty");
                    return(null);
                }

                _logger.LogInfo($"GroupService-GetGroup: [Started] to get detail for group id {id} from Azure AD B2C");

                var client = GraphClientUtility.GetGraphServiceClient();

                if (client == null)
                {
                    _logger.LogError("GroupService-GetGroup: Unable to create object for graph client");
                    return(null);
                }

                var group = await client.Groups[id].Request().GetAsync();

                if (group != null)
                {
                    _logger.LogInfo($"GroupService-GetGroup: Fetched the group detail for id {id} from Azure AD B2C");
                    groupModel = GraphClientUtility.ConvertGraphGroupToGroupModel(group, _logger);

                    var members = await client.Groups[id].Members.Request().Select(e => new { e.Id }).GetAsync();
                    if (members != null)
                    {
                        groupModel.NoOfMembers = members.Count();
                    }

                    var owners = await client.Groups[id].Owners.Request().Select(e => new { e.Id }).GetAsync();
                    if (owners != null)
                    {
                        groupModel.NoOfOwners = owners.Count();
                    }
                }


                _logger.LogInfo($"GroupService-GetGroup: [Completed] to get detail for group id {id} from Azure AD B2C");
                return(groupModel);
            }
            catch (ServiceException ex)
            {
                _logger.LogError("GroupService-GetGroup: Exception occured....");
                _logger.LogError(ex);
                throw ex;
            }
        }
示例#4
0
        public async Task AddGroupOwners(GroupOwnerAssignModel groupOwnerAssign)
        {
            try
            {
                if (groupOwnerAssign == null)
                {
                    _logger.LogError("GroupOwnerService-AddGroupOwners: Group owner cannot be null...");
                    return;
                }

                _logger.LogInfo("GroupOwnerService-AddGroupOwners: [Started] assigning owner(s) to group in Azure AD B2C");

                if (!string.IsNullOrEmpty(groupOwnerAssign.GroupId) && groupOwnerAssign.SelectedOwners.Any())
                {
                    var client = GraphClientUtility.GetGraphServiceClient();
                    if (client == null)
                    {
                        _logger.LogError("GroupOwnerService-AddGroupOwners: Unable to create object for graph client ");
                        return;
                    }

                    // Get all user from Graph
                    var users = await client.Users.Request().GetAsync();

                    if (users != null)
                    {
                        var assigningUsers = users.Where(x => groupOwnerAssign.SelectedOwners.Contains(x.Id)).ToList();
                        if (assigningUsers != null)
                        {
                            foreach (var assignUser in assigningUsers)
                            {
                                try
                                {
                                    await client.Groups[groupOwnerAssign.GroupId].Owners.References.Request().AddAsync(assignUser);
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogError($"GroupOwnerService-AddGroupOwners: unable to assign owner [{assignUser.UserPrincipalName}] to the group [id:{groupOwnerAssign.GroupId}]");
                                    _logger.LogError(ex);
                                }
                            }
                        }
                    }
                }

                _logger.LogInfo("GroupOwnerService-AddGroupOwners: [Completed] assigning owner(s) to group in Azure AD B2C");
            }
            catch (Exception ex)
            {
                _logger.LogError("GroupMemberService-AddGroupOwners: Exception occured....");
                _logger.LogError(ex);
            }
        }
        public async Task <List <GroupAssigned> > AssignUserToGroup(UserGroup userGroup)
        {
            List <GroupAssigned> retVal = null;

            try
            {
                _logger.LogInfo("UserGroupController-AssignUserToGroup: [Started] assigning group for user in Azure AD B2C");

                var newUser  = userGroup.User;
                var allGroup = userGroup.AllGroups;
                var client   = GraphClientUtility.GetGraphServiceClient();
                retVal = new List <GroupAssigned>();
                foreach (var group in userGroup.Groups)
                {
                    var groupAssigned = new GroupAssigned();
                    try
                    {
                        groupAssigned.GroupName = group;

                        if (group.StartsWith($"{CareStreamConst.Owner}{CareStreamConst.Dash}"))
                        {
                            await client.Groups[allGroup[group.Replace($"{CareStreamConst.Owner}{CareStreamConst.Dash}", "")]].Owners.References.Request().AddAsync(newUser);
                        }
                        else if (group.StartsWith($"{CareStreamConst.Member}{CareStreamConst.Dash}"))
                        {
                            await client.Groups[allGroup[group.Replace($"{CareStreamConst.Member}{CareStreamConst.Dash}", "")]].Members.References.Request().AddAsync(newUser);
                        }
                        else
                        {
                            await client.Groups[allGroup[group.Replace($"{CareStreamConst.Member}{CareStreamConst.Dash}", "")]].Members.References.Request().AddAsync(newUser);
                        }

                        groupAssigned.IsGroupAssigned = true;
                    }
                    catch (Exception ex)
                    {
                        groupAssigned.IsGroupAssigned = false;
                        _logger.LogError($"UserGroupController-Post: Unable to assign group {group} for user {newUser.DisplayName} - Id: {newUser.Id}");
                        _logger.LogError(ex);
                    }
                    retVal.Add(groupAssigned);
                }

                _logger.LogInfo("UserGroupController-AssignUserToGroup: [Completed] assigning group for user in Azure AD B2C");
            }
            catch (Exception ex)
            {
                _logger.LogError("UserGroupController-Post: Exception occured....");
                _logger.LogError(ex);
            }
            return(retVal);
        }
示例#6
0
        public async Task <List <GroupAssignModel> > BuildGroupOwnerMember()
        {
            var groupAssignModel = new List <GroupAssignModel>();

            try
            {
                _logger.LogInfo("GroupService-BuildGroupOwnerMember: [Started] to get detail list of user to build group owner and member");

                var _graphServiceClient = GraphClientUtility.GetGraphServiceClient();

                if (_graphServiceClient == null)
                {
                    _logger.LogError("GroupService-BuildGroupOwnerMember: Unable to create object for graph client");
                    return(null);
                }

                var taskGroupOwnerMember = await GetNewGroupDefaultOwnerMember();

                if (taskGroupOwnerMember != null)
                {
                    if (taskGroupOwnerMember.Any())
                    {
                        var ownerAssignModel = new GroupAssignModel
                        {
                            AssignFor = CareStreamConst.Owner
                        };
                        var memberAssignModel = new GroupAssignModel
                        {
                            AssignFor = CareStreamConst.Member
                        };

                        foreach (var aDict in taskGroupOwnerMember.OrderBy(x => x.Value))
                        {
                            ownerAssignModel.AssignList.Add(aDict.Key, aDict.Value);
                            memberAssignModel.AssignList.Add(aDict.Key, aDict.Value);
                        }

                        groupAssignModel.Add(ownerAssignModel);
                        groupAssignModel.Add(memberAssignModel);
                    }
                }

                _logger.LogInfo("GroupService-BuildGroupOwnerMember: [Completed] to getting detail list of user to build group owner and member");
            }
            catch (ServiceException ex)
            {
                _logger.LogError("GroupService-BuildGroupOwnerMember: Exception occured....");
                _logger.LogError(ex);
            }
            return(groupAssignModel);
        }
示例#7
0
        public async Task RemoveGroupOwners(GroupOwnerAssignModel val)
        {
            try
            {
                if (val == null)
                {
                    _logger.LogError("GroupOwnerService-RemoveGroupOwners: Input value cannot be empty");
                    return;
                }

                var groupId = val.GroupId;
                if (!string.IsNullOrEmpty(groupId))
                {
                    GraphServiceClient client = GraphClientUtility.GetGraphServiceClient();
                    if (client == null)
                    {
                        _logger.LogError("GroupOwnerService-RemoveGroupOwners: Unable to create object for graph client");
                        return;
                    }

                    _logger.LogInfo($"GroupOwnerService-RemoveGroupOwners: [Started] unassigning owner(s) for group [Id:{groupId}]");

                    foreach (var ownerId in val.SelectedOwners)
                    {
                        try
                        {
                            _logger.LogInfo($"GroupOwnerService-RemoveGroupOwners: Removing owner [{ownerId}] from group [Id:{groupId}] on Azure AD B2C");

                            await client.Groups[groupId].Owners[ownerId].Reference.Request().DeleteAsync();

                            _logger.LogInfo($"GroupOwnerService-RemoveGroupOwners: Removed member [{ownerId}] from group [Id:{groupId}] on Azure AD B2C");
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError($"GroupOwnerService-RemoveGroupOwners: Exception occured while unassigning owner [Id:{ownerId}] for group  [Id:{groupId}] ");
                            _logger.LogError(ex);
                        }
                    }

                    _logger.LogInfo($"GroupOwnerService-RemoveGroupOwners: [Completed] unassigning owner(s) from group [Id:{val.GroupId}]");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("GroupOwnersController-RemoveGroupOwners: Exception occured....");
                _logger.LogError(ex);
                throw ex;
            }
        }
示例#8
0
        public async Task <UserDropDownModel> GetUserDropDownAsync()
        {
            UserDropDownModel retVal = null;

            try
            {
                retVal = new UserDropDownModel();

                var client = GraphClientUtility.GetGraphServiceClient();

                var loadUserDropDownTasks = new Task[]
                {
                    Task.Run(() => {
                        PasswordService.Logger = _logger;
                        retVal.AutoPassword    = PasswordService.GenerateNewPassword(GetRandomNumber(),
                                                                                     GetRandomNumber(), GetRandomNumber(), GetRandomNumber());
                    }),
                    Task.Run(() => {
                        GroupService groupService = new GroupService(_logger, null, null);
                        retVal.Groups             = groupService.GetGroups();
                    }),
                    Task.Run(() => retVal.UserRoles = GetUserRoles()),
                    Task.Run(() =>
                    {
                        CountryService countryService = new CountryService(_logger);
                        var countryResult             = countryService.GetCountries();

                        if (countryResult != null)
                        {
                            retVal.UserLocation = countryResult.Result.CountryModel;
                        }
                    }),
                    Task.Run(() => retVal.UserTypes               = GetUserTypes()),
                    Task.Run(() => retVal.UserLanguages           = GetUserLanguage()),
                    Task.Run(() => retVal.UserBusinessDepartments = GetUserBusinessDepartments()),
                };

                await Task.WhenAll(loadUserDropDownTasks);
            }
            catch (Exception ex)
            {
                retVal = null;
                _logger.LogError("UserService-GetUserDropDownAsync: Exception occured....");
                _logger.LogError(ex);
            }
            return(retVal);
        }
示例#9
0
        public async Task <List <GroupModel> > GetGroupDetails()
        {
            List <GroupModel> retVal = new List <GroupModel>();

            try
            {
                _logger.LogInfo("GroupService-GetGroups: Getting group detail from Azure AD B2C");

                var _graphServiceClient = GraphClientUtility.GetGraphServiceClient();
                var groupDetails        = await _graphServiceClient.Groups.Request().GetAsync();

                if (groupDetails != null)
                {
                    foreach (var groupItem in groupDetails)
                    {
                        try
                        {
                            var groupModel = GraphClientUtility.ConvertGraphGroupToGroupModel(groupItem, _logger);

                            if (groupItem.GroupTypes != null)
                            {
                                if (groupItem.GroupTypes.Any())
                                {
                                    groupModel.GroupType = string.Join('|', groupItem.GroupTypes);
                                }
                            }
                            retVal.Add(groupModel);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError($"GroupService-GetGroups: failed to add group for group name {groupItem.DisplayName}");
                            _logger.LogError(ex);
                        }
                    }
                    retVal = retVal.OrderBy(x => x.DisplayName).ToList();
                }

                _logger.LogInfo("GroupService-GetGroups: Completed getting the group detail from Azure AD B2C");
            }
            catch (Exception ex)
            {
                _logger.LogError("GroupService-GetGroups: Exception occured....");
                _logger.LogError(ex);
                throw ex;
            }
            return(retVal);
        }
示例#10
0
        public async Task <UsersModel> GetFilteredUsers(string filter)
        {
            UsersModel usersModel = new UsersModel();

            var client   = GraphClientUtility.GetGraphServiceClient();
            var userList = await client.Users.Request().Filter($"startswith(displayName,'{filter}') or startswith(givenName,'{filter}') or startswith(surname,'{filter}') or startswith(mail,'{filter}') or startswith(userPrincipalName,'{filter}')").GetAsync();

            if (userList != null)
            {
                foreach (var user in userList)
                {
                    UserModel userModel = GraphClientUtility.ConvertGraphUserToUserModel(user, null);
                    usersModel.Users.Add(userModel);
                }
            }

            return(usersModel);
        }
示例#11
0
        public async Task RemoveUser(List <string> userIdsToDelete)
        {
            try
            {
                if (userIdsToDelete == null)
                {
                    _logger.LogError("UserService-RemoveUser: Input value cannot be empty");
                    return;
                }

                GraphServiceClient client = GraphClientUtility.GetGraphServiceClient();
                if (client == null)
                {
                    _logger.LogError("UserService-RemoveUser: Unable to create object for graph client");
                    return;
                }

                foreach (var id in userIdsToDelete)
                {
                    try
                    {
                        _logger.LogInfo($"UserService-RemoveUser: [Started] removing user for id [{id}] on Azure AD B2C");

                        await client.Users[id].Request().DeleteAsync();

                        _logger.LogInfo($"UserService-RemoveUser: [Completed] removing user [{id}] on Azure AD B2C");
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"UserService-RemoveUser: Exception occured while removing user for id [{id}]");
                        _logger.LogError(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("UserService-RemoveUser: Exception occured....");
                _logger.LogError(ex);
                throw ex;
            }
        }
        private async Task <string> CheckIfExtensionExist(string schemaName)
        {
            var retVal = string.Empty;

            try
            {
                var client = GraphClientUtility.GetGraphServiceClient();

                if (client == null)
                {
                    _logger.LogError("UserAttributeService-CheckIfExtensionExist: Unable to create proxy for the Azure AD B2C graph client");
                    return(retVal);
                }

                var schemaExtensions = await client.SchemaExtensions.Request().GetAsync();

                while (schemaExtensions.NextPageRequest != null)
                {
                    foreach (SchemaExtension extension in schemaExtensions.CurrentPage)
                    {
                        if (extension.Id.Contains(schemaName))
                        {
                            retVal = extension.Id;
                            break;
                        }
                    }
                    if (!string.IsNullOrEmpty(retVal))
                    {
                        break;
                    }
                    schemaExtensions = await schemaExtensions.NextPageRequest.GetAsync();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("UserAttributeService-CheckIfExtensionExist: Exception occured....");
                _logger.LogError(ex);
            }
            return(retVal);
        }
示例#13
0
        public async Task <UsersModel> GetUser()
        {
            UsersModel usersModel = new UsersModel();
            var        client     = GraphClientUtility.GetGraphServiceClient();

            if (client == null)
            {
                return(usersModel);
            }

            var userList = await client.Users.Request().GetAsync();

            if (userList != null)
            {
                foreach (var user in userList)
                {
                    UserModel userModel = GraphClientUtility.ConvertGraphUserToUserModel(user, null);
                    usersModel.Users.Add(userModel);
                }
            }
            return(usersModel);
        }
示例#14
0
        public async Task <List <GroupModel> > GetDetailGroupList()
        {
            try
            {
                var _graphServiceClient = GraphClientUtility.GetGraphServiceClient();

                if (_graphServiceClient == null)
                {
                    return(null);
                }

                var groupsModel = await GetGroupDetails();

                return(groupsModel);
            }
            catch (ServiceException ex)
            {
                _logger.LogError("GroupService-GetDetailGroupList: Exception occured....");
                _logger.LogError(ex);
                throw ex;
            }
        }
示例#15
0
        public async Task <UserModel> GetUser(string id)
        {
            var userModel = new UserModel();

            try
            {
                var client = GraphClientUtility.GetGraphServiceClient();

                var user = await client.Users[id].Request().GetAsync();

                var extensions = await client.Users[id].Extensions.Request().GetAsync();
                user.Extensions = extensions;

                userModel            = GraphClientUtility.ConvertGraphUserToUserModel(user, null);
                userModel.SignInName = user.UserPrincipalName;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex);
            }

            return(userModel);
        }
示例#16
0
        public async Task <GroupOwnerModel> GetGroupOwners(string id)
        {
            try
            {
                if (string.IsNullOrEmpty(id) || string.IsNullOrWhiteSpace(id))
                {
                    _logger.LogError("GroupOwnerService-GetGroupOwners: Id cannot be empty");
                    return(null);
                }

                var groupOwnerModel = new GroupOwnerModel
                {
                    GroupId = id
                };

                _logger.LogInfo($"GroupOwnerService-GetGroupOwners: [Started] to get member detail for group id {id} from Azure AD B2C");

                var client = GraphClientUtility.GetGraphServiceClient();

                if (client == null)
                {
                    _logger.LogError("GroupOwnerService-GetGroupOwners: Unable to create object for graph client");
                    return(null);
                }

                groupOwnerModel = await GetGroupOwnerAsync(id);

                _logger.LogInfo($"GroupOwnerService-GetGroupOwners: [Completed] to getting member detail for group id {id} from Azure AD B2C");
                return(groupOwnerModel);
            }
            catch (ServiceException ex)
            {
                _logger.LogError("GroupOwnerService-GetGroupOwners: Exception occured....");
                _logger.LogError(ex);
                throw ex;
            }
        }
示例#17
0
        private async Task <List <UserModel> > GetMembersForGroup(string groupId)
        {
            List <UserModel> retVal = new List <UserModel>();

            try
            {
                var members = await _graphServiceClient.Groups[groupId].Members.Request().GetAsync();
                if (members != null)
                {
                    foreach (var member in members)
                    {
                        try
                        {
                            if (!(member is User))
                            {
                                continue;
                            }

                            UserModel userModel = GraphClientUtility.ConvertGraphUserToUserModel((User)member, _logger);
                            retVal.Add(userModel);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError($"GroupService-GetMembersForGroup: Error adding group owner to the collection for owner {member.Id}");
                            _logger.LogError(ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("GroupService-GetMembersForGroup: Exception occured....");
                _logger.LogError(ex);
                throw ex;
            }
            return(retVal);
        }
示例#18
0
        private async Task <Dictionary <string, string> > GetNewGroupDefaultOwnerMember()
        {
            Dictionary <string, string> retVal = null;

            try
            {
                var _graphServiceClient = GraphClientUtility.GetGraphServiceClient();
                var users = await _graphServiceClient.Users.Request().GetAsync();

                if (users != null)
                {
                    retVal = new Dictionary <string, string>();
                    foreach (var user in users.Where(x => !string.IsNullOrEmpty(x.UserPrincipalName)))
                    {
                        try
                        {
                            if (!retVal.ContainsKey(user.Id))
                            {
                                var value = string.IsNullOrEmpty(user.GivenName + user.Surname) ? user.UserPrincipalName : $"{user.GivenName} {user.Surname}";
                                retVal.Add(user.Id, value);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError($"GroupService-GetGroupOwnerMemberAsync: unable to add user in the group owner and member collection for user {user.UserPrincipalName}");
                            _logger.LogError(ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("GroupService-GetNewGroupDefaultOwnerMember: Exception occured....");
                _logger.LogError(ex);
            }
            return(retVal);
        }
示例#19
0
        public async Task SendInvite(InviteUser user)
        {
            GraphServiceClient client = GraphClientUtility.GetGraphServiceClient();

            var invitation = new Invitation
            {
                InvitedUserEmailAddress = user.InvitedUserEmailAddress,
                InviteRedirectUrl       = "http://localhost:57774",
                InvitedUserDisplayName  = user.InvitedUserDisplayName,
                InvitedUserMessageInfo  = new InvitedUserMessageInfo
                {
                    CustomizedMessageBody = user.CustomizedMessageBody
                },
                InvitedUserType       = user.InvitedUserType,
                SendInvitationMessage = true,
                InvitedUser           = user.InvitedUser,
                Status          = user.Status,
                InviteRedeemUrl = user.InviteRedeemUrl
            };

            await client.Invitations
            .Request()
            .AddAsync(invitation);
        }
示例#20
0
        public async Task Update(UserModel user)
        {
            try
            {
                if (string.IsNullOrEmpty(user.UserPrincipalName) && string.IsNullOrEmpty(user.Id))
                {
                    var errorMessage = $"Cannot update user. User id [{user.Id}] required field is missing.";
                    _logger.LogWarn(errorMessage);
                }

                var client = GraphClientUtility.GetGraphServiceClient();
                if (client == null)
                {
                    var errorMessage = $"[User Update] Unable to get the proxy for Graph client for user [{user.UserPrincipalName}]";
                    _logger.LogWarn(errorMessage);
                }

                #region Custom Attributes

                user.CustomAttributes = new Dictionary <string, string>();

                if (user.RolesAA != null)
                {
                    if (user.RolesAA.Any())
                    {
                        user.Roles_C = string.Join(CareStreamConst.Pipe, user.RolesAA);
                        user.CustomAttributes.Add(CareStreamConst.Roles_C, user.Roles_C);
                    }
                }

                if (user.UserTypeAA != null)
                {
                    if (user.UserTypeAA.Any())
                    {
                        user.UserType_C = string.Join(CareStreamConst.Pipe, user.UserTypeAA);
                        user.CustomAttributes.Add(CareStreamConst.UserType_C, user.UserType_C);
                    }
                }

                if (user.UserBusinessDepartmentAA != null)
                {
                    if (user.UserBusinessDepartmentAA.Any())
                    {
                        user.UserBusinessDepartment_C = string.Join(CareStreamConst.Pipe, user.UserBusinessDepartmentAA);
                        user.CustomAttributes.Add(CareStreamConst.UserBusinessDepartment_C, user.UserBusinessDepartment_C);
                    }
                }

                if (!string.IsNullOrEmpty(user.Language_C))
                {
                    user.CustomAttributes.Add(CareStreamConst.Language_C, user.Language_C);
                }

                #endregion

                var b2cExtensionAppClientId = GraphClientUtility.b2cExtensionAppClientId;

                var userService  = new UserService(_logger);
                var updatingUser = userService.BuildUserForUpdate(user, b2cExtensionAppClientId);

                var result = await client.Users[user.Id].Request().UpdateAsync(updatingUser);

                if (result == null)
                {
                    var errorMessage = $"Failed to update user for [{user.UserPrincipalName}]";
                    _logger.LogWarn(errorMessage);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"User Update :error updating user for user id {user.Id}");
                _logger.LogError(ex);
            }
        }
示例#21
0
        public async Task Create(UserModel user)
        {
            #region setting properites

            user.DisplayName = $"{user.GivenName} {user.Surname}";

            user.AutoGeneratePassword = string.IsNullOrEmpty(user.Password) ? true : false;

            #region Custom Attributes

            user.CustomAttributes = new Dictionary <string, string>();

            if (user.RolesAA != null)
            {
                if (user.RolesAA.Any())
                {
                    user.Roles_C = string.Join(CareStreamConst.Pipe, user.RolesAA);
                    user.CustomAttributes.Add(CareStreamConst.Roles_C, user.Roles_C);
                }
            }

            if (user.UserTypeAA != null)
            {
                if (user.UserTypeAA.Any())
                {
                    user.UserType_C = string.Join(CareStreamConst.Pipe, user.UserTypeAA);
                    user.CustomAttributes.Add(CareStreamConst.UserType_C, user.UserType_C);
                }
            }

            if (user.UserBusinessDepartmentAA != null)
            {
                if (user.UserBusinessDepartmentAA.Any())
                {
                    user.UserBusinessDepartment_C = string.Join(CareStreamConst.Pipe, user.UserBusinessDepartmentAA);
                    user.CustomAttributes.Add(CareStreamConst.UserBusinessDepartment_C, user.UserBusinessDepartment_C);
                }
            }

            if (!string.IsNullOrEmpty(user.Language_C))
            {
                user.CustomAttributes.Add(CareStreamConst.Language_C, user.Language_C);
            }

            #endregion


            #endregion

            GraphServiceClient client = GraphClientUtility.GetGraphServiceClient();


            var tenantId = GraphClientUtility.TenantId;
            var b2cExtensionAppClientId = GraphClientUtility.b2cExtensionAppClientId;

            var newUser = BuildUserForCreation(user, tenantId, b2cExtensionAppClientId);

            var result = await client.Users.Request().AddAsync(newUser);

            if (result != null)
            {
                newUser.Id = result.Id;

                #region Assign group(s)

                if (user.Groups != null)
                {
                    if (user.Groups.Any())
                    {
                        AssignGroupsToUser(client, result, user.Groups);
                    }
                }

                #endregion
            }
        }
        public async Task <UserAttributeModel> GetUserAttribute()
        {
            try
            {
                var client = GraphClientUtility.GetGraphServiceClient();

                if (client == null)
                {
                    _logger.LogError("UserAttributeService-GetUserAttribute: Unable to create proxy for the Azure AD B2C graph client");
                    return(null);
                }
                _logger.LogInfo("UserAttributeService-GetUserAttribute: [Started] to fetch user attribute in Azure AD B2C");

                var extensionName = GraphClientUtility.ExtensionName;

                var schemaExtensions = await client.SchemaExtensions.Request().GetAsync();


                var userAttributeModel = new UserAttributeModel();
                var extensionSchemas   = new List <ExtensionSchema>();
                while (schemaExtensions.NextPageRequest != null)
                {
                    foreach (SchemaExtension extension in schemaExtensions.CurrentPage)
                    {
                        try
                        {
                            if (extension.Id.Contains(extensionName))
                            {
                                userAttributeModel.Id = extension.Id;

                                foreach (var item in extension.Properties)
                                {
                                    try
                                    {
                                        ExtensionSchema extensionSchema = new ExtensionSchema();

                                        extensionSchema.Name     = item.Name;
                                        extensionSchema.DataType = item.Type;
                                        extensionSchemas.Add(extensionSchema);
                                    }
                                    catch (Exception ex)
                                    {
                                        _logger.LogError($"ExtensionController-GetExtensions: fail to add extension [name:{item.Name}] to collection ");
                                        _logger.LogError(ex);
                                    }
                                }
                                userAttributeModel.ExtensionSchemas = extensionSchemas;
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError($"ExtensionController-GetExtensions: fail to add extension [name:{extension.Id}] to collection ");
                            _logger.LogError(ex);
                        }
                    }


                    schemaExtensions = await schemaExtensions.NextPageRequest.GetAsync();
                }

                return(userAttributeModel);
            }
            catch (Exception ex)
            {
                _logger.LogError("ExtensionController-GetExtensions: Exception occured....");
                _logger.LogError(ex);
            }
            return(null);
        }
示例#23
0
        public async Task <GroupModel> CreateGroup(GroupModel groupModel)
        {
            try
            {
                _logger.LogInfo("GroupService-CreateGroup: [Started] creation of group in Azure AD B2C");

                if (groupModel == null)
                {
                    _logger.LogError("GroupService-CreateGroup: Group Model cannot be null...");
                    return(null);
                }

                var client = GraphClientUtility.GetGraphServiceClient();
                if (client == null)
                {
                    _logger.LogError("GroupService-CreateGroup: Unable to create object for graph client ");
                    return(null);
                }

                var group = BuildGroup(groupModel);

                var newGroup = await client.Groups.Request().AddAsync(group);

                var newGroupModel = GraphClientUtility.ConvertGraphGroupToGroupModel(newGroup, _logger);

                if (newGroupModel != null)
                {
                    var groupId = newGroup.Id;
                    if (!string.IsNullOrEmpty(groupId))
                    {
                        #region Assign Members

                        if (groupModel.OwnerSelected.Any())
                        {
                            _logger.LogInfo($"GroupService-CreateGroup: assigning {groupModel.OwnerSelected.Count()} owner(s) for group {newGroupModel.DisplayName} in Azure AD B2C");

                            var groupOwnerAssign = new GroupOwnerAssignModel
                            {
                                GroupId        = groupId,
                                SelectedOwners = groupModel.OwnerSelected
                            };

                            await _groupOwnerService.AddGroupOwners(groupOwnerAssign);

                            _logger.LogInfo($"GroupService-CreateGroup: assigned {groupModel.OwnerSelected.Count()} owner(s) for group {newGroupModel.DisplayName} in Azure AD B2C");
                        }

                        if (groupModel.MemberSelected.Any())
                        {
                            _logger.LogInfo($"GroupService-CreateGroup: assigning {groupModel.MemberSelected.Count()} member(s) for group {newGroupModel.DisplayName} in Azure AD B2C");

                            var groupMemberAssign = new GroupMemberAssignModel
                            {
                                GroupId         = groupId,
                                SelectedMembers = groupModel.MemberSelected
                            };

                            await _groupMemberService.AddGroupMembers(groupMemberAssign);

                            _logger.LogInfo($"GroupService-CreateGroup: assigned {groupModel.MemberSelected.Count()} member(s) for group {newGroupModel.DisplayName} in Azure AD B2C");
                        }
                        #endregion
                    }
                }

                _logger.LogInfo("GroupService-CreateGroup: [Completed] creation of group in Azure AD B2C");
                return(newGroupModel);
            }
            catch (Exception ex)
            {
                _logger.LogError("GroupService-CreateGroup: Exception occured....");
                _logger.LogError(ex);
                throw ex;
            }
        }
        public async Task UpsertUserAttributes(ExtensionModel extension)
        {
            try
            {
                _logger.LogInfo("UserAttributeService-UpsertUserAttributes: [Started] creation of user attribute in Azure AD B2C");

                if (extension == null)
                {
                    _logger.LogError("UserAttributeService-UpsertUserAttributes: Input cannot be null");
                    return;
                }


                #region Validation

                if (extension.TargetObjects == null)
                {
                    _logger.LogError("UserAttributeService-UpsertUserAttributes: Target Object for creation of custom attribute cannot be empty");
                    return;
                }

                if (string.IsNullOrEmpty(extension.Name) &&
                    string.IsNullOrEmpty(extension.DataType) &&
                    !extension.TargetObjects.Any())
                {
                    _logger.LogError("UserAttributeService-UpsertUserAttributes: Input [Name | Data Type | Target Obejct] for creation of custom attribute cannot be empty");
                    return;
                }
                #endregion

                var client = GraphClientUtility.GetGraphServiceClient();

                if (client == null)
                {
                    _logger.LogError("UserAttributeService-UpsertUserAttributes: Unable create graph proxy to access Azure AD B2C");
                    return;
                }


                var taskSchemaName = await CheckIfExtensionExist(GraphClientUtility.ExtensionName);

                var schemaName = string.Empty;

                if (taskSchemaName != null)
                {
                    schemaName = "";
                }

                if (string.IsNullOrEmpty(schemaName))
                {
                    //var schemaExtension = new SchemaExtension
                    //{
                    //    Id = GraphClientUtility.ExtensionName,
                    //    Description = extension.Description,
                    //    TargetTypes = extension.TargetObjects,
                    //    Properties = new List<ExtensionSchemaProperty>()
                    //    {
                    //        new ExtensionSchemaProperty
                    //        {
                    //            Name= extension.Name,
                    //            Type = extension.DataType
                    //        }
                    //    }
                    //};

                    var schemaExtension = new SchemaExtension
                    {
                        Id          = "prasadtest3vikas",
                        Description = "Prasad Learn training courses extensions",
                        Status      = "InDevelopment",
                        TargetTypes = new List <String>()
                        {
                            "User"
                        },
                        Properties = new List <ExtensionSchemaProperty>()
                        {
                            new ExtensionSchemaProperty
                            {
                                Name = "courseId",
                                Type = "Integer"
                            },
                            new ExtensionSchemaProperty
                            {
                                Name = "courseName",
                                Type = "String"
                            },
                            new ExtensionSchemaProperty
                            {
                                Name = "courseType",
                                Type = "String"
                            }
                        }
                    };

                    try
                    {
                        var response = await client.SchemaExtensions
                                       .Request()
                                       .AddAsync(schemaExtension);

                        var result = response;
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex);
                    }
                }
                else
                {
                    var schemaExtension = new SchemaExtension
                    {
                        TargetTypes = extension.TargetObjects,
                        Properties  = new List <ExtensionSchemaProperty>()
                        {
                            new ExtensionSchemaProperty
                            {
                                Name = extension.Name,
                                Type = extension.DataType
                            }
                        }
                    };
                    await client.SchemaExtensions[schemaName].Request().UpdateAsync(schemaExtension);
                }


                _logger.LogInfo("UserAttributeService-UpsertUserAttributes: [Completed] creation of user attribute in Azure AD B2C");
            }
            catch (Exception ex)
            {
                _logger.LogError("UserAttributeService-UpsertUserAttributes: Exception occured....");
                _logger.LogError(ex);
                throw ex;
            }
        }
示例#25
0
        private async Task <GroupOwnerModel> GetGroupOwnerAsync(string groupId)
        {
            GroupOwnerModel retVal = null;

            try
            {
                if (string.IsNullOrEmpty(groupId))
                {
                    _logger.LogError("GroupOwnerService-GetGroupOwnerAsync: Group Id cannot be null");
                    return(retVal);
                }
                _logger.LogInfo("GroupOwnerService-GetGroupOwnerAsync: Starting to get group owner from Azure AD B2C");


                retVal = new GroupOwnerModel
                {
                    GroupId = groupId
                };

                var _graphServiceClient = GraphClientUtility.GetGraphServiceClient();

                var tasks = new Task[]
                {
                    Task.Run(async() => {
                        Dictionary <string, string> ownersList = null;

                        var users = await _graphServiceClient.Users.Request().GetAsync();

                        if (users != null)
                        {
                            ownersList = new Dictionary <string, string>();
                            foreach (var user in users.Where(x => !string.IsNullOrEmpty(x.UserPrincipalName)))
                            {
                                try
                                {
                                    if (!ownersList.ContainsKey(user.Id))
                                    {
                                        var value = string.IsNullOrEmpty(user.GivenName + user.Surname) ? user.UserPrincipalName : $"{user.GivenName} {user.Surname}";
                                        ownersList.Add(user.Id, value);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogError($"GroupOwnerService-GetGroupOwnerMemberAsync: unable to add user in the group owner and member collection for user {user.UserPrincipalName}");
                                    _logger.LogError(ex);
                                }
                            }
                        }
                        if (ownersList != null)
                        {
                            retVal.Owners = new Dictionary <string, string>();
                            foreach (var aDict in ownersList)
                            {
                                retVal.Owners.Add(aDict.Key, aDict.Value);
                            }
                        }
                    }),
                    Task.Run(async() =>
                    {
                        List <UserModel> assignedOwners = new List <UserModel>();

                        var owners = await _graphServiceClient.Groups[groupId].Owners.Request().GetAsync();
                        if (owners != null)
                        {
                            foreach (var owner in owners)
                            {
                                try
                                {
                                    if (!(owner is User))
                                    {
                                        continue;
                                    }

                                    UserModel userModel = GraphClientUtility.ConvertGraphUserToUserModel((User)owner, _logger);
                                    assignedOwners.Add(userModel);
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogError($"GroupOwnerService-GetOwnersForGroupGetOwnersForGroup: Error adding group owner to the collection for owner {owner.Id}");
                                    _logger.LogError(ex);
                                }
                            }
                        }

                        if (assignedOwners != null)
                        {
                            retVal.AssignedOwners = assignedOwners.ToList <UserModel>();
                        }
                    })
                };

                await Task.WhenAll(tasks);

                if (retVal != null)
                {
                    if ((retVal.AssignedOwners != null) && (retVal.Owners != null))
                    {
                        var userIds = retVal.AssignedOwners.Select(x => x.Id).ToList();
                        if (retVal.Owners.Any() && userIds.Any())
                        {
                            var keys = retVal.Owners.Keys.Where(x => userIds.Contains(x)).ToList();
                            foreach (var key in keys)
                            {
                                retVal.Owners.Remove(key);
                            }
                        }
                    }
                }

                _logger.LogInfo("GroupOwnerService-GetGroupOwnerAsync: Completed getting the group owner from Azure AD B2C");
            }
            catch (Exception ex)
            {
                _logger.LogError("GroupOwnerService-GetGroupOwnerAsync: Exception occured....");
                _logger.LogError(ex);
                throw ex;
            }
            return(retVal);
        }